10b57cec5SDimitry Andric //===--- Format.cpp - Format C++ code -------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric ///
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// This file implements functions declared in Format.h. This will be
110b57cec5SDimitry Andric /// split into separate files as we go.
120b57cec5SDimitry Andric ///
130b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
140b57cec5SDimitry Andric 
150b57cec5SDimitry Andric #include "clang/Format/Format.h"
160b57cec5SDimitry Andric #include "AffectedRangeManager.h"
170b57cec5SDimitry Andric #include "ContinuationIndenter.h"
180b57cec5SDimitry Andric #include "FormatInternal.h"
190b57cec5SDimitry Andric #include "FormatTokenLexer.h"
200b57cec5SDimitry Andric #include "NamespaceEndCommentsFixer.h"
210b57cec5SDimitry Andric #include "SortJavaScriptImports.h"
220b57cec5SDimitry Andric #include "TokenAnalyzer.h"
230b57cec5SDimitry Andric #include "TokenAnnotator.h"
240b57cec5SDimitry Andric #include "UnwrappedLineFormatter.h"
250b57cec5SDimitry Andric #include "UnwrappedLineParser.h"
260b57cec5SDimitry Andric #include "UsingDeclarationsSorter.h"
270b57cec5SDimitry Andric #include "WhitespaceManager.h"
280b57cec5SDimitry Andric #include "clang/Basic/Diagnostic.h"
290b57cec5SDimitry Andric #include "clang/Basic/DiagnosticOptions.h"
300b57cec5SDimitry Andric #include "clang/Basic/SourceManager.h"
310b57cec5SDimitry Andric #include "clang/Lex/Lexer.h"
320b57cec5SDimitry Andric #include "clang/Tooling/Inclusions/HeaderIncludes.h"
330b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
340b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
350b57cec5SDimitry Andric #include "llvm/Support/Allocator.h"
360b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
370b57cec5SDimitry Andric #include "llvm/Support/Path.h"
380b57cec5SDimitry Andric #include "llvm/Support/Regex.h"
390b57cec5SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
400b57cec5SDimitry Andric #include "llvm/Support/YAMLTraits.h"
410b57cec5SDimitry Andric #include <algorithm>
420b57cec5SDimitry Andric #include <memory>
430b57cec5SDimitry Andric #include <mutex>
440b57cec5SDimitry Andric #include <string>
450b57cec5SDimitry Andric #include <unordered_map>
460b57cec5SDimitry Andric 
470b57cec5SDimitry Andric #define DEBUG_TYPE "format-formatter"
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric using clang::format::FormatStyle;
500b57cec5SDimitry Andric 
510b57cec5SDimitry Andric LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::RawStringFormat)
520b57cec5SDimitry Andric 
530b57cec5SDimitry Andric namespace llvm {
540b57cec5SDimitry Andric namespace yaml {
550b57cec5SDimitry Andric template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
560b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
570b57cec5SDimitry Andric     IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
580b57cec5SDimitry Andric     IO.enumCase(Value, "Java", FormatStyle::LK_Java);
590b57cec5SDimitry Andric     IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
600b57cec5SDimitry Andric     IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
610b57cec5SDimitry Andric     IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
620b57cec5SDimitry Andric     IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
630b57cec5SDimitry Andric     IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
640b57cec5SDimitry Andric     IO.enumCase(Value, "CSharp", FormatStyle::LK_CSharp);
650b57cec5SDimitry Andric   }
660b57cec5SDimitry Andric };
670b57cec5SDimitry Andric 
680b57cec5SDimitry Andric template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
690b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
700b57cec5SDimitry Andric     IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
710b57cec5SDimitry Andric     IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
720b57cec5SDimitry Andric     IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
730b57cec5SDimitry Andric     IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
740b57cec5SDimitry Andric     IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
750b57cec5SDimitry Andric   }
760b57cec5SDimitry Andric };
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
790b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
800b57cec5SDimitry Andric     IO.enumCase(Value, "Never", FormatStyle::UT_Never);
810b57cec5SDimitry Andric     IO.enumCase(Value, "false", FormatStyle::UT_Never);
820b57cec5SDimitry Andric     IO.enumCase(Value, "Always", FormatStyle::UT_Always);
830b57cec5SDimitry Andric     IO.enumCase(Value, "true", FormatStyle::UT_Always);
840b57cec5SDimitry Andric     IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
850b57cec5SDimitry Andric     IO.enumCase(Value, "ForContinuationAndIndentation",
860b57cec5SDimitry Andric                 FormatStyle::UT_ForContinuationAndIndentation);
870b57cec5SDimitry Andric   }
880b57cec5SDimitry Andric };
890b57cec5SDimitry Andric 
900b57cec5SDimitry Andric template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
910b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
920b57cec5SDimitry Andric     IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
930b57cec5SDimitry Andric     IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
940b57cec5SDimitry Andric     IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
950b57cec5SDimitry Andric   }
960b57cec5SDimitry Andric };
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
990b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
1000b57cec5SDimitry Andric     IO.enumCase(Value, "None", FormatStyle::SFS_None);
1010b57cec5SDimitry Andric     IO.enumCase(Value, "false", FormatStyle::SFS_None);
1020b57cec5SDimitry Andric     IO.enumCase(Value, "All", FormatStyle::SFS_All);
1030b57cec5SDimitry Andric     IO.enumCase(Value, "true", FormatStyle::SFS_All);
1040b57cec5SDimitry Andric     IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
1050b57cec5SDimitry Andric     IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly);
1060b57cec5SDimitry Andric     IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
1070b57cec5SDimitry Andric   }
1080b57cec5SDimitry Andric };
1090b57cec5SDimitry Andric 
1100b57cec5SDimitry Andric template <> struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
1110b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::ShortIfStyle &Value) {
1120b57cec5SDimitry Andric     IO.enumCase(Value, "Never", FormatStyle::SIS_Never);
1130b57cec5SDimitry Andric     IO.enumCase(Value, "Always", FormatStyle::SIS_Always);
1140b57cec5SDimitry Andric     IO.enumCase(Value, "WithoutElse", FormatStyle::SIS_WithoutElse);
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric     // For backward compatibility.
1170b57cec5SDimitry Andric     IO.enumCase(Value, "false", FormatStyle::SIS_Never);
1180b57cec5SDimitry Andric     IO.enumCase(Value, "true", FormatStyle::SIS_WithoutElse);
1190b57cec5SDimitry Andric   }
1200b57cec5SDimitry Andric };
1210b57cec5SDimitry Andric 
1220b57cec5SDimitry Andric template <> struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {
1230b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::ShortLambdaStyle &Value) {
1240b57cec5SDimitry Andric     IO.enumCase(Value, "None", FormatStyle::SLS_None);
1250b57cec5SDimitry Andric     IO.enumCase(Value, "false", FormatStyle::SLS_None);
1260b57cec5SDimitry Andric     IO.enumCase(Value, "Empty", FormatStyle::SLS_Empty);
1270b57cec5SDimitry Andric     IO.enumCase(Value, "Inline", FormatStyle::SLS_Inline);
1280b57cec5SDimitry Andric     IO.enumCase(Value, "All", FormatStyle::SLS_All);
1290b57cec5SDimitry Andric     IO.enumCase(Value, "true", FormatStyle::SLS_All);
1300b57cec5SDimitry Andric   }
1310b57cec5SDimitry Andric };
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
1340b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value) {
1350b57cec5SDimitry Andric     IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
1360b57cec5SDimitry Andric     IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
1370b57cec5SDimitry Andric     IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
1380b57cec5SDimitry Andric   }
1390b57cec5SDimitry Andric };
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
1420b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
1430b57cec5SDimitry Andric     IO.enumCase(Value, "All", FormatStyle::BOS_All);
1440b57cec5SDimitry Andric     IO.enumCase(Value, "true", FormatStyle::BOS_All);
1450b57cec5SDimitry Andric     IO.enumCase(Value, "None", FormatStyle::BOS_None);
1460b57cec5SDimitry Andric     IO.enumCase(Value, "false", FormatStyle::BOS_None);
1470b57cec5SDimitry Andric     IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
1480b57cec5SDimitry Andric   }
1490b57cec5SDimitry Andric };
1500b57cec5SDimitry Andric 
1510b57cec5SDimitry Andric template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
1520b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
1530b57cec5SDimitry Andric     IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
1540b57cec5SDimitry Andric     IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
1550b57cec5SDimitry Andric     IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
1560b57cec5SDimitry Andric     IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
1570b57cec5SDimitry Andric     IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
1580b57cec5SDimitry Andric     IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
1590b57cec5SDimitry Andric     IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
1600b57cec5SDimitry Andric     IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
1610b57cec5SDimitry Andric   }
1620b57cec5SDimitry Andric };
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric template <>
1650b57cec5SDimitry Andric struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
1660b57cec5SDimitry Andric   static void
1670b57cec5SDimitry Andric   enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) {
1680b57cec5SDimitry Andric     IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
1690b57cec5SDimitry Andric     IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
1700b57cec5SDimitry Andric     IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
1710b57cec5SDimitry Andric   }
1720b57cec5SDimitry Andric };
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric template <>
1750b57cec5SDimitry Andric struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
1760b57cec5SDimitry Andric   static void enumeration(IO &IO,
1770b57cec5SDimitry Andric                           FormatStyle::BreakInheritanceListStyle &Value) {
1780b57cec5SDimitry Andric     IO.enumCase(Value, "BeforeColon", FormatStyle::BILS_BeforeColon);
1790b57cec5SDimitry Andric     IO.enumCase(Value, "BeforeComma", FormatStyle::BILS_BeforeComma);
1800b57cec5SDimitry Andric     IO.enumCase(Value, "AfterColon", FormatStyle::BILS_AfterColon);
1810b57cec5SDimitry Andric   }
1820b57cec5SDimitry Andric };
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric template <>
1850b57cec5SDimitry Andric struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
1860b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) {
1870b57cec5SDimitry Andric     IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
1880b57cec5SDimitry Andric     IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
1890b57cec5SDimitry Andric     IO.enumCase(Value, "BeforeHash", FormatStyle::PPDIS_BeforeHash);
1900b57cec5SDimitry Andric   }
1910b57cec5SDimitry Andric };
1920b57cec5SDimitry Andric 
1930b57cec5SDimitry Andric template <>
1940b57cec5SDimitry Andric struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
1950b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
1960b57cec5SDimitry Andric     IO.enumCase(Value, "None", FormatStyle::RTBS_None);
1970b57cec5SDimitry Andric     IO.enumCase(Value, "All", FormatStyle::RTBS_All);
1980b57cec5SDimitry Andric     IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
1990b57cec5SDimitry Andric     IO.enumCase(Value, "TopLevelDefinitions",
2000b57cec5SDimitry Andric                 FormatStyle::RTBS_TopLevelDefinitions);
2010b57cec5SDimitry Andric     IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
2020b57cec5SDimitry Andric   }
2030b57cec5SDimitry Andric };
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric template <>
2060b57cec5SDimitry Andric struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
2070b57cec5SDimitry Andric   static void enumeration(IO &IO,
2080b57cec5SDimitry Andric                           FormatStyle::BreakTemplateDeclarationsStyle &Value) {
2090b57cec5SDimitry Andric     IO.enumCase(Value, "No", FormatStyle::BTDS_No);
2100b57cec5SDimitry Andric     IO.enumCase(Value, "MultiLine", FormatStyle::BTDS_MultiLine);
2110b57cec5SDimitry Andric     IO.enumCase(Value, "Yes", FormatStyle::BTDS_Yes);
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric     // For backward compatibility.
2140b57cec5SDimitry Andric     IO.enumCase(Value, "false", FormatStyle::BTDS_MultiLine);
2150b57cec5SDimitry Andric     IO.enumCase(Value, "true", FormatStyle::BTDS_Yes);
2160b57cec5SDimitry Andric   }
2170b57cec5SDimitry Andric };
2180b57cec5SDimitry Andric 
2190b57cec5SDimitry Andric template <>
2200b57cec5SDimitry Andric struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
2210b57cec5SDimitry Andric   static void
2220b57cec5SDimitry Andric   enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
2230b57cec5SDimitry Andric     IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
2240b57cec5SDimitry Andric     IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
2250b57cec5SDimitry Andric     IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric     // For backward compatibility.
2280b57cec5SDimitry Andric     IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
2290b57cec5SDimitry Andric     IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
2300b57cec5SDimitry Andric   }
2310b57cec5SDimitry Andric };
2320b57cec5SDimitry Andric 
2330b57cec5SDimitry Andric template <>
2340b57cec5SDimitry Andric struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
2350b57cec5SDimitry Andric   static void enumeration(IO &IO,
2360b57cec5SDimitry Andric                           FormatStyle::NamespaceIndentationKind &Value) {
2370b57cec5SDimitry Andric     IO.enumCase(Value, "None", FormatStyle::NI_None);
2380b57cec5SDimitry Andric     IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
2390b57cec5SDimitry Andric     IO.enumCase(Value, "All", FormatStyle::NI_All);
2400b57cec5SDimitry Andric   }
2410b57cec5SDimitry Andric };
2420b57cec5SDimitry Andric 
2430b57cec5SDimitry Andric template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
2440b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
2450b57cec5SDimitry Andric     IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
2460b57cec5SDimitry Andric     IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
2470b57cec5SDimitry Andric     IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
2480b57cec5SDimitry Andric 
2490b57cec5SDimitry Andric     // For backward compatibility.
2500b57cec5SDimitry Andric     IO.enumCase(Value, "true", FormatStyle::BAS_Align);
2510b57cec5SDimitry Andric     IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
2520b57cec5SDimitry Andric   }
2530b57cec5SDimitry Andric };
2540b57cec5SDimitry Andric 
2550b57cec5SDimitry Andric template <>
2560b57cec5SDimitry Andric struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
2570b57cec5SDimitry Andric   static void enumeration(IO &IO,
2580b57cec5SDimitry Andric                           FormatStyle::EscapedNewlineAlignmentStyle &Value) {
2590b57cec5SDimitry Andric     IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
2600b57cec5SDimitry Andric     IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
2610b57cec5SDimitry Andric     IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric     // For backward compatibility.
2640b57cec5SDimitry Andric     IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
2650b57cec5SDimitry Andric     IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
2660b57cec5SDimitry Andric   }
2670b57cec5SDimitry Andric };
2680b57cec5SDimitry Andric 
2690b57cec5SDimitry Andric template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
2700b57cec5SDimitry Andric   static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
2710b57cec5SDimitry Andric     IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
2720b57cec5SDimitry Andric     IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
2730b57cec5SDimitry Andric     IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
2740b57cec5SDimitry Andric 
2750b57cec5SDimitry Andric     // For backward compatibility.
2760b57cec5SDimitry Andric     IO.enumCase(Value, "true", FormatStyle::PAS_Left);
2770b57cec5SDimitry Andric     IO.enumCase(Value, "false", FormatStyle::PAS_Right);
2780b57cec5SDimitry Andric   }
2790b57cec5SDimitry Andric };
2800b57cec5SDimitry Andric 
2810b57cec5SDimitry Andric template <>
2820b57cec5SDimitry Andric struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
2830b57cec5SDimitry Andric   static void enumeration(IO &IO,
2840b57cec5SDimitry Andric                           FormatStyle::SpaceBeforeParensOptions &Value) {
2850b57cec5SDimitry Andric     IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
2860b57cec5SDimitry Andric     IO.enumCase(Value, "ControlStatements",
2870b57cec5SDimitry Andric                 FormatStyle::SBPO_ControlStatements);
2880b57cec5SDimitry Andric     IO.enumCase(Value, "NonEmptyParentheses",
2890b57cec5SDimitry Andric                 FormatStyle::SBPO_NonEmptyParentheses);
2900b57cec5SDimitry Andric     IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
2910b57cec5SDimitry Andric 
2920b57cec5SDimitry Andric     // For backward compatibility.
2930b57cec5SDimitry Andric     IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
2940b57cec5SDimitry Andric     IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
2950b57cec5SDimitry Andric   }
2960b57cec5SDimitry Andric };
2970b57cec5SDimitry Andric 
2980b57cec5SDimitry Andric template <> struct MappingTraits<FormatStyle> {
2990b57cec5SDimitry Andric   static void mapping(IO &IO, FormatStyle &Style) {
3000b57cec5SDimitry Andric     // When reading, read the language first, we need it for getPredefinedStyle.
3010b57cec5SDimitry Andric     IO.mapOptional("Language", Style.Language);
3020b57cec5SDimitry Andric 
3030b57cec5SDimitry Andric     if (IO.outputting()) {
3040b57cec5SDimitry Andric       StringRef StylesArray[] = {"LLVM",   "Google", "Chromium", "Mozilla",
3050b57cec5SDimitry Andric                                  "WebKit", "GNU",    "Microsoft"};
3060b57cec5SDimitry Andric       ArrayRef<StringRef> Styles(StylesArray);
3070b57cec5SDimitry Andric       for (size_t i = 0, e = Styles.size(); i < e; ++i) {
3080b57cec5SDimitry Andric         StringRef StyleName(Styles[i]);
3090b57cec5SDimitry Andric         FormatStyle PredefinedStyle;
3100b57cec5SDimitry Andric         if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
3110b57cec5SDimitry Andric             Style == PredefinedStyle) {
3120b57cec5SDimitry Andric           IO.mapOptional("# BasedOnStyle", StyleName);
3130b57cec5SDimitry Andric           break;
3140b57cec5SDimitry Andric         }
3150b57cec5SDimitry Andric       }
3160b57cec5SDimitry Andric     } else {
3170b57cec5SDimitry Andric       StringRef BasedOnStyle;
3180b57cec5SDimitry Andric       IO.mapOptional("BasedOnStyle", BasedOnStyle);
3190b57cec5SDimitry Andric       if (!BasedOnStyle.empty()) {
3200b57cec5SDimitry Andric         FormatStyle::LanguageKind OldLanguage = Style.Language;
3210b57cec5SDimitry Andric         FormatStyle::LanguageKind Language =
3220b57cec5SDimitry Andric             ((FormatStyle *)IO.getContext())->Language;
3230b57cec5SDimitry Andric         if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
3240b57cec5SDimitry Andric           IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
3250b57cec5SDimitry Andric           return;
3260b57cec5SDimitry Andric         }
3270b57cec5SDimitry Andric         Style.Language = OldLanguage;
3280b57cec5SDimitry Andric       }
3290b57cec5SDimitry Andric     }
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric     // For backward compatibility.
3320b57cec5SDimitry Andric     if (!IO.outputting()) {
3330b57cec5SDimitry Andric       IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
3340b57cec5SDimitry Andric       IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
3350b57cec5SDimitry Andric       IO.mapOptional("IndentFunctionDeclarationAfterType",
3360b57cec5SDimitry Andric                      Style.IndentWrappedFunctionNames);
3370b57cec5SDimitry Andric       IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
3380b57cec5SDimitry Andric       IO.mapOptional("SpaceAfterControlStatementKeyword",
3390b57cec5SDimitry Andric                      Style.SpaceBeforeParens);
3400b57cec5SDimitry Andric     }
3410b57cec5SDimitry Andric 
3420b57cec5SDimitry Andric     IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
3430b57cec5SDimitry Andric     IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
3440b57cec5SDimitry Andric     IO.mapOptional("AlignConsecutiveMacros", Style.AlignConsecutiveMacros);
3450b57cec5SDimitry Andric     IO.mapOptional("AlignConsecutiveAssignments",
3460b57cec5SDimitry Andric                    Style.AlignConsecutiveAssignments);
3470b57cec5SDimitry Andric     IO.mapOptional("AlignConsecutiveDeclarations",
3480b57cec5SDimitry Andric                    Style.AlignConsecutiveDeclarations);
3490b57cec5SDimitry Andric     IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
3500b57cec5SDimitry Andric     IO.mapOptional("AlignOperands", Style.AlignOperands);
3510b57cec5SDimitry Andric     IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
3520b57cec5SDimitry Andric     IO.mapOptional("AllowAllArgumentsOnNextLine",
3530b57cec5SDimitry Andric                    Style.AllowAllArgumentsOnNextLine);
3540b57cec5SDimitry Andric     IO.mapOptional("AllowAllConstructorInitializersOnNextLine",
3550b57cec5SDimitry Andric                    Style.AllowAllConstructorInitializersOnNextLine);
3560b57cec5SDimitry Andric     IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
3570b57cec5SDimitry Andric                    Style.AllowAllParametersOfDeclarationOnNextLine);
3580b57cec5SDimitry Andric     IO.mapOptional("AllowShortBlocksOnASingleLine",
3590b57cec5SDimitry Andric                    Style.AllowShortBlocksOnASingleLine);
3600b57cec5SDimitry Andric     IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
3610b57cec5SDimitry Andric                    Style.AllowShortCaseLabelsOnASingleLine);
3620b57cec5SDimitry Andric     IO.mapOptional("AllowShortFunctionsOnASingleLine",
3630b57cec5SDimitry Andric                    Style.AllowShortFunctionsOnASingleLine);
3640b57cec5SDimitry Andric     IO.mapOptional("AllowShortLambdasOnASingleLine",
3650b57cec5SDimitry Andric                    Style.AllowShortLambdasOnASingleLine);
3660b57cec5SDimitry Andric     IO.mapOptional("AllowShortIfStatementsOnASingleLine",
3670b57cec5SDimitry Andric                    Style.AllowShortIfStatementsOnASingleLine);
3680b57cec5SDimitry Andric     IO.mapOptional("AllowShortLoopsOnASingleLine",
3690b57cec5SDimitry Andric                    Style.AllowShortLoopsOnASingleLine);
3700b57cec5SDimitry Andric     IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
3710b57cec5SDimitry Andric                    Style.AlwaysBreakAfterDefinitionReturnType);
3720b57cec5SDimitry Andric     IO.mapOptional("AlwaysBreakAfterReturnType",
3730b57cec5SDimitry Andric                    Style.AlwaysBreakAfterReturnType);
3740b57cec5SDimitry Andric 
3750b57cec5SDimitry Andric     // If AlwaysBreakAfterDefinitionReturnType was specified but
3760b57cec5SDimitry Andric     // AlwaysBreakAfterReturnType was not, initialize the latter from the
3770b57cec5SDimitry Andric     // former for backwards compatibility.
3780b57cec5SDimitry Andric     if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
3790b57cec5SDimitry Andric         Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
3800b57cec5SDimitry Andric       if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
3810b57cec5SDimitry Andric         Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
3820b57cec5SDimitry Andric       else if (Style.AlwaysBreakAfterDefinitionReturnType ==
3830b57cec5SDimitry Andric                FormatStyle::DRTBS_TopLevel)
3840b57cec5SDimitry Andric         Style.AlwaysBreakAfterReturnType =
3850b57cec5SDimitry Andric             FormatStyle::RTBS_TopLevelDefinitions;
3860b57cec5SDimitry Andric     }
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric     IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
3890b57cec5SDimitry Andric                    Style.AlwaysBreakBeforeMultilineStrings);
3900b57cec5SDimitry Andric     IO.mapOptional("AlwaysBreakTemplateDeclarations",
3910b57cec5SDimitry Andric                    Style.AlwaysBreakTemplateDeclarations);
3920b57cec5SDimitry Andric     IO.mapOptional("BinPackArguments", Style.BinPackArguments);
3930b57cec5SDimitry Andric     IO.mapOptional("BinPackParameters", Style.BinPackParameters);
3940b57cec5SDimitry Andric     IO.mapOptional("BraceWrapping", Style.BraceWrapping);
3950b57cec5SDimitry Andric     IO.mapOptional("BreakBeforeBinaryOperators",
3960b57cec5SDimitry Andric                    Style.BreakBeforeBinaryOperators);
3970b57cec5SDimitry Andric     IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
3980b57cec5SDimitry Andric 
3990b57cec5SDimitry Andric     bool BreakBeforeInheritanceComma = false;
4000b57cec5SDimitry Andric     IO.mapOptional("BreakBeforeInheritanceComma", BreakBeforeInheritanceComma);
4010b57cec5SDimitry Andric     IO.mapOptional("BreakInheritanceList", Style.BreakInheritanceList);
4020b57cec5SDimitry Andric     // If BreakBeforeInheritanceComma was specified but
4030b57cec5SDimitry Andric     // BreakInheritance was not, initialize the latter from the
4040b57cec5SDimitry Andric     // former for backwards compatibility.
4050b57cec5SDimitry Andric     if (BreakBeforeInheritanceComma &&
4060b57cec5SDimitry Andric         Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon)
4070b57cec5SDimitry Andric       Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
4080b57cec5SDimitry Andric 
4090b57cec5SDimitry Andric     IO.mapOptional("BreakBeforeTernaryOperators",
4100b57cec5SDimitry Andric                    Style.BreakBeforeTernaryOperators);
4110b57cec5SDimitry Andric 
4120b57cec5SDimitry Andric     bool BreakConstructorInitializersBeforeComma = false;
4130b57cec5SDimitry Andric     IO.mapOptional("BreakConstructorInitializersBeforeComma",
4140b57cec5SDimitry Andric                    BreakConstructorInitializersBeforeComma);
4150b57cec5SDimitry Andric     IO.mapOptional("BreakConstructorInitializers",
4160b57cec5SDimitry Andric                    Style.BreakConstructorInitializers);
4170b57cec5SDimitry Andric     // If BreakConstructorInitializersBeforeComma was specified but
4180b57cec5SDimitry Andric     // BreakConstructorInitializers was not, initialize the latter from the
4190b57cec5SDimitry Andric     // former for backwards compatibility.
4200b57cec5SDimitry Andric     if (BreakConstructorInitializersBeforeComma &&
4210b57cec5SDimitry Andric         Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon)
4220b57cec5SDimitry Andric       Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric     IO.mapOptional("BreakAfterJavaFieldAnnotations",
4250b57cec5SDimitry Andric                    Style.BreakAfterJavaFieldAnnotations);
4260b57cec5SDimitry Andric     IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
4270b57cec5SDimitry Andric     IO.mapOptional("ColumnLimit", Style.ColumnLimit);
4280b57cec5SDimitry Andric     IO.mapOptional("CommentPragmas", Style.CommentPragmas);
4290b57cec5SDimitry Andric     IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
4300b57cec5SDimitry Andric     IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
4310b57cec5SDimitry Andric                    Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
4320b57cec5SDimitry Andric     IO.mapOptional("ConstructorInitializerIndentWidth",
4330b57cec5SDimitry Andric                    Style.ConstructorInitializerIndentWidth);
4340b57cec5SDimitry Andric     IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
4350b57cec5SDimitry Andric     IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
4360b57cec5SDimitry Andric     IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
4370b57cec5SDimitry Andric     IO.mapOptional("DisableFormat", Style.DisableFormat);
4380b57cec5SDimitry Andric     IO.mapOptional("ExperimentalAutoDetectBinPacking",
4390b57cec5SDimitry Andric                    Style.ExperimentalAutoDetectBinPacking);
4400b57cec5SDimitry Andric     IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
4410b57cec5SDimitry Andric     IO.mapOptional("ForEachMacros", Style.ForEachMacros);
4420b57cec5SDimitry Andric     IO.mapOptional("IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
4430b57cec5SDimitry Andric     IO.mapOptional("IncludeCategories", Style.IncludeStyle.IncludeCategories);
4440b57cec5SDimitry Andric     IO.mapOptional("IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
4450b57cec5SDimitry Andric     IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
4460b57cec5SDimitry Andric     IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
4470b57cec5SDimitry Andric     IO.mapOptional("IndentWidth", Style.IndentWidth);
4480b57cec5SDimitry Andric     IO.mapOptional("IndentWrappedFunctionNames",
4490b57cec5SDimitry Andric                    Style.IndentWrappedFunctionNames);
4500b57cec5SDimitry Andric     IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
4510b57cec5SDimitry Andric     IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
4520b57cec5SDimitry Andric     IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
4530b57cec5SDimitry Andric     IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
4540b57cec5SDimitry Andric                    Style.KeepEmptyLinesAtTheStartOfBlocks);
4550b57cec5SDimitry Andric     IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
4560b57cec5SDimitry Andric     IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
4570b57cec5SDimitry Andric     IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
4580b57cec5SDimitry Andric     IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
4590b57cec5SDimitry Andric     IO.mapOptional("NamespaceMacros", Style.NamespaceMacros);
4600b57cec5SDimitry Andric     IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
4610b57cec5SDimitry Andric     IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
4620b57cec5SDimitry Andric     IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
4630b57cec5SDimitry Andric     IO.mapOptional("ObjCSpaceBeforeProtocolList",
4640b57cec5SDimitry Andric                    Style.ObjCSpaceBeforeProtocolList);
4650b57cec5SDimitry Andric     IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
4660b57cec5SDimitry Andric     IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
4670b57cec5SDimitry Andric                    Style.PenaltyBreakBeforeFirstCallParameter);
4680b57cec5SDimitry Andric     IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
4690b57cec5SDimitry Andric     IO.mapOptional("PenaltyBreakFirstLessLess",
4700b57cec5SDimitry Andric                    Style.PenaltyBreakFirstLessLess);
4710b57cec5SDimitry Andric     IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
4720b57cec5SDimitry Andric     IO.mapOptional("PenaltyBreakTemplateDeclaration",
4730b57cec5SDimitry Andric                    Style.PenaltyBreakTemplateDeclaration);
4740b57cec5SDimitry Andric     IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
4750b57cec5SDimitry Andric     IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
4760b57cec5SDimitry Andric                    Style.PenaltyReturnTypeOnItsOwnLine);
4770b57cec5SDimitry Andric     IO.mapOptional("PointerAlignment", Style.PointerAlignment);
4780b57cec5SDimitry Andric     IO.mapOptional("RawStringFormats", Style.RawStringFormats);
4790b57cec5SDimitry Andric     IO.mapOptional("ReflowComments", Style.ReflowComments);
4800b57cec5SDimitry Andric     IO.mapOptional("SortIncludes", Style.SortIncludes);
4810b57cec5SDimitry Andric     IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
4820b57cec5SDimitry Andric     IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
4830b57cec5SDimitry Andric     IO.mapOptional("SpaceAfterLogicalNot", Style.SpaceAfterLogicalNot);
4840b57cec5SDimitry Andric     IO.mapOptional("SpaceAfterTemplateKeyword",
4850b57cec5SDimitry Andric                    Style.SpaceAfterTemplateKeyword);
4860b57cec5SDimitry Andric     IO.mapOptional("SpaceBeforeAssignmentOperators",
4870b57cec5SDimitry Andric                    Style.SpaceBeforeAssignmentOperators);
4880b57cec5SDimitry Andric     IO.mapOptional("SpaceBeforeCpp11BracedList",
4890b57cec5SDimitry Andric                    Style.SpaceBeforeCpp11BracedList);
4900b57cec5SDimitry Andric     IO.mapOptional("SpaceBeforeCtorInitializerColon",
4910b57cec5SDimitry Andric                    Style.SpaceBeforeCtorInitializerColon);
4920b57cec5SDimitry Andric     IO.mapOptional("SpaceBeforeInheritanceColon",
4930b57cec5SDimitry Andric                    Style.SpaceBeforeInheritanceColon);
4940b57cec5SDimitry Andric     IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
4950b57cec5SDimitry Andric     IO.mapOptional("SpaceBeforeRangeBasedForLoopColon",
4960b57cec5SDimitry Andric                    Style.SpaceBeforeRangeBasedForLoopColon);
4970b57cec5SDimitry Andric     IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
4980b57cec5SDimitry Andric     IO.mapOptional("SpacesBeforeTrailingComments",
4990b57cec5SDimitry Andric                    Style.SpacesBeforeTrailingComments);
5000b57cec5SDimitry Andric     IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
5010b57cec5SDimitry Andric     IO.mapOptional("SpacesInContainerLiterals",
5020b57cec5SDimitry Andric                    Style.SpacesInContainerLiterals);
5030b57cec5SDimitry Andric     IO.mapOptional("SpacesInCStyleCastParentheses",
5040b57cec5SDimitry Andric                    Style.SpacesInCStyleCastParentheses);
5050b57cec5SDimitry Andric     IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
5060b57cec5SDimitry Andric     IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
5070b57cec5SDimitry Andric     IO.mapOptional("Standard", Style.Standard);
5080b57cec5SDimitry Andric     IO.mapOptional("StatementMacros", Style.StatementMacros);
5090b57cec5SDimitry Andric     IO.mapOptional("TabWidth", Style.TabWidth);
5100b57cec5SDimitry Andric     IO.mapOptional("TypenameMacros", Style.TypenameMacros);
5110b57cec5SDimitry Andric     IO.mapOptional("UseTab", Style.UseTab);
5120b57cec5SDimitry Andric   }
5130b57cec5SDimitry Andric };
5140b57cec5SDimitry Andric 
5150b57cec5SDimitry Andric template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
5160b57cec5SDimitry Andric   static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
5170b57cec5SDimitry Andric     IO.mapOptional("AfterCaseLabel", Wrapping.AfterCaseLabel);
5180b57cec5SDimitry Andric     IO.mapOptional("AfterClass", Wrapping.AfterClass);
5190b57cec5SDimitry Andric     IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
5200b57cec5SDimitry Andric     IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
5210b57cec5SDimitry Andric     IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
5220b57cec5SDimitry Andric     IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
5230b57cec5SDimitry Andric     IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
5240b57cec5SDimitry Andric     IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
5250b57cec5SDimitry Andric     IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
5260b57cec5SDimitry Andric     IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
5270b57cec5SDimitry Andric     IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
5280b57cec5SDimitry Andric     IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
5290b57cec5SDimitry Andric     IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
5300b57cec5SDimitry Andric     IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
5310b57cec5SDimitry Andric     IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
5320b57cec5SDimitry Andric     IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
5330b57cec5SDimitry Andric   }
5340b57cec5SDimitry Andric };
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric template <> struct MappingTraits<FormatStyle::RawStringFormat> {
5370b57cec5SDimitry Andric   static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
5380b57cec5SDimitry Andric     IO.mapOptional("Language", Format.Language);
5390b57cec5SDimitry Andric     IO.mapOptional("Delimiters", Format.Delimiters);
5400b57cec5SDimitry Andric     IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
5410b57cec5SDimitry Andric     IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
5420b57cec5SDimitry Andric     IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
5430b57cec5SDimitry Andric   }
5440b57cec5SDimitry Andric };
5450b57cec5SDimitry Andric 
5460b57cec5SDimitry Andric // Allows to read vector<FormatStyle> while keeping default values.
5470b57cec5SDimitry Andric // IO.getContext() should contain a pointer to the FormatStyle structure, that
5480b57cec5SDimitry Andric // will be used to get default values for missing keys.
5490b57cec5SDimitry Andric // If the first element has no Language specified, it will be treated as the
5500b57cec5SDimitry Andric // default one for the following elements.
5510b57cec5SDimitry Andric template <> struct DocumentListTraits<std::vector<FormatStyle>> {
5520b57cec5SDimitry Andric   static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
5530b57cec5SDimitry Andric     return Seq.size();
5540b57cec5SDimitry Andric   }
5550b57cec5SDimitry Andric   static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
5560b57cec5SDimitry Andric                               size_t Index) {
5570b57cec5SDimitry Andric     if (Index >= Seq.size()) {
5580b57cec5SDimitry Andric       assert(Index == Seq.size());
5590b57cec5SDimitry Andric       FormatStyle Template;
5600b57cec5SDimitry Andric       if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
5610b57cec5SDimitry Andric         Template = Seq[0];
5620b57cec5SDimitry Andric       } else {
5630b57cec5SDimitry Andric         Template = *((const FormatStyle *)IO.getContext());
5640b57cec5SDimitry Andric         Template.Language = FormatStyle::LK_None;
5650b57cec5SDimitry Andric       }
5660b57cec5SDimitry Andric       Seq.resize(Index + 1, Template);
5670b57cec5SDimitry Andric     }
5680b57cec5SDimitry Andric     return Seq[Index];
5690b57cec5SDimitry Andric   }
5700b57cec5SDimitry Andric };
5710b57cec5SDimitry Andric } // namespace yaml
5720b57cec5SDimitry Andric } // namespace llvm
5730b57cec5SDimitry Andric 
5740b57cec5SDimitry Andric namespace clang {
5750b57cec5SDimitry Andric namespace format {
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric const std::error_category &getParseCategory() {
5780b57cec5SDimitry Andric   static const ParseErrorCategory C{};
5790b57cec5SDimitry Andric   return C;
5800b57cec5SDimitry Andric }
5810b57cec5SDimitry Andric std::error_code make_error_code(ParseError e) {
5820b57cec5SDimitry Andric   return std::error_code(static_cast<int>(e), getParseCategory());
5830b57cec5SDimitry Andric }
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric inline llvm::Error make_string_error(const llvm::Twine &Message) {
5860b57cec5SDimitry Andric   return llvm::make_error<llvm::StringError>(Message,
5870b57cec5SDimitry Andric                                              llvm::inconvertibleErrorCode());
5880b57cec5SDimitry Andric }
5890b57cec5SDimitry Andric 
5900b57cec5SDimitry Andric const char *ParseErrorCategory::name() const noexcept {
5910b57cec5SDimitry Andric   return "clang-format.parse_error";
5920b57cec5SDimitry Andric }
5930b57cec5SDimitry Andric 
5940b57cec5SDimitry Andric std::string ParseErrorCategory::message(int EV) const {
5950b57cec5SDimitry Andric   switch (static_cast<ParseError>(EV)) {
5960b57cec5SDimitry Andric   case ParseError::Success:
5970b57cec5SDimitry Andric     return "Success";
5980b57cec5SDimitry Andric   case ParseError::Error:
5990b57cec5SDimitry Andric     return "Invalid argument";
6000b57cec5SDimitry Andric   case ParseError::Unsuitable:
6010b57cec5SDimitry Andric     return "Unsuitable";
6020b57cec5SDimitry Andric   }
6030b57cec5SDimitry Andric   llvm_unreachable("unexpected parse error");
6040b57cec5SDimitry Andric }
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric static FormatStyle expandPresets(const FormatStyle &Style) {
6070b57cec5SDimitry Andric   if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
6080b57cec5SDimitry Andric     return Style;
6090b57cec5SDimitry Andric   FormatStyle Expanded = Style;
6100b57cec5SDimitry Andric   Expanded.BraceWrapping = {false, false, false, false, false, false,
6110b57cec5SDimitry Andric                             false, false, false, false, false,
6120b57cec5SDimitry Andric                             false, false, true,  true,  true};
6130b57cec5SDimitry Andric   switch (Style.BreakBeforeBraces) {
6140b57cec5SDimitry Andric   case FormatStyle::BS_Linux:
6150b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterClass = true;
6160b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterFunction = true;
6170b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterNamespace = true;
6180b57cec5SDimitry Andric     break;
6190b57cec5SDimitry Andric   case FormatStyle::BS_Mozilla:
6200b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterClass = true;
6210b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterEnum = true;
6220b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterFunction = true;
6230b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterStruct = true;
6240b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterUnion = true;
6250b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterExternBlock = true;
6260b57cec5SDimitry Andric     Expanded.BraceWrapping.SplitEmptyFunction = true;
6270b57cec5SDimitry Andric     Expanded.BraceWrapping.SplitEmptyRecord = false;
6280b57cec5SDimitry Andric     break;
6290b57cec5SDimitry Andric   case FormatStyle::BS_Stroustrup:
6300b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterFunction = true;
6310b57cec5SDimitry Andric     Expanded.BraceWrapping.BeforeCatch = true;
6320b57cec5SDimitry Andric     Expanded.BraceWrapping.BeforeElse = true;
6330b57cec5SDimitry Andric     break;
6340b57cec5SDimitry Andric   case FormatStyle::BS_Allman:
6350b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterCaseLabel = true;
6360b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterClass = true;
6370b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterControlStatement = true;
6380b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterEnum = true;
6390b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterFunction = true;
6400b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterNamespace = true;
6410b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterObjCDeclaration = true;
6420b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterStruct = true;
6430b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterExternBlock = true;
6440b57cec5SDimitry Andric     Expanded.BraceWrapping.BeforeCatch = true;
6450b57cec5SDimitry Andric     Expanded.BraceWrapping.BeforeElse = true;
6460b57cec5SDimitry Andric     break;
6470b57cec5SDimitry Andric   case FormatStyle::BS_GNU:
6480b57cec5SDimitry Andric     Expanded.BraceWrapping = {true, true, true, true, true, true, true, true,
6490b57cec5SDimitry Andric                               true, true, true, true, true, true, true, true};
6500b57cec5SDimitry Andric     break;
6510b57cec5SDimitry Andric   case FormatStyle::BS_WebKit:
6520b57cec5SDimitry Andric     Expanded.BraceWrapping.AfterFunction = true;
6530b57cec5SDimitry Andric     break;
6540b57cec5SDimitry Andric   default:
6550b57cec5SDimitry Andric     break;
6560b57cec5SDimitry Andric   }
6570b57cec5SDimitry Andric   return Expanded;
6580b57cec5SDimitry Andric }
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) {
6610b57cec5SDimitry Andric   FormatStyle LLVMStyle;
6620b57cec5SDimitry Andric   LLVMStyle.Language = Language;
6630b57cec5SDimitry Andric   LLVMStyle.AccessModifierOffset = -2;
6640b57cec5SDimitry Andric   LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
6650b57cec5SDimitry Andric   LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6660b57cec5SDimitry Andric   LLVMStyle.AlignOperands = true;
6670b57cec5SDimitry Andric   LLVMStyle.AlignTrailingComments = true;
6680b57cec5SDimitry Andric   LLVMStyle.AlignConsecutiveAssignments = false;
6690b57cec5SDimitry Andric   LLVMStyle.AlignConsecutiveDeclarations = false;
6700b57cec5SDimitry Andric   LLVMStyle.AlignConsecutiveMacros = false;
6710b57cec5SDimitry Andric   LLVMStyle.AllowAllArgumentsOnNextLine = true;
6720b57cec5SDimitry Andric   LLVMStyle.AllowAllConstructorInitializersOnNextLine = true;
6730b57cec5SDimitry Andric   LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
6740b57cec5SDimitry Andric   LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
6750b57cec5SDimitry Andric   LLVMStyle.AllowShortBlocksOnASingleLine = false;
6760b57cec5SDimitry Andric   LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
6770b57cec5SDimitry Andric   LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
6780b57cec5SDimitry Andric   LLVMStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
6790b57cec5SDimitry Andric   LLVMStyle.AllowShortLoopsOnASingleLine = false;
6800b57cec5SDimitry Andric   LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
6810b57cec5SDimitry Andric   LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
6820b57cec5SDimitry Andric   LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
6830b57cec5SDimitry Andric   LLVMStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
6840b57cec5SDimitry Andric   LLVMStyle.BinPackArguments = true;
6850b57cec5SDimitry Andric   LLVMStyle.BinPackParameters = true;
6860b57cec5SDimitry Andric   LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6870b57cec5SDimitry Andric   LLVMStyle.BreakBeforeTernaryOperators = true;
6880b57cec5SDimitry Andric   LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
6890b57cec5SDimitry Andric   LLVMStyle.BraceWrapping = {false, false, false, false, false, false,
6900b57cec5SDimitry Andric                              false, false, false, false, false,
6910b57cec5SDimitry Andric                              false, false, true,  true,  true};
6920b57cec5SDimitry Andric   LLVMStyle.BreakAfterJavaFieldAnnotations = false;
6930b57cec5SDimitry Andric   LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6940b57cec5SDimitry Andric   LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
6950b57cec5SDimitry Andric   LLVMStyle.BreakStringLiterals = true;
6960b57cec5SDimitry Andric   LLVMStyle.ColumnLimit = 80;
6970b57cec5SDimitry Andric   LLVMStyle.CommentPragmas = "^ IWYU pragma:";
6980b57cec5SDimitry Andric   LLVMStyle.CompactNamespaces = false;
6990b57cec5SDimitry Andric   LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
7000b57cec5SDimitry Andric   LLVMStyle.ConstructorInitializerIndentWidth = 4;
7010b57cec5SDimitry Andric   LLVMStyle.ContinuationIndentWidth = 4;
7020b57cec5SDimitry Andric   LLVMStyle.Cpp11BracedListStyle = true;
7030b57cec5SDimitry Andric   LLVMStyle.DerivePointerAlignment = false;
7040b57cec5SDimitry Andric   LLVMStyle.ExperimentalAutoDetectBinPacking = false;
7050b57cec5SDimitry Andric   LLVMStyle.FixNamespaceComments = true;
7060b57cec5SDimitry Andric   LLVMStyle.ForEachMacros.push_back("foreach");
7070b57cec5SDimitry Andric   LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
7080b57cec5SDimitry Andric   LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
7090b57cec5SDimitry Andric   LLVMStyle.IncludeStyle.IncludeCategories = {
7100b57cec5SDimitry Andric       {"^\"(llvm|llvm-c|clang|clang-c)/", 2},
7110b57cec5SDimitry Andric       {"^(<|\"(gtest|gmock|isl|json)/)", 3},
7120b57cec5SDimitry Andric       {".*", 1}};
7130b57cec5SDimitry Andric   LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
7140b57cec5SDimitry Andric   LLVMStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve;
7150b57cec5SDimitry Andric   LLVMStyle.IndentCaseLabels = false;
7160b57cec5SDimitry Andric   LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
7170b57cec5SDimitry Andric   LLVMStyle.IndentWrappedFunctionNames = false;
7180b57cec5SDimitry Andric   LLVMStyle.IndentWidth = 2;
7190b57cec5SDimitry Andric   LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
7200b57cec5SDimitry Andric   LLVMStyle.JavaScriptWrapImports = true;
7210b57cec5SDimitry Andric   LLVMStyle.TabWidth = 8;
7220b57cec5SDimitry Andric   LLVMStyle.MaxEmptyLinesToKeep = 1;
7230b57cec5SDimitry Andric   LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
7240b57cec5SDimitry Andric   LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
7250b57cec5SDimitry Andric   LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
7260b57cec5SDimitry Andric   LLVMStyle.ObjCBlockIndentWidth = 2;
7270b57cec5SDimitry Andric   LLVMStyle.ObjCSpaceAfterProperty = false;
7280b57cec5SDimitry Andric   LLVMStyle.ObjCSpaceBeforeProtocolList = true;
7290b57cec5SDimitry Andric   LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
7300b57cec5SDimitry Andric   LLVMStyle.SpacesBeforeTrailingComments = 1;
7310b57cec5SDimitry Andric   LLVMStyle.Standard = FormatStyle::LS_Cpp11;
7320b57cec5SDimitry Andric   LLVMStyle.UseTab = FormatStyle::UT_Never;
7330b57cec5SDimitry Andric   LLVMStyle.ReflowComments = true;
7340b57cec5SDimitry Andric   LLVMStyle.SpacesInParentheses = false;
7350b57cec5SDimitry Andric   LLVMStyle.SpacesInSquareBrackets = false;
7360b57cec5SDimitry Andric   LLVMStyle.SpaceInEmptyParentheses = false;
7370b57cec5SDimitry Andric   LLVMStyle.SpacesInContainerLiterals = true;
7380b57cec5SDimitry Andric   LLVMStyle.SpacesInCStyleCastParentheses = false;
7390b57cec5SDimitry Andric   LLVMStyle.SpaceAfterCStyleCast = false;
7400b57cec5SDimitry Andric   LLVMStyle.SpaceAfterLogicalNot = false;
7410b57cec5SDimitry Andric   LLVMStyle.SpaceAfterTemplateKeyword = true;
7420b57cec5SDimitry Andric   LLVMStyle.SpaceBeforeCtorInitializerColon = true;
7430b57cec5SDimitry Andric   LLVMStyle.SpaceBeforeInheritanceColon = true;
7440b57cec5SDimitry Andric   LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
7450b57cec5SDimitry Andric   LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
7460b57cec5SDimitry Andric   LLVMStyle.SpaceBeforeAssignmentOperators = true;
7470b57cec5SDimitry Andric   LLVMStyle.SpaceBeforeCpp11BracedList = false;
7480b57cec5SDimitry Andric   LLVMStyle.SpacesInAngles = false;
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric   LLVMStyle.PenaltyBreakAssignment = prec::Assignment;
7510b57cec5SDimitry Andric   LLVMStyle.PenaltyBreakComment = 300;
7520b57cec5SDimitry Andric   LLVMStyle.PenaltyBreakFirstLessLess = 120;
7530b57cec5SDimitry Andric   LLVMStyle.PenaltyBreakString = 1000;
7540b57cec5SDimitry Andric   LLVMStyle.PenaltyExcessCharacter = 1000000;
7550b57cec5SDimitry Andric   LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
7560b57cec5SDimitry Andric   LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
7570b57cec5SDimitry Andric   LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational;
7580b57cec5SDimitry Andric 
7590b57cec5SDimitry Andric   LLVMStyle.DisableFormat = false;
7600b57cec5SDimitry Andric   LLVMStyle.SortIncludes = true;
7610b57cec5SDimitry Andric   LLVMStyle.SortUsingDeclarations = true;
7620b57cec5SDimitry Andric   LLVMStyle.StatementMacros.push_back("Q_UNUSED");
7630b57cec5SDimitry Andric   LLVMStyle.StatementMacros.push_back("QT_REQUIRE_VERSION");
7640b57cec5SDimitry Andric 
7650b57cec5SDimitry Andric   // Defaults that differ when not C++.
7660b57cec5SDimitry Andric   if (Language == FormatStyle::LK_TableGen) {
7670b57cec5SDimitry Andric     LLVMStyle.SpacesInContainerLiterals = false;
7680b57cec5SDimitry Andric   }
7690b57cec5SDimitry Andric 
7700b57cec5SDimitry Andric   return LLVMStyle;
7710b57cec5SDimitry Andric }
7720b57cec5SDimitry Andric 
7730b57cec5SDimitry Andric FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
7740b57cec5SDimitry Andric   if (Language == FormatStyle::LK_TextProto) {
7750b57cec5SDimitry Andric     FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
7760b57cec5SDimitry Andric     GoogleStyle.Language = FormatStyle::LK_TextProto;
7770b57cec5SDimitry Andric 
7780b57cec5SDimitry Andric     return GoogleStyle;
7790b57cec5SDimitry Andric   }
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric   FormatStyle GoogleStyle = getLLVMStyle(Language);
7820b57cec5SDimitry Andric 
7830b57cec5SDimitry Andric   GoogleStyle.AccessModifierOffset = -1;
7840b57cec5SDimitry Andric   GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
7850b57cec5SDimitry Andric   GoogleStyle.AllowShortIfStatementsOnASingleLine =
7860b57cec5SDimitry Andric       FormatStyle::SIS_WithoutElse;
7870b57cec5SDimitry Andric   GoogleStyle.AllowShortLoopsOnASingleLine = true;
7880b57cec5SDimitry Andric   GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
7890b57cec5SDimitry Andric   GoogleStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7900b57cec5SDimitry Andric   GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
7910b57cec5SDimitry Andric   GoogleStyle.DerivePointerAlignment = true;
7920b57cec5SDimitry Andric   GoogleStyle.IncludeStyle.IncludeCategories = {
7930b57cec5SDimitry Andric       {"^<ext/.*\\.h>", 2}, {"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
7940b57cec5SDimitry Andric   GoogleStyle.IncludeStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
7950b57cec5SDimitry Andric   GoogleStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup;
7960b57cec5SDimitry Andric   GoogleStyle.IndentCaseLabels = true;
7970b57cec5SDimitry Andric   GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
7980b57cec5SDimitry Andric   GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
7990b57cec5SDimitry Andric   GoogleStyle.ObjCSpaceAfterProperty = false;
8000b57cec5SDimitry Andric   GoogleStyle.ObjCSpaceBeforeProtocolList = true;
8010b57cec5SDimitry Andric   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
8020b57cec5SDimitry Andric   GoogleStyle.RawStringFormats = {
8030b57cec5SDimitry Andric       {
8040b57cec5SDimitry Andric           FormatStyle::LK_Cpp,
8050b57cec5SDimitry Andric           /*Delimiters=*/
8060b57cec5SDimitry Andric           {
8070b57cec5SDimitry Andric               "cc",
8080b57cec5SDimitry Andric               "CC",
8090b57cec5SDimitry Andric               "cpp",
8100b57cec5SDimitry Andric               "Cpp",
8110b57cec5SDimitry Andric               "CPP",
8120b57cec5SDimitry Andric               "c++",
8130b57cec5SDimitry Andric               "C++",
8140b57cec5SDimitry Andric           },
8150b57cec5SDimitry Andric           /*EnclosingFunctionNames=*/
8160b57cec5SDimitry Andric           {},
8170b57cec5SDimitry Andric           /*CanonicalDelimiter=*/"",
8180b57cec5SDimitry Andric           /*BasedOnStyle=*/"google",
8190b57cec5SDimitry Andric       },
8200b57cec5SDimitry Andric       {
8210b57cec5SDimitry Andric           FormatStyle::LK_TextProto,
8220b57cec5SDimitry Andric           /*Delimiters=*/
8230b57cec5SDimitry Andric           {
8240b57cec5SDimitry Andric               "pb",
8250b57cec5SDimitry Andric               "PB",
8260b57cec5SDimitry Andric               "proto",
8270b57cec5SDimitry Andric               "PROTO",
8280b57cec5SDimitry Andric           },
8290b57cec5SDimitry Andric           /*EnclosingFunctionNames=*/
8300b57cec5SDimitry Andric           {
8310b57cec5SDimitry Andric               "EqualsProto",
8320b57cec5SDimitry Andric               "EquivToProto",
8330b57cec5SDimitry Andric               "PARSE_PARTIAL_TEXT_PROTO",
8340b57cec5SDimitry Andric               "PARSE_TEST_PROTO",
8350b57cec5SDimitry Andric               "PARSE_TEXT_PROTO",
8360b57cec5SDimitry Andric               "ParseTextOrDie",
8370b57cec5SDimitry Andric               "ParseTextProtoOrDie",
8380b57cec5SDimitry Andric           },
8390b57cec5SDimitry Andric           /*CanonicalDelimiter=*/"",
8400b57cec5SDimitry Andric           /*BasedOnStyle=*/"google",
8410b57cec5SDimitry Andric       },
8420b57cec5SDimitry Andric   };
8430b57cec5SDimitry Andric   GoogleStyle.SpacesBeforeTrailingComments = 2;
8440b57cec5SDimitry Andric   GoogleStyle.Standard = FormatStyle::LS_Auto;
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric   GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
8470b57cec5SDimitry Andric   GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
8480b57cec5SDimitry Andric 
8490b57cec5SDimitry Andric   if (Language == FormatStyle::LK_Java) {
8500b57cec5SDimitry Andric     GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8510b57cec5SDimitry Andric     GoogleStyle.AlignOperands = false;
8520b57cec5SDimitry Andric     GoogleStyle.AlignTrailingComments = false;
8530b57cec5SDimitry Andric     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
8540b57cec5SDimitry Andric     GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
8550b57cec5SDimitry Andric     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
8560b57cec5SDimitry Andric     GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
8570b57cec5SDimitry Andric     GoogleStyle.ColumnLimit = 100;
8580b57cec5SDimitry Andric     GoogleStyle.SpaceAfterCStyleCast = true;
8590b57cec5SDimitry Andric     GoogleStyle.SpacesBeforeTrailingComments = 1;
8600b57cec5SDimitry Andric   } else if (Language == FormatStyle::LK_JavaScript) {
8610b57cec5SDimitry Andric     GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8620b57cec5SDimitry Andric     GoogleStyle.AlignOperands = false;
8630b57cec5SDimitry Andric     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
8640b57cec5SDimitry Andric     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
8650b57cec5SDimitry Andric     GoogleStyle.BreakBeforeTernaryOperators = false;
8660b57cec5SDimitry Andric     // taze:, triple slash directives (`/// <...`), @see, which is commonly
8670b57cec5SDimitry Andric     // followed by overlong URLs.
8680b57cec5SDimitry Andric     GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|@see)";
8690b57cec5SDimitry Andric     GoogleStyle.MaxEmptyLinesToKeep = 3;
8700b57cec5SDimitry Andric     GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
8710b57cec5SDimitry Andric     GoogleStyle.SpacesInContainerLiterals = false;
8720b57cec5SDimitry Andric     GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
8730b57cec5SDimitry Andric     GoogleStyle.JavaScriptWrapImports = false;
8740b57cec5SDimitry Andric   } else if (Language == FormatStyle::LK_Proto) {
8750b57cec5SDimitry Andric     GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
8760b57cec5SDimitry Andric     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
8770b57cec5SDimitry Andric     GoogleStyle.SpacesInContainerLiterals = false;
8780b57cec5SDimitry Andric     GoogleStyle.Cpp11BracedListStyle = false;
8790b57cec5SDimitry Andric     // This affects protocol buffer options specifications and text protos.
8800b57cec5SDimitry Andric     // Text protos are currently mostly formatted inside C++ raw string literals
8810b57cec5SDimitry Andric     // and often the current breaking behavior of string literals is not
8820b57cec5SDimitry Andric     // beneficial there. Investigate turning this on once proper string reflow
8830b57cec5SDimitry Andric     // has been implemented.
8840b57cec5SDimitry Andric     GoogleStyle.BreakStringLiterals = false;
8850b57cec5SDimitry Andric   } else if (Language == FormatStyle::LK_ObjC) {
8860b57cec5SDimitry Andric     GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
8870b57cec5SDimitry Andric     GoogleStyle.ColumnLimit = 100;
8880b57cec5SDimitry Andric     // "Regroup" doesn't work well for ObjC yet (main header heuristic,
8890b57cec5SDimitry Andric     // relationship between ObjC standard library headers and other heades,
8900b57cec5SDimitry Andric     // #imports, etc.)
8910b57cec5SDimitry Andric     GoogleStyle.IncludeStyle.IncludeBlocks =
8920b57cec5SDimitry Andric         tooling::IncludeStyle::IBS_Preserve;
8930b57cec5SDimitry Andric   }
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric   return GoogleStyle;
8960b57cec5SDimitry Andric }
8970b57cec5SDimitry Andric 
8980b57cec5SDimitry Andric FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
8990b57cec5SDimitry Andric   FormatStyle ChromiumStyle = getGoogleStyle(Language);
9000b57cec5SDimitry Andric   if (Language == FormatStyle::LK_Java) {
9010b57cec5SDimitry Andric     ChromiumStyle.AllowShortIfStatementsOnASingleLine =
9020b57cec5SDimitry Andric         FormatStyle::SIS_WithoutElse;
9030b57cec5SDimitry Andric     ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
9040b57cec5SDimitry Andric     ChromiumStyle.ContinuationIndentWidth = 8;
9050b57cec5SDimitry Andric     ChromiumStyle.IndentWidth = 4;
9060b57cec5SDimitry Andric     // See styleguide for import groups:
9070b57cec5SDimitry Andric     // https://chromium.googlesource.com/chromium/src/+/master/styleguide/java/java.md#Import-Order
9080b57cec5SDimitry Andric     ChromiumStyle.JavaImportGroups = {
9090b57cec5SDimitry Andric         "android",
9100b57cec5SDimitry Andric         "androidx",
9110b57cec5SDimitry Andric         "com",
9120b57cec5SDimitry Andric         "dalvik",
9130b57cec5SDimitry Andric         "junit",
9140b57cec5SDimitry Andric         "org",
9150b57cec5SDimitry Andric         "com.google.android.apps.chrome",
9160b57cec5SDimitry Andric         "org.chromium",
9170b57cec5SDimitry Andric         "java",
9180b57cec5SDimitry Andric         "javax",
9190b57cec5SDimitry Andric     };
9200b57cec5SDimitry Andric     ChromiumStyle.SortIncludes = true;
9210b57cec5SDimitry Andric   } else if (Language == FormatStyle::LK_JavaScript) {
9220b57cec5SDimitry Andric     ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
9230b57cec5SDimitry Andric     ChromiumStyle.AllowShortLoopsOnASingleLine = false;
9240b57cec5SDimitry Andric   } else {
9250b57cec5SDimitry Andric     ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
9260b57cec5SDimitry Andric     ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
9270b57cec5SDimitry Andric     ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
9280b57cec5SDimitry Andric     ChromiumStyle.AllowShortLoopsOnASingleLine = false;
9290b57cec5SDimitry Andric     ChromiumStyle.BinPackParameters = false;
9300b57cec5SDimitry Andric     ChromiumStyle.DerivePointerAlignment = false;
9310b57cec5SDimitry Andric     if (Language == FormatStyle::LK_ObjC)
9320b57cec5SDimitry Andric       ChromiumStyle.ColumnLimit = 80;
9330b57cec5SDimitry Andric   }
9340b57cec5SDimitry Andric   return ChromiumStyle;
9350b57cec5SDimitry Andric }
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric FormatStyle getMozillaStyle() {
9380b57cec5SDimitry Andric   FormatStyle MozillaStyle = getLLVMStyle();
9390b57cec5SDimitry Andric   MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
9400b57cec5SDimitry Andric   MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
9410b57cec5SDimitry Andric   MozillaStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
9420b57cec5SDimitry Andric   MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
9430b57cec5SDimitry Andric       FormatStyle::DRTBS_TopLevel;
9440b57cec5SDimitry Andric   MozillaStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9450b57cec5SDimitry Andric   MozillaStyle.BinPackParameters = false;
9460b57cec5SDimitry Andric   MozillaStyle.BinPackArguments = false;
9470b57cec5SDimitry Andric   MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
9480b57cec5SDimitry Andric   MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
9490b57cec5SDimitry Andric   MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
9500b57cec5SDimitry Andric   MozillaStyle.ConstructorInitializerIndentWidth = 2;
9510b57cec5SDimitry Andric   MozillaStyle.ContinuationIndentWidth = 2;
9520b57cec5SDimitry Andric   MozillaStyle.Cpp11BracedListStyle = false;
9530b57cec5SDimitry Andric   MozillaStyle.FixNamespaceComments = false;
9540b57cec5SDimitry Andric   MozillaStyle.IndentCaseLabels = true;
9550b57cec5SDimitry Andric   MozillaStyle.ObjCSpaceAfterProperty = true;
9560b57cec5SDimitry Andric   MozillaStyle.ObjCSpaceBeforeProtocolList = false;
9570b57cec5SDimitry Andric   MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
9580b57cec5SDimitry Andric   MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
9590b57cec5SDimitry Andric   MozillaStyle.SpaceAfterTemplateKeyword = false;
9600b57cec5SDimitry Andric   return MozillaStyle;
9610b57cec5SDimitry Andric }
9620b57cec5SDimitry Andric 
9630b57cec5SDimitry Andric FormatStyle getWebKitStyle() {
9640b57cec5SDimitry Andric   FormatStyle Style = getLLVMStyle();
9650b57cec5SDimitry Andric   Style.AccessModifierOffset = -4;
9660b57cec5SDimitry Andric   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
9670b57cec5SDimitry Andric   Style.AlignOperands = false;
9680b57cec5SDimitry Andric   Style.AlignTrailingComments = false;
9690b57cec5SDimitry Andric   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9700b57cec5SDimitry Andric   Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
9710b57cec5SDimitry Andric   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
9720b57cec5SDimitry Andric   Style.Cpp11BracedListStyle = false;
9730b57cec5SDimitry Andric   Style.ColumnLimit = 0;
9740b57cec5SDimitry Andric   Style.FixNamespaceComments = false;
9750b57cec5SDimitry Andric   Style.IndentWidth = 4;
9760b57cec5SDimitry Andric   Style.NamespaceIndentation = FormatStyle::NI_Inner;
9770b57cec5SDimitry Andric   Style.ObjCBlockIndentWidth = 4;
9780b57cec5SDimitry Andric   Style.ObjCSpaceAfterProperty = true;
9790b57cec5SDimitry Andric   Style.PointerAlignment = FormatStyle::PAS_Left;
9800b57cec5SDimitry Andric   Style.SpaceBeforeCpp11BracedList = true;
9810b57cec5SDimitry Andric   return Style;
9820b57cec5SDimitry Andric }
9830b57cec5SDimitry Andric 
9840b57cec5SDimitry Andric FormatStyle getGNUStyle() {
9850b57cec5SDimitry Andric   FormatStyle Style = getLLVMStyle();
9860b57cec5SDimitry Andric   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
9870b57cec5SDimitry Andric   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
9880b57cec5SDimitry Andric   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9890b57cec5SDimitry Andric   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
9900b57cec5SDimitry Andric   Style.BreakBeforeTernaryOperators = true;
9910b57cec5SDimitry Andric   Style.Cpp11BracedListStyle = false;
9920b57cec5SDimitry Andric   Style.ColumnLimit = 79;
9930b57cec5SDimitry Andric   Style.FixNamespaceComments = false;
9940b57cec5SDimitry Andric   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
9950b57cec5SDimitry Andric   Style.Standard = FormatStyle::LS_Cpp03;
9960b57cec5SDimitry Andric   return Style;
9970b57cec5SDimitry Andric }
9980b57cec5SDimitry Andric 
9990b57cec5SDimitry Andric FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language) {
10000b57cec5SDimitry Andric   FormatStyle Style = getLLVMStyle();
10010b57cec5SDimitry Andric   Style.ColumnLimit = 120;
10020b57cec5SDimitry Andric   Style.TabWidth = 4;
10030b57cec5SDimitry Andric   Style.IndentWidth = 4;
10040b57cec5SDimitry Andric   Style.UseTab = FormatStyle::UT_Never;
10050b57cec5SDimitry Andric   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10060b57cec5SDimitry Andric   Style.BraceWrapping.AfterClass = true;
10070b57cec5SDimitry Andric   Style.BraceWrapping.AfterControlStatement = true;
10080b57cec5SDimitry Andric   Style.BraceWrapping.AfterEnum = true;
10090b57cec5SDimitry Andric   Style.BraceWrapping.AfterFunction = true;
10100b57cec5SDimitry Andric   Style.BraceWrapping.AfterNamespace = true;
10110b57cec5SDimitry Andric   Style.BraceWrapping.AfterObjCDeclaration = true;
10120b57cec5SDimitry Andric   Style.BraceWrapping.AfterStruct = true;
10130b57cec5SDimitry Andric   Style.BraceWrapping.AfterExternBlock = true;
10140b57cec5SDimitry Andric   Style.BraceWrapping.BeforeCatch = true;
10150b57cec5SDimitry Andric   Style.BraceWrapping.BeforeElse = true;
10160b57cec5SDimitry Andric   Style.PenaltyReturnTypeOnItsOwnLine = 1000;
10170b57cec5SDimitry Andric   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10180b57cec5SDimitry Andric   Style.AllowShortBlocksOnASingleLine = false;
10190b57cec5SDimitry Andric   Style.AllowShortCaseLabelsOnASingleLine = false;
10200b57cec5SDimitry Andric   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
10210b57cec5SDimitry Andric   Style.AllowShortLoopsOnASingleLine = false;
10220b57cec5SDimitry Andric   return Style;
10230b57cec5SDimitry Andric }
10240b57cec5SDimitry Andric 
10250b57cec5SDimitry Andric FormatStyle getNoStyle() {
10260b57cec5SDimitry Andric   FormatStyle NoStyle = getLLVMStyle();
10270b57cec5SDimitry Andric   NoStyle.DisableFormat = true;
10280b57cec5SDimitry Andric   NoStyle.SortIncludes = false;
10290b57cec5SDimitry Andric   NoStyle.SortUsingDeclarations = false;
10300b57cec5SDimitry Andric   return NoStyle;
10310b57cec5SDimitry Andric }
10320b57cec5SDimitry Andric 
10330b57cec5SDimitry Andric bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
10340b57cec5SDimitry Andric                         FormatStyle *Style) {
10350b57cec5SDimitry Andric   if (Name.equals_lower("llvm")) {
10360b57cec5SDimitry Andric     *Style = getLLVMStyle(Language);
10370b57cec5SDimitry Andric   } else if (Name.equals_lower("chromium")) {
10380b57cec5SDimitry Andric     *Style = getChromiumStyle(Language);
10390b57cec5SDimitry Andric   } else if (Name.equals_lower("mozilla")) {
10400b57cec5SDimitry Andric     *Style = getMozillaStyle();
10410b57cec5SDimitry Andric   } else if (Name.equals_lower("google")) {
10420b57cec5SDimitry Andric     *Style = getGoogleStyle(Language);
10430b57cec5SDimitry Andric   } else if (Name.equals_lower("webkit")) {
10440b57cec5SDimitry Andric     *Style = getWebKitStyle();
10450b57cec5SDimitry Andric   } else if (Name.equals_lower("gnu")) {
10460b57cec5SDimitry Andric     *Style = getGNUStyle();
10470b57cec5SDimitry Andric   } else if (Name.equals_lower("microsoft")) {
10480b57cec5SDimitry Andric     *Style = getMicrosoftStyle(Language);
10490b57cec5SDimitry Andric   } else if (Name.equals_lower("none")) {
10500b57cec5SDimitry Andric     *Style = getNoStyle();
10510b57cec5SDimitry Andric   } else {
10520b57cec5SDimitry Andric     return false;
10530b57cec5SDimitry Andric   }
10540b57cec5SDimitry Andric 
10550b57cec5SDimitry Andric   Style->Language = Language;
10560b57cec5SDimitry Andric   return true;
10570b57cec5SDimitry Andric }
10580b57cec5SDimitry Andric 
10590b57cec5SDimitry Andric std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
10600b57cec5SDimitry Andric   assert(Style);
10610b57cec5SDimitry Andric   FormatStyle::LanguageKind Language = Style->Language;
10620b57cec5SDimitry Andric   assert(Language != FormatStyle::LK_None);
10630b57cec5SDimitry Andric   if (Text.trim().empty())
10640b57cec5SDimitry Andric     return make_error_code(ParseError::Error);
10650b57cec5SDimitry Andric   Style->StyleSet.Clear();
10660b57cec5SDimitry Andric   std::vector<FormatStyle> Styles;
10670b57cec5SDimitry Andric   llvm::yaml::Input Input(Text);
10680b57cec5SDimitry Andric   // DocumentListTraits<vector<FormatStyle>> uses the context to get default
10690b57cec5SDimitry Andric   // values for the fields, keys for which are missing from the configuration.
10700b57cec5SDimitry Andric   // Mapping also uses the context to get the language to find the correct
10710b57cec5SDimitry Andric   // base style.
10720b57cec5SDimitry Andric   Input.setContext(Style);
10730b57cec5SDimitry Andric   Input >> Styles;
10740b57cec5SDimitry Andric   if (Input.error())
10750b57cec5SDimitry Andric     return Input.error();
10760b57cec5SDimitry Andric 
10770b57cec5SDimitry Andric   for (unsigned i = 0; i < Styles.size(); ++i) {
10780b57cec5SDimitry Andric     // Ensures that only the first configuration can skip the Language option.
10790b57cec5SDimitry Andric     if (Styles[i].Language == FormatStyle::LK_None && i != 0)
10800b57cec5SDimitry Andric       return make_error_code(ParseError::Error);
10810b57cec5SDimitry Andric     // Ensure that each language is configured at most once.
10820b57cec5SDimitry Andric     for (unsigned j = 0; j < i; ++j) {
10830b57cec5SDimitry Andric       if (Styles[i].Language == Styles[j].Language) {
10840b57cec5SDimitry Andric         LLVM_DEBUG(llvm::dbgs()
10850b57cec5SDimitry Andric                    << "Duplicate languages in the config file on positions "
10860b57cec5SDimitry Andric                    << j << " and " << i << "\n");
10870b57cec5SDimitry Andric         return make_error_code(ParseError::Error);
10880b57cec5SDimitry Andric       }
10890b57cec5SDimitry Andric     }
10900b57cec5SDimitry Andric   }
10910b57cec5SDimitry Andric   // Look for a suitable configuration starting from the end, so we can
10920b57cec5SDimitry Andric   // find the configuration for the specific language first, and the default
10930b57cec5SDimitry Andric   // configuration (which can only be at slot 0) after it.
10940b57cec5SDimitry Andric   FormatStyle::FormatStyleSet StyleSet;
10950b57cec5SDimitry Andric   bool LanguageFound = false;
10960b57cec5SDimitry Andric   for (int i = Styles.size() - 1; i >= 0; --i) {
10970b57cec5SDimitry Andric     if (Styles[i].Language != FormatStyle::LK_None)
10980b57cec5SDimitry Andric       StyleSet.Add(Styles[i]);
10990b57cec5SDimitry Andric     if (Styles[i].Language == Language)
11000b57cec5SDimitry Andric       LanguageFound = true;
11010b57cec5SDimitry Andric   }
11020b57cec5SDimitry Andric   if (!LanguageFound) {
11030b57cec5SDimitry Andric     if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None)
11040b57cec5SDimitry Andric       return make_error_code(ParseError::Unsuitable);
11050b57cec5SDimitry Andric     FormatStyle DefaultStyle = Styles[0];
11060b57cec5SDimitry Andric     DefaultStyle.Language = Language;
11070b57cec5SDimitry Andric     StyleSet.Add(std::move(DefaultStyle));
11080b57cec5SDimitry Andric   }
11090b57cec5SDimitry Andric   *Style = *StyleSet.Get(Language);
11100b57cec5SDimitry Andric   return make_error_code(ParseError::Success);
11110b57cec5SDimitry Andric }
11120b57cec5SDimitry Andric 
11130b57cec5SDimitry Andric std::string configurationAsText(const FormatStyle &Style) {
11140b57cec5SDimitry Andric   std::string Text;
11150b57cec5SDimitry Andric   llvm::raw_string_ostream Stream(Text);
11160b57cec5SDimitry Andric   llvm::yaml::Output Output(Stream);
11170b57cec5SDimitry Andric   // We use the same mapping method for input and output, so we need a non-const
11180b57cec5SDimitry Andric   // reference here.
11190b57cec5SDimitry Andric   FormatStyle NonConstStyle = expandPresets(Style);
11200b57cec5SDimitry Andric   Output << NonConstStyle;
11210b57cec5SDimitry Andric   return Stream.str();
11220b57cec5SDimitry Andric }
11230b57cec5SDimitry Andric 
11240b57cec5SDimitry Andric llvm::Optional<FormatStyle>
11250b57cec5SDimitry Andric FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const {
11260b57cec5SDimitry Andric   if (!Styles)
11270b57cec5SDimitry Andric     return None;
11280b57cec5SDimitry Andric   auto It = Styles->find(Language);
11290b57cec5SDimitry Andric   if (It == Styles->end())
11300b57cec5SDimitry Andric     return None;
11310b57cec5SDimitry Andric   FormatStyle Style = It->second;
11320b57cec5SDimitry Andric   Style.StyleSet = *this;
11330b57cec5SDimitry Andric   return Style;
11340b57cec5SDimitry Andric }
11350b57cec5SDimitry Andric 
11360b57cec5SDimitry Andric void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
11370b57cec5SDimitry Andric   assert(Style.Language != LK_None &&
11380b57cec5SDimitry Andric          "Cannot add a style for LK_None to a StyleSet");
11390b57cec5SDimitry Andric   assert(
11400b57cec5SDimitry Andric       !Style.StyleSet.Styles &&
11410b57cec5SDimitry Andric       "Cannot add a style associated with an existing StyleSet to a StyleSet");
11420b57cec5SDimitry Andric   if (!Styles)
11430b57cec5SDimitry Andric     Styles = std::make_shared<MapType>();
11440b57cec5SDimitry Andric   (*Styles)[Style.Language] = std::move(Style);
11450b57cec5SDimitry Andric }
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
11480b57cec5SDimitry Andric 
11490b57cec5SDimitry Andric llvm::Optional<FormatStyle>
11500b57cec5SDimitry Andric FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const {
11510b57cec5SDimitry Andric   return StyleSet.Get(Language);
11520b57cec5SDimitry Andric }
11530b57cec5SDimitry Andric 
11540b57cec5SDimitry Andric namespace {
11550b57cec5SDimitry Andric 
11560b57cec5SDimitry Andric class JavaScriptRequoter : public TokenAnalyzer {
11570b57cec5SDimitry Andric public:
11580b57cec5SDimitry Andric   JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
11590b57cec5SDimitry Andric       : TokenAnalyzer(Env, Style) {}
11600b57cec5SDimitry Andric 
11610b57cec5SDimitry Andric   std::pair<tooling::Replacements, unsigned>
11620b57cec5SDimitry Andric   analyze(TokenAnnotator &Annotator,
11630b57cec5SDimitry Andric           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
11640b57cec5SDimitry Andric           FormatTokenLexer &Tokens) override {
11650b57cec5SDimitry Andric     AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
11660b57cec5SDimitry Andric     tooling::Replacements Result;
11670b57cec5SDimitry Andric     requoteJSStringLiteral(AnnotatedLines, Result);
11680b57cec5SDimitry Andric     return {Result, 0};
11690b57cec5SDimitry Andric   }
11700b57cec5SDimitry Andric 
11710b57cec5SDimitry Andric private:
11720b57cec5SDimitry Andric   // Replaces double/single-quoted string literal as appropriate, re-escaping
11730b57cec5SDimitry Andric   // the contents in the process.
11740b57cec5SDimitry Andric   void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
11750b57cec5SDimitry Andric                               tooling::Replacements &Result) {
11760b57cec5SDimitry Andric     for (AnnotatedLine *Line : Lines) {
11770b57cec5SDimitry Andric       requoteJSStringLiteral(Line->Children, Result);
11780b57cec5SDimitry Andric       if (!Line->Affected)
11790b57cec5SDimitry Andric         continue;
11800b57cec5SDimitry Andric       for (FormatToken *FormatTok = Line->First; FormatTok;
11810b57cec5SDimitry Andric            FormatTok = FormatTok->Next) {
11820b57cec5SDimitry Andric         StringRef Input = FormatTok->TokenText;
11830b57cec5SDimitry Andric         if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
11840b57cec5SDimitry Andric             // NB: testing for not starting with a double quote to avoid
11850b57cec5SDimitry Andric             // breaking `template strings`.
11860b57cec5SDimitry Andric             (Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
11870b57cec5SDimitry Andric              !Input.startswith("\"")) ||
11880b57cec5SDimitry Andric             (Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
11890b57cec5SDimitry Andric              !Input.startswith("\'")))
11900b57cec5SDimitry Andric           continue;
11910b57cec5SDimitry Andric 
11920b57cec5SDimitry Andric         // Change start and end quote.
11930b57cec5SDimitry Andric         bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
11940b57cec5SDimitry Andric         SourceLocation Start = FormatTok->Tok.getLocation();
11950b57cec5SDimitry Andric         auto Replace = [&](SourceLocation Start, unsigned Length,
11960b57cec5SDimitry Andric                            StringRef ReplacementText) {
11970b57cec5SDimitry Andric           auto Err = Result.add(tooling::Replacement(
11980b57cec5SDimitry Andric               Env.getSourceManager(), Start, Length, ReplacementText));
11990b57cec5SDimitry Andric           // FIXME: handle error. For now, print error message and skip the
12000b57cec5SDimitry Andric           // replacement for release version.
12010b57cec5SDimitry Andric           if (Err) {
12020b57cec5SDimitry Andric             llvm::errs() << llvm::toString(std::move(Err)) << "\n";
12030b57cec5SDimitry Andric             assert(false);
12040b57cec5SDimitry Andric           }
12050b57cec5SDimitry Andric         };
12060b57cec5SDimitry Andric         Replace(Start, 1, IsSingle ? "'" : "\"");
12070b57cec5SDimitry Andric         Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
12080b57cec5SDimitry Andric                 IsSingle ? "'" : "\"");
12090b57cec5SDimitry Andric 
12100b57cec5SDimitry Andric         // Escape internal quotes.
12110b57cec5SDimitry Andric         bool Escaped = false;
12120b57cec5SDimitry Andric         for (size_t i = 1; i < Input.size() - 1; i++) {
12130b57cec5SDimitry Andric           switch (Input[i]) {
12140b57cec5SDimitry Andric           case '\\':
12150b57cec5SDimitry Andric             if (!Escaped && i + 1 < Input.size() &&
12160b57cec5SDimitry Andric                 ((IsSingle && Input[i + 1] == '"') ||
12170b57cec5SDimitry Andric                  (!IsSingle && Input[i + 1] == '\''))) {
12180b57cec5SDimitry Andric               // Remove this \, it's escaping a " or ' that no longer needs
12190b57cec5SDimitry Andric               // escaping
12200b57cec5SDimitry Andric               Replace(Start.getLocWithOffset(i), 1, "");
12210b57cec5SDimitry Andric               continue;
12220b57cec5SDimitry Andric             }
12230b57cec5SDimitry Andric             Escaped = !Escaped;
12240b57cec5SDimitry Andric             break;
12250b57cec5SDimitry Andric           case '\"':
12260b57cec5SDimitry Andric           case '\'':
12270b57cec5SDimitry Andric             if (!Escaped && IsSingle == (Input[i] == '\'')) {
12280b57cec5SDimitry Andric               // Escape the quote.
12290b57cec5SDimitry Andric               Replace(Start.getLocWithOffset(i), 0, "\\");
12300b57cec5SDimitry Andric             }
12310b57cec5SDimitry Andric             Escaped = false;
12320b57cec5SDimitry Andric             break;
12330b57cec5SDimitry Andric           default:
12340b57cec5SDimitry Andric             Escaped = false;
12350b57cec5SDimitry Andric             break;
12360b57cec5SDimitry Andric           }
12370b57cec5SDimitry Andric         }
12380b57cec5SDimitry Andric       }
12390b57cec5SDimitry Andric     }
12400b57cec5SDimitry Andric   }
12410b57cec5SDimitry Andric };
12420b57cec5SDimitry Andric 
12430b57cec5SDimitry Andric class Formatter : public TokenAnalyzer {
12440b57cec5SDimitry Andric public:
12450b57cec5SDimitry Andric   Formatter(const Environment &Env, const FormatStyle &Style,
12460b57cec5SDimitry Andric             FormattingAttemptStatus *Status)
12470b57cec5SDimitry Andric       : TokenAnalyzer(Env, Style), Status(Status) {}
12480b57cec5SDimitry Andric 
12490b57cec5SDimitry Andric   std::pair<tooling::Replacements, unsigned>
12500b57cec5SDimitry Andric   analyze(TokenAnnotator &Annotator,
12510b57cec5SDimitry Andric           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
12520b57cec5SDimitry Andric           FormatTokenLexer &Tokens) override {
12530b57cec5SDimitry Andric     tooling::Replacements Result;
12540b57cec5SDimitry Andric     deriveLocalStyle(AnnotatedLines);
12550b57cec5SDimitry Andric     AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
12560b57cec5SDimitry Andric     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
12570b57cec5SDimitry Andric       Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
12580b57cec5SDimitry Andric     }
12590b57cec5SDimitry Andric     Annotator.setCommentLineLevels(AnnotatedLines);
12600b57cec5SDimitry Andric 
12610b57cec5SDimitry Andric     WhitespaceManager Whitespaces(
12620b57cec5SDimitry Andric         Env.getSourceManager(), Style,
12630b57cec5SDimitry Andric         inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID())));
12640b57cec5SDimitry Andric     ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
12650b57cec5SDimitry Andric                                   Env.getSourceManager(), Whitespaces, Encoding,
12660b57cec5SDimitry Andric                                   BinPackInconclusiveFunctions);
12670b57cec5SDimitry Andric     unsigned Penalty =
12680b57cec5SDimitry Andric         UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
12690b57cec5SDimitry Andric                                Tokens.getKeywords(), Env.getSourceManager(),
12700b57cec5SDimitry Andric                                Status)
12710b57cec5SDimitry Andric             .format(AnnotatedLines, /*DryRun=*/false,
12720b57cec5SDimitry Andric                     /*AdditionalIndent=*/0,
12730b57cec5SDimitry Andric                     /*FixBadIndentation=*/false,
12740b57cec5SDimitry Andric                     /*FirstStartColumn=*/Env.getFirstStartColumn(),
12750b57cec5SDimitry Andric                     /*NextStartColumn=*/Env.getNextStartColumn(),
12760b57cec5SDimitry Andric                     /*LastStartColumn=*/Env.getLastStartColumn());
12770b57cec5SDimitry Andric     for (const auto &R : Whitespaces.generateReplacements())
12780b57cec5SDimitry Andric       if (Result.add(R))
12790b57cec5SDimitry Andric         return std::make_pair(Result, 0);
12800b57cec5SDimitry Andric     return std::make_pair(Result, Penalty);
12810b57cec5SDimitry Andric   }
12820b57cec5SDimitry Andric 
12830b57cec5SDimitry Andric private:
12840b57cec5SDimitry Andric   static bool inputUsesCRLF(StringRef Text) {
12850b57cec5SDimitry Andric     return Text.count('\r') * 2 > Text.count('\n');
12860b57cec5SDimitry Andric   }
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric   bool
12890b57cec5SDimitry Andric   hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
12900b57cec5SDimitry Andric     for (const AnnotatedLine *Line : Lines) {
12910b57cec5SDimitry Andric       if (hasCpp03IncompatibleFormat(Line->Children))
12920b57cec5SDimitry Andric         return true;
12930b57cec5SDimitry Andric       for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
12940b57cec5SDimitry Andric         if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
12950b57cec5SDimitry Andric           if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
12960b57cec5SDimitry Andric             return true;
12970b57cec5SDimitry Andric           if (Tok->is(TT_TemplateCloser) &&
12980b57cec5SDimitry Andric               Tok->Previous->is(TT_TemplateCloser))
12990b57cec5SDimitry Andric             return true;
13000b57cec5SDimitry Andric         }
13010b57cec5SDimitry Andric       }
13020b57cec5SDimitry Andric     }
13030b57cec5SDimitry Andric     return false;
13040b57cec5SDimitry Andric   }
13050b57cec5SDimitry Andric 
13060b57cec5SDimitry Andric   int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
13070b57cec5SDimitry Andric     int AlignmentDiff = 0;
13080b57cec5SDimitry Andric     for (const AnnotatedLine *Line : Lines) {
13090b57cec5SDimitry Andric       AlignmentDiff += countVariableAlignments(Line->Children);
13100b57cec5SDimitry Andric       for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
13110b57cec5SDimitry Andric         if (!Tok->is(TT_PointerOrReference))
13120b57cec5SDimitry Andric           continue;
13130b57cec5SDimitry Andric         bool SpaceBefore =
13140b57cec5SDimitry Andric             Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
13150b57cec5SDimitry Andric         bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
13160b57cec5SDimitry Andric                           Tok->Next->WhitespaceRange.getEnd();
13170b57cec5SDimitry Andric         if (SpaceBefore && !SpaceAfter)
13180b57cec5SDimitry Andric           ++AlignmentDiff;
13190b57cec5SDimitry Andric         if (!SpaceBefore && SpaceAfter)
13200b57cec5SDimitry Andric           --AlignmentDiff;
13210b57cec5SDimitry Andric       }
13220b57cec5SDimitry Andric     }
13230b57cec5SDimitry Andric     return AlignmentDiff;
13240b57cec5SDimitry Andric   }
13250b57cec5SDimitry Andric 
13260b57cec5SDimitry Andric   void
13270b57cec5SDimitry Andric   deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
13280b57cec5SDimitry Andric     bool HasBinPackedFunction = false;
13290b57cec5SDimitry Andric     bool HasOnePerLineFunction = false;
13300b57cec5SDimitry Andric     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
13310b57cec5SDimitry Andric       if (!AnnotatedLines[i]->First->Next)
13320b57cec5SDimitry Andric         continue;
13330b57cec5SDimitry Andric       FormatToken *Tok = AnnotatedLines[i]->First->Next;
13340b57cec5SDimitry Andric       while (Tok->Next) {
13350b57cec5SDimitry Andric         if (Tok->PackingKind == PPK_BinPacked)
13360b57cec5SDimitry Andric           HasBinPackedFunction = true;
13370b57cec5SDimitry Andric         if (Tok->PackingKind == PPK_OnePerLine)
13380b57cec5SDimitry Andric           HasOnePerLineFunction = true;
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric         Tok = Tok->Next;
13410b57cec5SDimitry Andric       }
13420b57cec5SDimitry Andric     }
13430b57cec5SDimitry Andric     if (Style.DerivePointerAlignment)
13440b57cec5SDimitry Andric       Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
13450b57cec5SDimitry Andric                                    ? FormatStyle::PAS_Left
13460b57cec5SDimitry Andric                                    : FormatStyle::PAS_Right;
13470b57cec5SDimitry Andric     if (Style.Standard == FormatStyle::LS_Auto)
13480b57cec5SDimitry Andric       Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
13490b57cec5SDimitry Andric                            ? FormatStyle::LS_Cpp11
13500b57cec5SDimitry Andric                            : FormatStyle::LS_Cpp03;
13510b57cec5SDimitry Andric     BinPackInconclusiveFunctions =
13520b57cec5SDimitry Andric         HasBinPackedFunction || !HasOnePerLineFunction;
13530b57cec5SDimitry Andric   }
13540b57cec5SDimitry Andric 
13550b57cec5SDimitry Andric   bool BinPackInconclusiveFunctions;
13560b57cec5SDimitry Andric   FormattingAttemptStatus *Status;
13570b57cec5SDimitry Andric };
13580b57cec5SDimitry Andric 
13590b57cec5SDimitry Andric // This class clean up the erroneous/redundant code around the given ranges in
13600b57cec5SDimitry Andric // file.
13610b57cec5SDimitry Andric class Cleaner : public TokenAnalyzer {
13620b57cec5SDimitry Andric public:
13630b57cec5SDimitry Andric   Cleaner(const Environment &Env, const FormatStyle &Style)
13640b57cec5SDimitry Andric       : TokenAnalyzer(Env, Style),
13650b57cec5SDimitry Andric         DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
13660b57cec5SDimitry Andric 
13670b57cec5SDimitry Andric   // FIXME: eliminate unused parameters.
13680b57cec5SDimitry Andric   std::pair<tooling::Replacements, unsigned>
13690b57cec5SDimitry Andric   analyze(TokenAnnotator &Annotator,
13700b57cec5SDimitry Andric           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
13710b57cec5SDimitry Andric           FormatTokenLexer &Tokens) override {
13720b57cec5SDimitry Andric     // FIXME: in the current implementation the granularity of affected range
13730b57cec5SDimitry Andric     // is an annotated line. However, this is not sufficient. Furthermore,
13740b57cec5SDimitry Andric     // redundant code introduced by replacements does not necessarily
13750b57cec5SDimitry Andric     // intercept with ranges of replacements that result in the redundancy.
13760b57cec5SDimitry Andric     // To determine if some redundant code is actually introduced by
13770b57cec5SDimitry Andric     // replacements(e.g. deletions), we need to come up with a more
13780b57cec5SDimitry Andric     // sophisticated way of computing affected ranges.
13790b57cec5SDimitry Andric     AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
13800b57cec5SDimitry Andric 
13810b57cec5SDimitry Andric     checkEmptyNamespace(AnnotatedLines);
13820b57cec5SDimitry Andric 
13830b57cec5SDimitry Andric     for (auto &Line : AnnotatedLines) {
13840b57cec5SDimitry Andric       if (Line->Affected) {
13850b57cec5SDimitry Andric         cleanupRight(Line->First, tok::comma, tok::comma);
13860b57cec5SDimitry Andric         cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
13870b57cec5SDimitry Andric         cleanupRight(Line->First, tok::l_paren, tok::comma);
13880b57cec5SDimitry Andric         cleanupLeft(Line->First, tok::comma, tok::r_paren);
13890b57cec5SDimitry Andric         cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
13900b57cec5SDimitry Andric         cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
13910b57cec5SDimitry Andric         cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
13920b57cec5SDimitry Andric       }
13930b57cec5SDimitry Andric     }
13940b57cec5SDimitry Andric 
13950b57cec5SDimitry Andric     return {generateFixes(), 0};
13960b57cec5SDimitry Andric   }
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric private:
13990b57cec5SDimitry Andric   bool containsOnlyComments(const AnnotatedLine &Line) {
14000b57cec5SDimitry Andric     for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
14010b57cec5SDimitry Andric       if (Tok->isNot(tok::comment))
14020b57cec5SDimitry Andric         return false;
14030b57cec5SDimitry Andric     }
14040b57cec5SDimitry Andric     return true;
14050b57cec5SDimitry Andric   }
14060b57cec5SDimitry Andric 
14070b57cec5SDimitry Andric   // Iterate through all lines and remove any empty (nested) namespaces.
14080b57cec5SDimitry Andric   void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
14090b57cec5SDimitry Andric     std::set<unsigned> DeletedLines;
14100b57cec5SDimitry Andric     for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
14110b57cec5SDimitry Andric       auto &Line = *AnnotatedLines[i];
14120b57cec5SDimitry Andric       if (Line.startsWithNamespace()) {
14130b57cec5SDimitry Andric         checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
14140b57cec5SDimitry Andric       }
14150b57cec5SDimitry Andric     }
14160b57cec5SDimitry Andric 
14170b57cec5SDimitry Andric     for (auto Line : DeletedLines) {
14180b57cec5SDimitry Andric       FormatToken *Tok = AnnotatedLines[Line]->First;
14190b57cec5SDimitry Andric       while (Tok) {
14200b57cec5SDimitry Andric         deleteToken(Tok);
14210b57cec5SDimitry Andric         Tok = Tok->Next;
14220b57cec5SDimitry Andric       }
14230b57cec5SDimitry Andric     }
14240b57cec5SDimitry Andric   }
14250b57cec5SDimitry Andric 
14260b57cec5SDimitry Andric   // The function checks if the namespace, which starts from \p CurrentLine, and
14270b57cec5SDimitry Andric   // its nested namespaces are empty and delete them if they are empty. It also
14280b57cec5SDimitry Andric   // sets \p NewLine to the last line checked.
14290b57cec5SDimitry Andric   // Returns true if the current namespace is empty.
14300b57cec5SDimitry Andric   bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
14310b57cec5SDimitry Andric                            unsigned CurrentLine, unsigned &NewLine,
14320b57cec5SDimitry Andric                            std::set<unsigned> &DeletedLines) {
14330b57cec5SDimitry Andric     unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
14340b57cec5SDimitry Andric     if (Style.BraceWrapping.AfterNamespace) {
14350b57cec5SDimitry Andric       // If the left brace is in a new line, we should consume it first so that
14360b57cec5SDimitry Andric       // it does not make the namespace non-empty.
14370b57cec5SDimitry Andric       // FIXME: error handling if there is no left brace.
14380b57cec5SDimitry Andric       if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
14390b57cec5SDimitry Andric         NewLine = CurrentLine;
14400b57cec5SDimitry Andric         return false;
14410b57cec5SDimitry Andric       }
14420b57cec5SDimitry Andric     } else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
14430b57cec5SDimitry Andric       return false;
14440b57cec5SDimitry Andric     }
14450b57cec5SDimitry Andric     while (++CurrentLine < End) {
14460b57cec5SDimitry Andric       if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
14470b57cec5SDimitry Andric         break;
14480b57cec5SDimitry Andric 
14490b57cec5SDimitry Andric       if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
14500b57cec5SDimitry Andric         if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
14510b57cec5SDimitry Andric                                  DeletedLines))
14520b57cec5SDimitry Andric           return false;
14530b57cec5SDimitry Andric         CurrentLine = NewLine;
14540b57cec5SDimitry Andric         continue;
14550b57cec5SDimitry Andric       }
14560b57cec5SDimitry Andric 
14570b57cec5SDimitry Andric       if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
14580b57cec5SDimitry Andric         continue;
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric       // If there is anything other than comments or nested namespaces in the
14610b57cec5SDimitry Andric       // current namespace, the namespace cannot be empty.
14620b57cec5SDimitry Andric       NewLine = CurrentLine;
14630b57cec5SDimitry Andric       return false;
14640b57cec5SDimitry Andric     }
14650b57cec5SDimitry Andric 
14660b57cec5SDimitry Andric     NewLine = CurrentLine;
14670b57cec5SDimitry Andric     if (CurrentLine >= End)
14680b57cec5SDimitry Andric       return false;
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric     // Check if the empty namespace is actually affected by changed ranges.
14710b57cec5SDimitry Andric     if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
14720b57cec5SDimitry Andric             AnnotatedLines[InitLine]->First->Tok.getLocation(),
14730b57cec5SDimitry Andric             AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
14740b57cec5SDimitry Andric       return false;
14750b57cec5SDimitry Andric 
14760b57cec5SDimitry Andric     for (unsigned i = InitLine; i <= CurrentLine; ++i) {
14770b57cec5SDimitry Andric       DeletedLines.insert(i);
14780b57cec5SDimitry Andric     }
14790b57cec5SDimitry Andric 
14800b57cec5SDimitry Andric     return true;
14810b57cec5SDimitry Andric   }
14820b57cec5SDimitry Andric 
14830b57cec5SDimitry Andric   // Checks pairs {start, start->next},..., {end->previous, end} and deletes one
14840b57cec5SDimitry Andric   // of the token in the pair if the left token has \p LK token kind and the
14850b57cec5SDimitry Andric   // right token has \p RK token kind. If \p DeleteLeft is true, the left token
14860b57cec5SDimitry Andric   // is deleted on match; otherwise, the right token is deleted.
14870b57cec5SDimitry Andric   template <typename LeftKind, typename RightKind>
14880b57cec5SDimitry Andric   void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
14890b57cec5SDimitry Andric                    bool DeleteLeft) {
14900b57cec5SDimitry Andric     auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
14910b57cec5SDimitry Andric       for (auto *Res = Tok.Next; Res; Res = Res->Next)
14920b57cec5SDimitry Andric         if (!Res->is(tok::comment) &&
14930b57cec5SDimitry Andric             DeletedTokens.find(Res) == DeletedTokens.end())
14940b57cec5SDimitry Andric           return Res;
14950b57cec5SDimitry Andric       return nullptr;
14960b57cec5SDimitry Andric     };
14970b57cec5SDimitry Andric     for (auto *Left = Start; Left;) {
14980b57cec5SDimitry Andric       auto *Right = NextNotDeleted(*Left);
14990b57cec5SDimitry Andric       if (!Right)
15000b57cec5SDimitry Andric         break;
15010b57cec5SDimitry Andric       if (Left->is(LK) && Right->is(RK)) {
15020b57cec5SDimitry Andric         deleteToken(DeleteLeft ? Left : Right);
15030b57cec5SDimitry Andric         for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
15040b57cec5SDimitry Andric           deleteToken(Tok);
15050b57cec5SDimitry Andric         // If the right token is deleted, we should keep the left token
15060b57cec5SDimitry Andric         // unchanged and pair it with the new right token.
15070b57cec5SDimitry Andric         if (!DeleteLeft)
15080b57cec5SDimitry Andric           continue;
15090b57cec5SDimitry Andric       }
15100b57cec5SDimitry Andric       Left = Right;
15110b57cec5SDimitry Andric     }
15120b57cec5SDimitry Andric   }
15130b57cec5SDimitry Andric 
15140b57cec5SDimitry Andric   template <typename LeftKind, typename RightKind>
15150b57cec5SDimitry Andric   void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
15160b57cec5SDimitry Andric     cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
15170b57cec5SDimitry Andric   }
15180b57cec5SDimitry Andric 
15190b57cec5SDimitry Andric   template <typename LeftKind, typename RightKind>
15200b57cec5SDimitry Andric   void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
15210b57cec5SDimitry Andric     cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
15220b57cec5SDimitry Andric   }
15230b57cec5SDimitry Andric 
15240b57cec5SDimitry Andric   // Delete the given token.
15250b57cec5SDimitry Andric   inline void deleteToken(FormatToken *Tok) {
15260b57cec5SDimitry Andric     if (Tok)
15270b57cec5SDimitry Andric       DeletedTokens.insert(Tok);
15280b57cec5SDimitry Andric   }
15290b57cec5SDimitry Andric 
15300b57cec5SDimitry Andric   tooling::Replacements generateFixes() {
15310b57cec5SDimitry Andric     tooling::Replacements Fixes;
15320b57cec5SDimitry Andric     std::vector<FormatToken *> Tokens;
15330b57cec5SDimitry Andric     std::copy(DeletedTokens.begin(), DeletedTokens.end(),
15340b57cec5SDimitry Andric               std::back_inserter(Tokens));
15350b57cec5SDimitry Andric 
15360b57cec5SDimitry Andric     // Merge multiple continuous token deletions into one big deletion so that
15370b57cec5SDimitry Andric     // the number of replacements can be reduced. This makes computing affected
15380b57cec5SDimitry Andric     // ranges more efficient when we run reformat on the changed code.
15390b57cec5SDimitry Andric     unsigned Idx = 0;
15400b57cec5SDimitry Andric     while (Idx < Tokens.size()) {
15410b57cec5SDimitry Andric       unsigned St = Idx, End = Idx;
15420b57cec5SDimitry Andric       while ((End + 1) < Tokens.size() &&
15430b57cec5SDimitry Andric              Tokens[End]->Next == Tokens[End + 1]) {
15440b57cec5SDimitry Andric         End++;
15450b57cec5SDimitry Andric       }
15460b57cec5SDimitry Andric       auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
15470b57cec5SDimitry Andric                                               Tokens[End]->Tok.getEndLoc());
15480b57cec5SDimitry Andric       auto Err =
15490b57cec5SDimitry Andric           Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
15500b57cec5SDimitry Andric       // FIXME: better error handling. for now just print error message and skip
15510b57cec5SDimitry Andric       // for the release version.
15520b57cec5SDimitry Andric       if (Err) {
15530b57cec5SDimitry Andric         llvm::errs() << llvm::toString(std::move(Err)) << "\n";
15540b57cec5SDimitry Andric         assert(false && "Fixes must not conflict!");
15550b57cec5SDimitry Andric       }
15560b57cec5SDimitry Andric       Idx = End + 1;
15570b57cec5SDimitry Andric     }
15580b57cec5SDimitry Andric 
15590b57cec5SDimitry Andric     return Fixes;
15600b57cec5SDimitry Andric   }
15610b57cec5SDimitry Andric 
15620b57cec5SDimitry Andric   // Class for less-than inequality comparason for the set `RedundantTokens`.
15630b57cec5SDimitry Andric   // We store tokens in the order they appear in the translation unit so that
15640b57cec5SDimitry Andric   // we do not need to sort them in `generateFixes()`.
15650b57cec5SDimitry Andric   struct FormatTokenLess {
15660b57cec5SDimitry Andric     FormatTokenLess(const SourceManager &SM) : SM(SM) {}
15670b57cec5SDimitry Andric 
15680b57cec5SDimitry Andric     bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
15690b57cec5SDimitry Andric       return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
15700b57cec5SDimitry Andric                                           RHS->Tok.getLocation());
15710b57cec5SDimitry Andric     }
15720b57cec5SDimitry Andric     const SourceManager &SM;
15730b57cec5SDimitry Andric   };
15740b57cec5SDimitry Andric 
15750b57cec5SDimitry Andric   // Tokens to be deleted.
15760b57cec5SDimitry Andric   std::set<FormatToken *, FormatTokenLess> DeletedTokens;
15770b57cec5SDimitry Andric };
15780b57cec5SDimitry Andric 
15790b57cec5SDimitry Andric class ObjCHeaderStyleGuesser : public TokenAnalyzer {
15800b57cec5SDimitry Andric public:
15810b57cec5SDimitry Andric   ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
15820b57cec5SDimitry Andric       : TokenAnalyzer(Env, Style), IsObjC(false) {}
15830b57cec5SDimitry Andric 
15840b57cec5SDimitry Andric   std::pair<tooling::Replacements, unsigned>
15850b57cec5SDimitry Andric   analyze(TokenAnnotator &Annotator,
15860b57cec5SDimitry Andric           SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
15870b57cec5SDimitry Andric           FormatTokenLexer &Tokens) override {
15880b57cec5SDimitry Andric     assert(Style.Language == FormatStyle::LK_Cpp);
15890b57cec5SDimitry Andric     IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
15900b57cec5SDimitry Andric                          Tokens.getKeywords());
15910b57cec5SDimitry Andric     tooling::Replacements Result;
15920b57cec5SDimitry Andric     return {Result, 0};
15930b57cec5SDimitry Andric   }
15940b57cec5SDimitry Andric 
15950b57cec5SDimitry Andric   bool isObjC() { return IsObjC; }
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric private:
15980b57cec5SDimitry Andric   static bool
15990b57cec5SDimitry Andric   guessIsObjC(const SourceManager &SourceManager,
16000b57cec5SDimitry Andric               const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
16010b57cec5SDimitry Andric               const AdditionalKeywords &Keywords) {
16020b57cec5SDimitry Andric     // Keep this array sorted, since we are binary searching over it.
16030b57cec5SDimitry Andric     static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
16040b57cec5SDimitry Andric         "CGFloat",
16050b57cec5SDimitry Andric         "CGPoint",
16060b57cec5SDimitry Andric         "CGPointMake",
16070b57cec5SDimitry Andric         "CGPointZero",
16080b57cec5SDimitry Andric         "CGRect",
16090b57cec5SDimitry Andric         "CGRectEdge",
16100b57cec5SDimitry Andric         "CGRectInfinite",
16110b57cec5SDimitry Andric         "CGRectMake",
16120b57cec5SDimitry Andric         "CGRectNull",
16130b57cec5SDimitry Andric         "CGRectZero",
16140b57cec5SDimitry Andric         "CGSize",
16150b57cec5SDimitry Andric         "CGSizeMake",
16160b57cec5SDimitry Andric         "CGVector",
16170b57cec5SDimitry Andric         "CGVectorMake",
16180b57cec5SDimitry Andric         "NSAffineTransform",
16190b57cec5SDimitry Andric         "NSArray",
16200b57cec5SDimitry Andric         "NSAttributedString",
16210b57cec5SDimitry Andric         "NSBlockOperation",
16220b57cec5SDimitry Andric         "NSBundle",
16230b57cec5SDimitry Andric         "NSCache",
16240b57cec5SDimitry Andric         "NSCalendar",
16250b57cec5SDimitry Andric         "NSCharacterSet",
16260b57cec5SDimitry Andric         "NSCountedSet",
16270b57cec5SDimitry Andric         "NSData",
16280b57cec5SDimitry Andric         "NSDataDetector",
16290b57cec5SDimitry Andric         "NSDecimal",
16300b57cec5SDimitry Andric         "NSDecimalNumber",
16310b57cec5SDimitry Andric         "NSDictionary",
16320b57cec5SDimitry Andric         "NSEdgeInsets",
16330b57cec5SDimitry Andric         "NSHashTable",
16340b57cec5SDimitry Andric         "NSIndexPath",
16350b57cec5SDimitry Andric         "NSIndexSet",
16360b57cec5SDimitry Andric         "NSInteger",
16370b57cec5SDimitry Andric         "NSInvocationOperation",
16380b57cec5SDimitry Andric         "NSLocale",
16390b57cec5SDimitry Andric         "NSMapTable",
16400b57cec5SDimitry Andric         "NSMutableArray",
16410b57cec5SDimitry Andric         "NSMutableAttributedString",
16420b57cec5SDimitry Andric         "NSMutableCharacterSet",
16430b57cec5SDimitry Andric         "NSMutableData",
16440b57cec5SDimitry Andric         "NSMutableDictionary",
16450b57cec5SDimitry Andric         "NSMutableIndexSet",
16460b57cec5SDimitry Andric         "NSMutableOrderedSet",
16470b57cec5SDimitry Andric         "NSMutableSet",
16480b57cec5SDimitry Andric         "NSMutableString",
16490b57cec5SDimitry Andric         "NSNumber",
16500b57cec5SDimitry Andric         "NSNumberFormatter",
16510b57cec5SDimitry Andric         "NSObject",
16520b57cec5SDimitry Andric         "NSOperation",
16530b57cec5SDimitry Andric         "NSOperationQueue",
16540b57cec5SDimitry Andric         "NSOperationQueuePriority",
16550b57cec5SDimitry Andric         "NSOrderedSet",
16560b57cec5SDimitry Andric         "NSPoint",
16570b57cec5SDimitry Andric         "NSPointerArray",
16580b57cec5SDimitry Andric         "NSQualityOfService",
16590b57cec5SDimitry Andric         "NSRange",
16600b57cec5SDimitry Andric         "NSRect",
16610b57cec5SDimitry Andric         "NSRegularExpression",
16620b57cec5SDimitry Andric         "NSSet",
16630b57cec5SDimitry Andric         "NSSize",
16640b57cec5SDimitry Andric         "NSString",
16650b57cec5SDimitry Andric         "NSTimeZone",
16660b57cec5SDimitry Andric         "NSUInteger",
16670b57cec5SDimitry Andric         "NSURL",
16680b57cec5SDimitry Andric         "NSURLComponents",
16690b57cec5SDimitry Andric         "NSURLQueryItem",
16700b57cec5SDimitry Andric         "NSUUID",
16710b57cec5SDimitry Andric         "NSValue",
16720b57cec5SDimitry Andric         "UIImage",
16730b57cec5SDimitry Andric         "UIView",
16740b57cec5SDimitry Andric     };
16750b57cec5SDimitry Andric 
16760b57cec5SDimitry Andric     for (auto Line : AnnotatedLines) {
16770b57cec5SDimitry Andric       for (const FormatToken *FormatTok = Line->First; FormatTok;
16780b57cec5SDimitry Andric            FormatTok = FormatTok->Next) {
16790b57cec5SDimitry Andric         if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
16800b57cec5SDimitry Andric              (FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword ||
16810b57cec5SDimitry Andric               FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
16820b57cec5SDimitry Andric                                  tok::l_brace))) ||
16830b57cec5SDimitry Andric             (FormatTok->Tok.isAnyIdentifier() &&
16840b57cec5SDimitry Andric              std::binary_search(std::begin(FoundationIdentifiers),
16850b57cec5SDimitry Andric                                 std::end(FoundationIdentifiers),
16860b57cec5SDimitry Andric                                 FormatTok->TokenText)) ||
16870b57cec5SDimitry Andric             FormatTok->is(TT_ObjCStringLiteral) ||
16880b57cec5SDimitry Andric             FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
16890b57cec5SDimitry Andric                                TT_ObjCBlockLBrace, TT_ObjCBlockLParen,
16900b57cec5SDimitry Andric                                TT_ObjCDecl, TT_ObjCForIn, TT_ObjCMethodExpr,
16910b57cec5SDimitry Andric                                TT_ObjCMethodSpecifier, TT_ObjCProperty)) {
16920b57cec5SDimitry Andric           LLVM_DEBUG(llvm::dbgs()
16930b57cec5SDimitry Andric                      << "Detected ObjC at location "
16940b57cec5SDimitry Andric                      << FormatTok->Tok.getLocation().printToString(
16950b57cec5SDimitry Andric                             SourceManager)
16960b57cec5SDimitry Andric                      << " token: " << FormatTok->TokenText << " token type: "
16970b57cec5SDimitry Andric                      << getTokenTypeName(FormatTok->Type) << "\n");
16980b57cec5SDimitry Andric           return true;
16990b57cec5SDimitry Andric         }
17000b57cec5SDimitry Andric         if (guessIsObjC(SourceManager, Line->Children, Keywords))
17010b57cec5SDimitry Andric           return true;
17020b57cec5SDimitry Andric       }
17030b57cec5SDimitry Andric     }
17040b57cec5SDimitry Andric     return false;
17050b57cec5SDimitry Andric   }
17060b57cec5SDimitry Andric 
17070b57cec5SDimitry Andric   bool IsObjC;
17080b57cec5SDimitry Andric };
17090b57cec5SDimitry Andric 
17100b57cec5SDimitry Andric struct IncludeDirective {
17110b57cec5SDimitry Andric   StringRef Filename;
17120b57cec5SDimitry Andric   StringRef Text;
17130b57cec5SDimitry Andric   unsigned Offset;
17140b57cec5SDimitry Andric   int Category;
17150b57cec5SDimitry Andric };
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric struct JavaImportDirective {
17180b57cec5SDimitry Andric   StringRef Identifier;
17190b57cec5SDimitry Andric   StringRef Text;
17200b57cec5SDimitry Andric   unsigned Offset;
17210b57cec5SDimitry Andric   std::vector<StringRef> AssociatedCommentLines;
17220b57cec5SDimitry Andric   bool IsStatic;
17230b57cec5SDimitry Andric };
17240b57cec5SDimitry Andric 
17250b57cec5SDimitry Andric } // end anonymous namespace
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric // Determines whether 'Ranges' intersects with ('Start', 'End').
17280b57cec5SDimitry Andric static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
17290b57cec5SDimitry Andric                          unsigned End) {
17300b57cec5SDimitry Andric   for (auto Range : Ranges) {
17310b57cec5SDimitry Andric     if (Range.getOffset() < End &&
17320b57cec5SDimitry Andric         Range.getOffset() + Range.getLength() > Start)
17330b57cec5SDimitry Andric       return true;
17340b57cec5SDimitry Andric   }
17350b57cec5SDimitry Andric   return false;
17360b57cec5SDimitry Andric }
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric // Returns a pair (Index, OffsetToEOL) describing the position of the cursor
17390b57cec5SDimitry Andric // before sorting/deduplicating. Index is the index of the include under the
17400b57cec5SDimitry Andric // cursor in the original set of includes. If this include has duplicates, it is
17410b57cec5SDimitry Andric // the index of the first of the duplicates as the others are going to be
17420b57cec5SDimitry Andric // removed. OffsetToEOL describes the cursor's position relative to the end of
17430b57cec5SDimitry Andric // its current line.
17440b57cec5SDimitry Andric // If `Cursor` is not on any #include, `Index` will be UINT_MAX.
17450b57cec5SDimitry Andric static std::pair<unsigned, unsigned>
17460b57cec5SDimitry Andric FindCursorIndex(const SmallVectorImpl<IncludeDirective> &Includes,
17470b57cec5SDimitry Andric                 const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) {
17480b57cec5SDimitry Andric   unsigned CursorIndex = UINT_MAX;
17490b57cec5SDimitry Andric   unsigned OffsetToEOL = 0;
17500b57cec5SDimitry Andric   for (int i = 0, e = Includes.size(); i != e; ++i) {
17510b57cec5SDimitry Andric     unsigned Start = Includes[Indices[i]].Offset;
17520b57cec5SDimitry Andric     unsigned End = Start + Includes[Indices[i]].Text.size();
17530b57cec5SDimitry Andric     if (!(Cursor >= Start && Cursor < End))
17540b57cec5SDimitry Andric       continue;
17550b57cec5SDimitry Andric     CursorIndex = Indices[i];
17560b57cec5SDimitry Andric     OffsetToEOL = End - Cursor;
17570b57cec5SDimitry Andric     // Put the cursor on the only remaining #include among the duplicate
17580b57cec5SDimitry Andric     // #includes.
17590b57cec5SDimitry Andric     while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
17600b57cec5SDimitry Andric       CursorIndex = i;
17610b57cec5SDimitry Andric     break;
17620b57cec5SDimitry Andric   }
17630b57cec5SDimitry Andric   return std::make_pair(CursorIndex, OffsetToEOL);
17640b57cec5SDimitry Andric }
17650b57cec5SDimitry Andric 
17660b57cec5SDimitry Andric // Sorts and deduplicate a block of includes given by 'Includes' alphabetically
17670b57cec5SDimitry Andric // adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
17680b57cec5SDimitry Andric // source order.
17690b57cec5SDimitry Andric // #include directives with the same text will be deduplicated, and only the
17700b57cec5SDimitry Andric // first #include in the duplicate #includes remains. If the `Cursor` is
17710b57cec5SDimitry Andric // provided and put on a deleted #include, it will be moved to the remaining
17720b57cec5SDimitry Andric // #include in the duplicate #includes.
17730b57cec5SDimitry Andric static void sortCppIncludes(const FormatStyle &Style,
17740b57cec5SDimitry Andric                             const SmallVectorImpl<IncludeDirective> &Includes,
17750b57cec5SDimitry Andric                             ArrayRef<tooling::Range> Ranges, StringRef FileName,
17760b57cec5SDimitry Andric                             StringRef Code,
17770b57cec5SDimitry Andric                             tooling::Replacements &Replaces, unsigned *Cursor) {
17780b57cec5SDimitry Andric   unsigned IncludesBeginOffset = Includes.front().Offset;
17790b57cec5SDimitry Andric   unsigned IncludesEndOffset =
17800b57cec5SDimitry Andric       Includes.back().Offset + Includes.back().Text.size();
17810b57cec5SDimitry Andric   unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
17820b57cec5SDimitry Andric   if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
17830b57cec5SDimitry Andric     return;
17840b57cec5SDimitry Andric   SmallVector<unsigned, 16> Indices;
17850b57cec5SDimitry Andric   for (unsigned i = 0, e = Includes.size(); i != e; ++i)
17860b57cec5SDimitry Andric     Indices.push_back(i);
17870b57cec5SDimitry Andric   llvm::stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
17880b57cec5SDimitry Andric     return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
17890b57cec5SDimitry Andric            std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
17900b57cec5SDimitry Andric   });
17910b57cec5SDimitry Andric   // The index of the include on which the cursor will be put after
17920b57cec5SDimitry Andric   // sorting/deduplicating.
17930b57cec5SDimitry Andric   unsigned CursorIndex;
17940b57cec5SDimitry Andric   // The offset from cursor to the end of line.
17950b57cec5SDimitry Andric   unsigned CursorToEOLOffset;
17960b57cec5SDimitry Andric   if (Cursor)
17970b57cec5SDimitry Andric     std::tie(CursorIndex, CursorToEOLOffset) =
17980b57cec5SDimitry Andric         FindCursorIndex(Includes, Indices, *Cursor);
17990b57cec5SDimitry Andric 
18000b57cec5SDimitry Andric   // Deduplicate #includes.
18010b57cec5SDimitry Andric   Indices.erase(std::unique(Indices.begin(), Indices.end(),
18020b57cec5SDimitry Andric                             [&](unsigned LHSI, unsigned RHSI) {
18030b57cec5SDimitry Andric                               return Includes[LHSI].Text == Includes[RHSI].Text;
18040b57cec5SDimitry Andric                             }),
18050b57cec5SDimitry Andric                 Indices.end());
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric   int CurrentCategory = Includes.front().Category;
18080b57cec5SDimitry Andric 
18090b57cec5SDimitry Andric   // If the #includes are out of order, we generate a single replacement fixing
18100b57cec5SDimitry Andric   // the entire block. Otherwise, no replacement is generated.
18110b57cec5SDimitry Andric   // In case Style.IncldueStyle.IncludeBlocks != IBS_Preserve, this check is not
18120b57cec5SDimitry Andric   // enough as additional newlines might be added or removed across #include
18130b57cec5SDimitry Andric   // blocks. This we handle below by generating the updated #imclude blocks and
18140b57cec5SDimitry Andric   // comparing it to the original.
18150b57cec5SDimitry Andric   if (Indices.size() == Includes.size() &&
18160b57cec5SDimitry Andric       std::is_sorted(Indices.begin(), Indices.end()) &&
18170b57cec5SDimitry Andric       Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve)
18180b57cec5SDimitry Andric     return;
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric   std::string result;
18210b57cec5SDimitry Andric   for (unsigned Index : Indices) {
18220b57cec5SDimitry Andric     if (!result.empty()) {
18230b57cec5SDimitry Andric       result += "\n";
18240b57cec5SDimitry Andric       if (Style.IncludeStyle.IncludeBlocks ==
18250b57cec5SDimitry Andric               tooling::IncludeStyle::IBS_Regroup &&
18260b57cec5SDimitry Andric           CurrentCategory != Includes[Index].Category)
18270b57cec5SDimitry Andric         result += "\n";
18280b57cec5SDimitry Andric     }
18290b57cec5SDimitry Andric     result += Includes[Index].Text;
18300b57cec5SDimitry Andric     if (Cursor && CursorIndex == Index)
18310b57cec5SDimitry Andric       *Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
18320b57cec5SDimitry Andric     CurrentCategory = Includes[Index].Category;
18330b57cec5SDimitry Andric   }
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric   // If the #includes are out of order, we generate a single replacement fixing
18360b57cec5SDimitry Andric   // the entire range of blocks. Otherwise, no replacement is generated.
18370b57cec5SDimitry Andric   if (result == Code.substr(IncludesBeginOffset, IncludesBlockSize))
18380b57cec5SDimitry Andric     return;
18390b57cec5SDimitry Andric 
18400b57cec5SDimitry Andric   auto Err = Replaces.add(tooling::Replacement(
18410b57cec5SDimitry Andric       FileName, Includes.front().Offset, IncludesBlockSize, result));
18420b57cec5SDimitry Andric   // FIXME: better error handling. For now, just skip the replacement for the
18430b57cec5SDimitry Andric   // release version.
18440b57cec5SDimitry Andric   if (Err) {
18450b57cec5SDimitry Andric     llvm::errs() << llvm::toString(std::move(Err)) << "\n";
18460b57cec5SDimitry Andric     assert(false);
18470b57cec5SDimitry Andric   }
18480b57cec5SDimitry Andric }
18490b57cec5SDimitry Andric 
18500b57cec5SDimitry Andric namespace {
18510b57cec5SDimitry Andric 
18520b57cec5SDimitry Andric const char CppIncludeRegexPattern[] =
18530b57cec5SDimitry Andric     R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
18540b57cec5SDimitry Andric 
18550b57cec5SDimitry Andric } // anonymous namespace
18560b57cec5SDimitry Andric 
18570b57cec5SDimitry Andric tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
18580b57cec5SDimitry Andric                                       ArrayRef<tooling::Range> Ranges,
18590b57cec5SDimitry Andric                                       StringRef FileName,
18600b57cec5SDimitry Andric                                       tooling::Replacements &Replaces,
18610b57cec5SDimitry Andric                                       unsigned *Cursor) {
18620b57cec5SDimitry Andric   unsigned Prev = 0;
18630b57cec5SDimitry Andric   unsigned SearchFrom = 0;
18640b57cec5SDimitry Andric   llvm::Regex IncludeRegex(CppIncludeRegexPattern);
18650b57cec5SDimitry Andric   SmallVector<StringRef, 4> Matches;
18660b57cec5SDimitry Andric   SmallVector<IncludeDirective, 16> IncludesInBlock;
18670b57cec5SDimitry Andric 
18680b57cec5SDimitry Andric   // In compiled files, consider the first #include to be the main #include of
18690b57cec5SDimitry Andric   // the file if it is not a system #include. This ensures that the header
18700b57cec5SDimitry Andric   // doesn't have hidden dependencies
18710b57cec5SDimitry Andric   // (http://llvm.org/docs/CodingStandards.html#include-style).
18720b57cec5SDimitry Andric   //
18730b57cec5SDimitry Andric   // FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
18740b57cec5SDimitry Andric   // cases where the first #include is unlikely to be the main header.
18750b57cec5SDimitry Andric   tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
18760b57cec5SDimitry Andric   bool FirstIncludeBlock = true;
18770b57cec5SDimitry Andric   bool MainIncludeFound = false;
18780b57cec5SDimitry Andric   bool FormattingOff = false;
18790b57cec5SDimitry Andric 
18800b57cec5SDimitry Andric   for (;;) {
18810b57cec5SDimitry Andric     auto Pos = Code.find('\n', SearchFrom);
18820b57cec5SDimitry Andric     StringRef Line =
18830b57cec5SDimitry Andric         Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
18840b57cec5SDimitry Andric 
18850b57cec5SDimitry Andric     StringRef Trimmed = Line.trim();
18860b57cec5SDimitry Andric     if (Trimmed == "// clang-format off" || Trimmed == "/* clang-format off */")
18870b57cec5SDimitry Andric       FormattingOff = true;
18880b57cec5SDimitry Andric     else if (Trimmed == "// clang-format on" ||
18890b57cec5SDimitry Andric              Trimmed == "/* clang-format on */")
18900b57cec5SDimitry Andric       FormattingOff = false;
18910b57cec5SDimitry Andric 
18920b57cec5SDimitry Andric     const bool EmptyLineSkipped =
18930b57cec5SDimitry Andric         Trimmed.empty() &&
18940b57cec5SDimitry Andric         (Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge ||
18950b57cec5SDimitry Andric          Style.IncludeStyle.IncludeBlocks ==
18960b57cec5SDimitry Andric              tooling::IncludeStyle::IBS_Regroup);
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric     if (!FormattingOff && !Line.endswith("\\")) {
18990b57cec5SDimitry Andric       if (IncludeRegex.match(Line, &Matches)) {
19000b57cec5SDimitry Andric         StringRef IncludeName = Matches[2];
19010b57cec5SDimitry Andric         int Category = Categories.getIncludePriority(
19020b57cec5SDimitry Andric             IncludeName,
19030b57cec5SDimitry Andric             /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
19040b57cec5SDimitry Andric         if (Category == 0)
19050b57cec5SDimitry Andric           MainIncludeFound = true;
19060b57cec5SDimitry Andric         IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
19070b57cec5SDimitry Andric       } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
19080b57cec5SDimitry Andric         sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code,
19090b57cec5SDimitry Andric                         Replaces, Cursor);
19100b57cec5SDimitry Andric         IncludesInBlock.clear();
19110b57cec5SDimitry Andric         FirstIncludeBlock = false;
19120b57cec5SDimitry Andric       }
19130b57cec5SDimitry Andric       Prev = Pos + 1;
19140b57cec5SDimitry Andric     }
19150b57cec5SDimitry Andric     if (Pos == StringRef::npos || Pos + 1 == Code.size())
19160b57cec5SDimitry Andric       break;
19170b57cec5SDimitry Andric     SearchFrom = Pos + 1;
19180b57cec5SDimitry Andric   }
19190b57cec5SDimitry Andric   if (!IncludesInBlock.empty()) {
19200b57cec5SDimitry Andric     sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code, Replaces,
19210b57cec5SDimitry Andric                     Cursor);
19220b57cec5SDimitry Andric   }
19230b57cec5SDimitry Andric   return Replaces;
19240b57cec5SDimitry Andric }
19250b57cec5SDimitry Andric 
19260b57cec5SDimitry Andric // Returns group number to use as a first order sort on imports. Gives UINT_MAX
19270b57cec5SDimitry Andric // if the import does not match any given groups.
19280b57cec5SDimitry Andric static unsigned findJavaImportGroup(const FormatStyle &Style,
19290b57cec5SDimitry Andric                                     StringRef ImportIdentifier) {
19300b57cec5SDimitry Andric   unsigned LongestMatchIndex = UINT_MAX;
19310b57cec5SDimitry Andric   unsigned LongestMatchLength = 0;
19320b57cec5SDimitry Andric   for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
19330b57cec5SDimitry Andric     std::string GroupPrefix = Style.JavaImportGroups[I];
19340b57cec5SDimitry Andric     if (ImportIdentifier.startswith(GroupPrefix) &&
19350b57cec5SDimitry Andric         GroupPrefix.length() > LongestMatchLength) {
19360b57cec5SDimitry Andric       LongestMatchIndex = I;
19370b57cec5SDimitry Andric       LongestMatchLength = GroupPrefix.length();
19380b57cec5SDimitry Andric     }
19390b57cec5SDimitry Andric   }
19400b57cec5SDimitry Andric   return LongestMatchIndex;
19410b57cec5SDimitry Andric }
19420b57cec5SDimitry Andric 
19430b57cec5SDimitry Andric // Sorts and deduplicates a block of includes given by 'Imports' based on
19440b57cec5SDimitry Andric // JavaImportGroups, then adding the necessary replacement to 'Replaces'.
19450b57cec5SDimitry Andric // Import declarations with the same text will be deduplicated. Between each
19460b57cec5SDimitry Andric // import group, a newline is inserted, and within each import group, a
19470b57cec5SDimitry Andric // lexicographic sort based on ASCII value is performed.
19480b57cec5SDimitry Andric static void sortJavaImports(const FormatStyle &Style,
19490b57cec5SDimitry Andric                             const SmallVectorImpl<JavaImportDirective> &Imports,
19500b57cec5SDimitry Andric                             ArrayRef<tooling::Range> Ranges, StringRef FileName,
19510b57cec5SDimitry Andric                             StringRef Code, tooling::Replacements &Replaces) {
19520b57cec5SDimitry Andric   unsigned ImportsBeginOffset = Imports.front().Offset;
19530b57cec5SDimitry Andric   unsigned ImportsEndOffset =
19540b57cec5SDimitry Andric       Imports.back().Offset + Imports.back().Text.size();
19550b57cec5SDimitry Andric   unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
19560b57cec5SDimitry Andric   if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
19570b57cec5SDimitry Andric     return;
19580b57cec5SDimitry Andric   SmallVector<unsigned, 16> Indices;
19590b57cec5SDimitry Andric   SmallVector<unsigned, 16> JavaImportGroups;
19600b57cec5SDimitry Andric   for (unsigned i = 0, e = Imports.size(); i != e; ++i) {
19610b57cec5SDimitry Andric     Indices.push_back(i);
19620b57cec5SDimitry Andric     JavaImportGroups.push_back(
19630b57cec5SDimitry Andric         findJavaImportGroup(Style, Imports[i].Identifier));
19640b57cec5SDimitry Andric   }
19650b57cec5SDimitry Andric   llvm::sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
19660b57cec5SDimitry Andric     // Negating IsStatic to push static imports above non-static imports.
19670b57cec5SDimitry Andric     return std::make_tuple(!Imports[LHSI].IsStatic, JavaImportGroups[LHSI],
19680b57cec5SDimitry Andric                            Imports[LHSI].Identifier) <
19690b57cec5SDimitry Andric            std::make_tuple(!Imports[RHSI].IsStatic, JavaImportGroups[RHSI],
19700b57cec5SDimitry Andric                            Imports[RHSI].Identifier);
19710b57cec5SDimitry Andric   });
19720b57cec5SDimitry Andric 
19730b57cec5SDimitry Andric   // Deduplicate imports.
19740b57cec5SDimitry Andric   Indices.erase(std::unique(Indices.begin(), Indices.end(),
19750b57cec5SDimitry Andric                             [&](unsigned LHSI, unsigned RHSI) {
19760b57cec5SDimitry Andric                               return Imports[LHSI].Text == Imports[RHSI].Text;
19770b57cec5SDimitry Andric                             }),
19780b57cec5SDimitry Andric                 Indices.end());
19790b57cec5SDimitry Andric 
19800b57cec5SDimitry Andric   bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
19810b57cec5SDimitry Andric   unsigned CurrentImportGroup = JavaImportGroups[Indices.front()];
19820b57cec5SDimitry Andric 
19830b57cec5SDimitry Andric   std::string result;
19840b57cec5SDimitry Andric   for (unsigned Index : Indices) {
19850b57cec5SDimitry Andric     if (!result.empty()) {
19860b57cec5SDimitry Andric       result += "\n";
19870b57cec5SDimitry Andric       if (CurrentIsStatic != Imports[Index].IsStatic ||
19880b57cec5SDimitry Andric           CurrentImportGroup != JavaImportGroups[Index])
19890b57cec5SDimitry Andric         result += "\n";
19900b57cec5SDimitry Andric     }
19910b57cec5SDimitry Andric     for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
19920b57cec5SDimitry Andric       result += CommentLine;
19930b57cec5SDimitry Andric       result += "\n";
19940b57cec5SDimitry Andric     }
19950b57cec5SDimitry Andric     result += Imports[Index].Text;
19960b57cec5SDimitry Andric     CurrentIsStatic = Imports[Index].IsStatic;
19970b57cec5SDimitry Andric     CurrentImportGroup = JavaImportGroups[Index];
19980b57cec5SDimitry Andric   }
19990b57cec5SDimitry Andric 
20000b57cec5SDimitry Andric   // If the imports are out of order, we generate a single replacement fixing
20010b57cec5SDimitry Andric   // the entire block. Otherwise, no replacement is generated.
20020b57cec5SDimitry Andric   if (result == Code.substr(Imports.front().Offset, ImportsBlockSize))
20030b57cec5SDimitry Andric     return;
20040b57cec5SDimitry Andric 
20050b57cec5SDimitry Andric   auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset,
20060b57cec5SDimitry Andric                                                ImportsBlockSize, result));
20070b57cec5SDimitry Andric   // FIXME: better error handling. For now, just skip the replacement for the
20080b57cec5SDimitry Andric   // release version.
20090b57cec5SDimitry Andric   if (Err) {
20100b57cec5SDimitry Andric     llvm::errs() << llvm::toString(std::move(Err)) << "\n";
20110b57cec5SDimitry Andric     assert(false);
20120b57cec5SDimitry Andric   }
20130b57cec5SDimitry Andric }
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric namespace {
20160b57cec5SDimitry Andric 
20170b57cec5SDimitry Andric const char JavaImportRegexPattern[] =
20180b57cec5SDimitry Andric     "^[\t ]*import[\t ]+(static[\t ]*)?([^\t ]*)[\t ]*;";
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric } // anonymous namespace
20210b57cec5SDimitry Andric 
20220b57cec5SDimitry Andric tooling::Replacements sortJavaImports(const FormatStyle &Style, StringRef Code,
20230b57cec5SDimitry Andric                                       ArrayRef<tooling::Range> Ranges,
20240b57cec5SDimitry Andric                                       StringRef FileName,
20250b57cec5SDimitry Andric                                       tooling::Replacements &Replaces) {
20260b57cec5SDimitry Andric   unsigned Prev = 0;
20270b57cec5SDimitry Andric   unsigned SearchFrom = 0;
20280b57cec5SDimitry Andric   llvm::Regex ImportRegex(JavaImportRegexPattern);
20290b57cec5SDimitry Andric   SmallVector<StringRef, 4> Matches;
20300b57cec5SDimitry Andric   SmallVector<JavaImportDirective, 16> ImportsInBlock;
20310b57cec5SDimitry Andric   std::vector<StringRef> AssociatedCommentLines;
20320b57cec5SDimitry Andric 
20330b57cec5SDimitry Andric   bool FormattingOff = false;
20340b57cec5SDimitry Andric 
20350b57cec5SDimitry Andric   for (;;) {
20360b57cec5SDimitry Andric     auto Pos = Code.find('\n', SearchFrom);
20370b57cec5SDimitry Andric     StringRef Line =
20380b57cec5SDimitry Andric         Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
20390b57cec5SDimitry Andric 
20400b57cec5SDimitry Andric     StringRef Trimmed = Line.trim();
20410b57cec5SDimitry Andric     if (Trimmed == "// clang-format off")
20420b57cec5SDimitry Andric       FormattingOff = true;
20430b57cec5SDimitry Andric     else if (Trimmed == "// clang-format on")
20440b57cec5SDimitry Andric       FormattingOff = false;
20450b57cec5SDimitry Andric 
20460b57cec5SDimitry Andric     if (ImportRegex.match(Line, &Matches)) {
20470b57cec5SDimitry Andric       if (FormattingOff) {
20480b57cec5SDimitry Andric         // If at least one import line has formatting turned off, turn off
20490b57cec5SDimitry Andric         // formatting entirely.
20500b57cec5SDimitry Andric         return Replaces;
20510b57cec5SDimitry Andric       }
20520b57cec5SDimitry Andric       StringRef Static = Matches[1];
20530b57cec5SDimitry Andric       StringRef Identifier = Matches[2];
20540b57cec5SDimitry Andric       bool IsStatic = false;
20550b57cec5SDimitry Andric       if (Static.contains("static")) {
20560b57cec5SDimitry Andric         IsStatic = true;
20570b57cec5SDimitry Andric       }
20580b57cec5SDimitry Andric       ImportsInBlock.push_back(
20590b57cec5SDimitry Andric           {Identifier, Line, Prev, AssociatedCommentLines, IsStatic});
20600b57cec5SDimitry Andric       AssociatedCommentLines.clear();
20610b57cec5SDimitry Andric     } else if (Trimmed.size() > 0 && !ImportsInBlock.empty()) {
20620b57cec5SDimitry Andric       // Associating comments within the imports with the nearest import below
20630b57cec5SDimitry Andric       AssociatedCommentLines.push_back(Line);
20640b57cec5SDimitry Andric     }
20650b57cec5SDimitry Andric     Prev = Pos + 1;
20660b57cec5SDimitry Andric     if (Pos == StringRef::npos || Pos + 1 == Code.size())
20670b57cec5SDimitry Andric       break;
20680b57cec5SDimitry Andric     SearchFrom = Pos + 1;
20690b57cec5SDimitry Andric   }
20700b57cec5SDimitry Andric   if (!ImportsInBlock.empty())
20710b57cec5SDimitry Andric     sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
20720b57cec5SDimitry Andric   return Replaces;
20730b57cec5SDimitry Andric }
20740b57cec5SDimitry Andric 
20750b57cec5SDimitry Andric bool isMpegTS(StringRef Code) {
20760b57cec5SDimitry Andric   // MPEG transport streams use the ".ts" file extension. clang-format should
20770b57cec5SDimitry Andric   // not attempt to format those. MPEG TS' frame format starts with 0x47 every
20780b57cec5SDimitry Andric   // 189 bytes - detect that and return.
20790b57cec5SDimitry Andric   return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
20800b57cec5SDimitry Andric }
20810b57cec5SDimitry Andric 
20820b57cec5SDimitry Andric bool isLikelyXml(StringRef Code) { return Code.ltrim().startswith("<"); }
20830b57cec5SDimitry Andric 
20840b57cec5SDimitry Andric tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
20850b57cec5SDimitry Andric                                    ArrayRef<tooling::Range> Ranges,
20860b57cec5SDimitry Andric                                    StringRef FileName, unsigned *Cursor) {
20870b57cec5SDimitry Andric   tooling::Replacements Replaces;
20880b57cec5SDimitry Andric   if (!Style.SortIncludes)
20890b57cec5SDimitry Andric     return Replaces;
20900b57cec5SDimitry Andric   if (isLikelyXml(Code))
20910b57cec5SDimitry Andric     return Replaces;
20920b57cec5SDimitry Andric   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
20930b57cec5SDimitry Andric       isMpegTS(Code))
20940b57cec5SDimitry Andric     return Replaces;
20950b57cec5SDimitry Andric   if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
20960b57cec5SDimitry Andric     return sortJavaScriptImports(Style, Code, Ranges, FileName);
20970b57cec5SDimitry Andric   if (Style.Language == FormatStyle::LanguageKind::LK_Java)
20980b57cec5SDimitry Andric     return sortJavaImports(Style, Code, Ranges, FileName, Replaces);
20990b57cec5SDimitry Andric   sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
21000b57cec5SDimitry Andric   return Replaces;
21010b57cec5SDimitry Andric }
21020b57cec5SDimitry Andric 
21030b57cec5SDimitry Andric template <typename T>
21040b57cec5SDimitry Andric static llvm::Expected<tooling::Replacements>
21050b57cec5SDimitry Andric processReplacements(T ProcessFunc, StringRef Code,
21060b57cec5SDimitry Andric                     const tooling::Replacements &Replaces,
21070b57cec5SDimitry Andric                     const FormatStyle &Style) {
21080b57cec5SDimitry Andric   if (Replaces.empty())
21090b57cec5SDimitry Andric     return tooling::Replacements();
21100b57cec5SDimitry Andric 
21110b57cec5SDimitry Andric   auto NewCode = applyAllReplacements(Code, Replaces);
21120b57cec5SDimitry Andric   if (!NewCode)
21130b57cec5SDimitry Andric     return NewCode.takeError();
21140b57cec5SDimitry Andric   std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
21150b57cec5SDimitry Andric   StringRef FileName = Replaces.begin()->getFilePath();
21160b57cec5SDimitry Andric 
21170b57cec5SDimitry Andric   tooling::Replacements FormatReplaces =
21180b57cec5SDimitry Andric       ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
21190b57cec5SDimitry Andric 
21200b57cec5SDimitry Andric   return Replaces.merge(FormatReplaces);
21210b57cec5SDimitry Andric }
21220b57cec5SDimitry Andric 
21230b57cec5SDimitry Andric llvm::Expected<tooling::Replacements>
21240b57cec5SDimitry Andric formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
21250b57cec5SDimitry Andric                    const FormatStyle &Style) {
21260b57cec5SDimitry Andric   // We need to use lambda function here since there are two versions of
21270b57cec5SDimitry Andric   // `sortIncludes`.
21280b57cec5SDimitry Andric   auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
21290b57cec5SDimitry Andric                          std::vector<tooling::Range> Ranges,
21300b57cec5SDimitry Andric                          StringRef FileName) -> tooling::Replacements {
21310b57cec5SDimitry Andric     return sortIncludes(Style, Code, Ranges, FileName);
21320b57cec5SDimitry Andric   };
21330b57cec5SDimitry Andric   auto SortedReplaces =
21340b57cec5SDimitry Andric       processReplacements(SortIncludes, Code, Replaces, Style);
21350b57cec5SDimitry Andric   if (!SortedReplaces)
21360b57cec5SDimitry Andric     return SortedReplaces.takeError();
21370b57cec5SDimitry Andric 
21380b57cec5SDimitry Andric   // We need to use lambda function here since there are two versions of
21390b57cec5SDimitry Andric   // `reformat`.
21400b57cec5SDimitry Andric   auto Reformat = [](const FormatStyle &Style, StringRef Code,
21410b57cec5SDimitry Andric                      std::vector<tooling::Range> Ranges,
21420b57cec5SDimitry Andric                      StringRef FileName) -> tooling::Replacements {
21430b57cec5SDimitry Andric     return reformat(Style, Code, Ranges, FileName);
21440b57cec5SDimitry Andric   };
21450b57cec5SDimitry Andric   return processReplacements(Reformat, Code, *SortedReplaces, Style);
21460b57cec5SDimitry Andric }
21470b57cec5SDimitry Andric 
21480b57cec5SDimitry Andric namespace {
21490b57cec5SDimitry Andric 
21500b57cec5SDimitry Andric inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
21510b57cec5SDimitry Andric   return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 &&
21520b57cec5SDimitry Andric          llvm::Regex(CppIncludeRegexPattern)
21530b57cec5SDimitry Andric              .match(Replace.getReplacementText());
21540b57cec5SDimitry Andric }
21550b57cec5SDimitry Andric 
21560b57cec5SDimitry Andric inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
21570b57cec5SDimitry Andric   return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1;
21580b57cec5SDimitry Andric }
21590b57cec5SDimitry Andric 
21600b57cec5SDimitry Andric // FIXME: insert empty lines between newly created blocks.
21610b57cec5SDimitry Andric tooling::Replacements
21620b57cec5SDimitry Andric fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
21630b57cec5SDimitry Andric                         const FormatStyle &Style) {
21640b57cec5SDimitry Andric   if (!Style.isCpp())
21650b57cec5SDimitry Andric     return Replaces;
21660b57cec5SDimitry Andric 
21670b57cec5SDimitry Andric   tooling::Replacements HeaderInsertions;
21680b57cec5SDimitry Andric   std::set<llvm::StringRef> HeadersToDelete;
21690b57cec5SDimitry Andric   tooling::Replacements Result;
21700b57cec5SDimitry Andric   for (const auto &R : Replaces) {
21710b57cec5SDimitry Andric     if (isHeaderInsertion(R)) {
21720b57cec5SDimitry Andric       // Replacements from \p Replaces must be conflict-free already, so we can
21730b57cec5SDimitry Andric       // simply consume the error.
21740b57cec5SDimitry Andric       llvm::consumeError(HeaderInsertions.add(R));
21750b57cec5SDimitry Andric     } else if (isHeaderDeletion(R)) {
21760b57cec5SDimitry Andric       HeadersToDelete.insert(R.getReplacementText());
21770b57cec5SDimitry Andric     } else if (R.getOffset() == UINT_MAX) {
21780b57cec5SDimitry Andric       llvm::errs() << "Insertions other than header #include insertion are "
21790b57cec5SDimitry Andric                       "not supported! "
21800b57cec5SDimitry Andric                    << R.getReplacementText() << "\n";
21810b57cec5SDimitry Andric     } else {
21820b57cec5SDimitry Andric       llvm::consumeError(Result.add(R));
21830b57cec5SDimitry Andric     }
21840b57cec5SDimitry Andric   }
21850b57cec5SDimitry Andric   if (HeaderInsertions.empty() && HeadersToDelete.empty())
21860b57cec5SDimitry Andric     return Replaces;
21870b57cec5SDimitry Andric 
21880b57cec5SDimitry Andric   StringRef FileName = Replaces.begin()->getFilePath();
21890b57cec5SDimitry Andric   tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle);
21900b57cec5SDimitry Andric 
21910b57cec5SDimitry Andric   for (const auto &Header : HeadersToDelete) {
21920b57cec5SDimitry Andric     tooling::Replacements Replaces =
21930b57cec5SDimitry Andric         Includes.remove(Header.trim("\"<>"), Header.startswith("<"));
21940b57cec5SDimitry Andric     for (const auto &R : Replaces) {
21950b57cec5SDimitry Andric       auto Err = Result.add(R);
21960b57cec5SDimitry Andric       if (Err) {
21970b57cec5SDimitry Andric         // Ignore the deletion on conflict.
21980b57cec5SDimitry Andric         llvm::errs() << "Failed to add header deletion replacement for "
21990b57cec5SDimitry Andric                      << Header << ": " << llvm::toString(std::move(Err))
22000b57cec5SDimitry Andric                      << "\n";
22010b57cec5SDimitry Andric       }
22020b57cec5SDimitry Andric     }
22030b57cec5SDimitry Andric   }
22040b57cec5SDimitry Andric 
22050b57cec5SDimitry Andric   llvm::Regex IncludeRegex = llvm::Regex(CppIncludeRegexPattern);
22060b57cec5SDimitry Andric   llvm::SmallVector<StringRef, 4> Matches;
22070b57cec5SDimitry Andric   for (const auto &R : HeaderInsertions) {
22080b57cec5SDimitry Andric     auto IncludeDirective = R.getReplacementText();
22090b57cec5SDimitry Andric     bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
22100b57cec5SDimitry Andric     assert(Matched && "Header insertion replacement must have replacement text "
22110b57cec5SDimitry Andric                       "'#include ...'");
22120b57cec5SDimitry Andric     (void)Matched;
22130b57cec5SDimitry Andric     auto IncludeName = Matches[2];
22140b57cec5SDimitry Andric     auto Replace =
22150b57cec5SDimitry Andric         Includes.insert(IncludeName.trim("\"<>"), IncludeName.startswith("<"));
22160b57cec5SDimitry Andric     if (Replace) {
22170b57cec5SDimitry Andric       auto Err = Result.add(*Replace);
22180b57cec5SDimitry Andric       if (Err) {
22190b57cec5SDimitry Andric         llvm::consumeError(std::move(Err));
22200b57cec5SDimitry Andric         unsigned NewOffset =
22210b57cec5SDimitry Andric             Result.getShiftedCodePosition(Replace->getOffset());
22220b57cec5SDimitry Andric         auto Shifted = tooling::Replacement(FileName, NewOffset, 0,
22230b57cec5SDimitry Andric                                             Replace->getReplacementText());
22240b57cec5SDimitry Andric         Result = Result.merge(tooling::Replacements(Shifted));
22250b57cec5SDimitry Andric       }
22260b57cec5SDimitry Andric     }
22270b57cec5SDimitry Andric   }
22280b57cec5SDimitry Andric   return Result;
22290b57cec5SDimitry Andric }
22300b57cec5SDimitry Andric 
22310b57cec5SDimitry Andric } // anonymous namespace
22320b57cec5SDimitry Andric 
22330b57cec5SDimitry Andric llvm::Expected<tooling::Replacements>
22340b57cec5SDimitry Andric cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
22350b57cec5SDimitry Andric                           const FormatStyle &Style) {
22360b57cec5SDimitry Andric   // We need to use lambda function here since there are two versions of
22370b57cec5SDimitry Andric   // `cleanup`.
22380b57cec5SDimitry Andric   auto Cleanup = [](const FormatStyle &Style, StringRef Code,
22390b57cec5SDimitry Andric                     std::vector<tooling::Range> Ranges,
22400b57cec5SDimitry Andric                     StringRef FileName) -> tooling::Replacements {
22410b57cec5SDimitry Andric     return cleanup(Style, Code, Ranges, FileName);
22420b57cec5SDimitry Andric   };
22430b57cec5SDimitry Andric   // Make header insertion replacements insert new headers into correct blocks.
22440b57cec5SDimitry Andric   tooling::Replacements NewReplaces =
22450b57cec5SDimitry Andric       fixCppIncludeInsertions(Code, Replaces, Style);
22460b57cec5SDimitry Andric   return processReplacements(Cleanup, Code, NewReplaces, Style);
22470b57cec5SDimitry Andric }
22480b57cec5SDimitry Andric 
22490b57cec5SDimitry Andric namespace internal {
22500b57cec5SDimitry Andric std::pair<tooling::Replacements, unsigned>
22510b57cec5SDimitry Andric reformat(const FormatStyle &Style, StringRef Code,
22520b57cec5SDimitry Andric          ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
22530b57cec5SDimitry Andric          unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
22540b57cec5SDimitry Andric          FormattingAttemptStatus *Status) {
22550b57cec5SDimitry Andric   FormatStyle Expanded = expandPresets(Style);
22560b57cec5SDimitry Andric   if (Expanded.DisableFormat)
22570b57cec5SDimitry Andric     return {tooling::Replacements(), 0};
22580b57cec5SDimitry Andric   if (isLikelyXml(Code))
22590b57cec5SDimitry Andric     return {tooling::Replacements(), 0};
22600b57cec5SDimitry Andric   if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
22610b57cec5SDimitry Andric     return {tooling::Replacements(), 0};
22620b57cec5SDimitry Andric 
22630b57cec5SDimitry Andric   typedef std::function<std::pair<tooling::Replacements, unsigned>(
22640b57cec5SDimitry Andric       const Environment &)>
22650b57cec5SDimitry Andric       AnalyzerPass;
22660b57cec5SDimitry Andric   SmallVector<AnalyzerPass, 4> Passes;
22670b57cec5SDimitry Andric 
22680b57cec5SDimitry Andric   if (Style.Language == FormatStyle::LK_Cpp) {
22690b57cec5SDimitry Andric     if (Style.FixNamespaceComments)
22700b57cec5SDimitry Andric       Passes.emplace_back([&](const Environment &Env) {
22710b57cec5SDimitry Andric         return NamespaceEndCommentsFixer(Env, Expanded).process();
22720b57cec5SDimitry Andric       });
22730b57cec5SDimitry Andric 
22740b57cec5SDimitry Andric     if (Style.SortUsingDeclarations)
22750b57cec5SDimitry Andric       Passes.emplace_back([&](const Environment &Env) {
22760b57cec5SDimitry Andric         return UsingDeclarationsSorter(Env, Expanded).process();
22770b57cec5SDimitry Andric       });
22780b57cec5SDimitry Andric   }
22790b57cec5SDimitry Andric 
22800b57cec5SDimitry Andric   if (Style.Language == FormatStyle::LK_JavaScript &&
22810b57cec5SDimitry Andric       Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
22820b57cec5SDimitry Andric     Passes.emplace_back([&](const Environment &Env) {
22830b57cec5SDimitry Andric       return JavaScriptRequoter(Env, Expanded).process();
22840b57cec5SDimitry Andric     });
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric   Passes.emplace_back([&](const Environment &Env) {
22870b57cec5SDimitry Andric     return Formatter(Env, Expanded, Status).process();
22880b57cec5SDimitry Andric   });
22890b57cec5SDimitry Andric 
22900b57cec5SDimitry Andric   auto Env =
22910b57cec5SDimitry Andric       llvm::make_unique<Environment>(Code, FileName, Ranges, FirstStartColumn,
22920b57cec5SDimitry Andric                                      NextStartColumn, LastStartColumn);
22930b57cec5SDimitry Andric   llvm::Optional<std::string> CurrentCode = None;
22940b57cec5SDimitry Andric   tooling::Replacements Fixes;
22950b57cec5SDimitry Andric   unsigned Penalty = 0;
22960b57cec5SDimitry Andric   for (size_t I = 0, E = Passes.size(); I < E; ++I) {
22970b57cec5SDimitry Andric     std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
22980b57cec5SDimitry Andric     auto NewCode = applyAllReplacements(
22990b57cec5SDimitry Andric         CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
23000b57cec5SDimitry Andric     if (NewCode) {
23010b57cec5SDimitry Andric       Fixes = Fixes.merge(PassFixes.first);
23020b57cec5SDimitry Andric       Penalty += PassFixes.second;
23030b57cec5SDimitry Andric       if (I + 1 < E) {
23040b57cec5SDimitry Andric         CurrentCode = std::move(*NewCode);
23050b57cec5SDimitry Andric         Env = llvm::make_unique<Environment>(
23060b57cec5SDimitry Andric             *CurrentCode, FileName,
23070b57cec5SDimitry Andric             tooling::calculateRangesAfterReplacements(Fixes, Ranges),
23080b57cec5SDimitry Andric             FirstStartColumn, NextStartColumn, LastStartColumn);
23090b57cec5SDimitry Andric       }
23100b57cec5SDimitry Andric     }
23110b57cec5SDimitry Andric   }
23120b57cec5SDimitry Andric 
23130b57cec5SDimitry Andric   return {Fixes, Penalty};
23140b57cec5SDimitry Andric }
23150b57cec5SDimitry Andric } // namespace internal
23160b57cec5SDimitry Andric 
23170b57cec5SDimitry Andric tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
23180b57cec5SDimitry Andric                                ArrayRef<tooling::Range> Ranges,
23190b57cec5SDimitry Andric                                StringRef FileName,
23200b57cec5SDimitry Andric                                FormattingAttemptStatus *Status) {
23210b57cec5SDimitry Andric   return internal::reformat(Style, Code, Ranges,
23220b57cec5SDimitry Andric                             /*FirstStartColumn=*/0,
23230b57cec5SDimitry Andric                             /*NextStartColumn=*/0,
23240b57cec5SDimitry Andric                             /*LastStartColumn=*/0, FileName, Status)
23250b57cec5SDimitry Andric       .first;
23260b57cec5SDimitry Andric }
23270b57cec5SDimitry Andric 
23280b57cec5SDimitry Andric tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
23290b57cec5SDimitry Andric                               ArrayRef<tooling::Range> Ranges,
23300b57cec5SDimitry Andric                               StringRef FileName) {
23310b57cec5SDimitry Andric   // cleanups only apply to C++ (they mostly concern ctor commas etc.)
23320b57cec5SDimitry Andric   if (Style.Language != FormatStyle::LK_Cpp)
23330b57cec5SDimitry Andric     return tooling::Replacements();
23340b57cec5SDimitry Andric   return Cleaner(Environment(Code, FileName, Ranges), Style).process().first;
23350b57cec5SDimitry Andric }
23360b57cec5SDimitry Andric 
23370b57cec5SDimitry Andric tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
23380b57cec5SDimitry Andric                                ArrayRef<tooling::Range> Ranges,
23390b57cec5SDimitry Andric                                StringRef FileName, bool *IncompleteFormat) {
23400b57cec5SDimitry Andric   FormattingAttemptStatus Status;
23410b57cec5SDimitry Andric   auto Result = reformat(Style, Code, Ranges, FileName, &Status);
23420b57cec5SDimitry Andric   if (!Status.FormatComplete)
23430b57cec5SDimitry Andric     *IncompleteFormat = true;
23440b57cec5SDimitry Andric   return Result;
23450b57cec5SDimitry Andric }
23460b57cec5SDimitry Andric 
23470b57cec5SDimitry Andric tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
23480b57cec5SDimitry Andric                                               StringRef Code,
23490b57cec5SDimitry Andric                                               ArrayRef<tooling::Range> Ranges,
23500b57cec5SDimitry Andric                                               StringRef FileName) {
23510b57cec5SDimitry Andric   return NamespaceEndCommentsFixer(Environment(Code, FileName, Ranges), Style)
23520b57cec5SDimitry Andric       .process()
23530b57cec5SDimitry Andric       .first;
23540b57cec5SDimitry Andric }
23550b57cec5SDimitry Andric 
23560b57cec5SDimitry Andric tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
23570b57cec5SDimitry Andric                                             StringRef Code,
23580b57cec5SDimitry Andric                                             ArrayRef<tooling::Range> Ranges,
23590b57cec5SDimitry Andric                                             StringRef FileName) {
23600b57cec5SDimitry Andric   return UsingDeclarationsSorter(Environment(Code, FileName, Ranges), Style)
23610b57cec5SDimitry Andric       .process()
23620b57cec5SDimitry Andric       .first;
23630b57cec5SDimitry Andric }
23640b57cec5SDimitry Andric 
23650b57cec5SDimitry Andric LangOptions getFormattingLangOpts(const FormatStyle &Style) {
23660b57cec5SDimitry Andric   LangOptions LangOpts;
23670b57cec5SDimitry Andric   LangOpts.CPlusPlus = 1;
23680b57cec5SDimitry Andric   LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
23690b57cec5SDimitry Andric   LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
23700b57cec5SDimitry Andric   LangOpts.CPlusPlus17 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
23710b57cec5SDimitry Andric   LangOpts.CPlusPlus2a = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
23720b57cec5SDimitry Andric   LangOpts.LineComment = 1;
23730b57cec5SDimitry Andric   bool AlternativeOperators = Style.isCpp();
23740b57cec5SDimitry Andric   LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
23750b57cec5SDimitry Andric   LangOpts.Bool = 1;
23760b57cec5SDimitry Andric   LangOpts.ObjC = 1;
23770b57cec5SDimitry Andric   LangOpts.MicrosoftExt = 1;    // To get kw___try, kw___finally.
23780b57cec5SDimitry Andric   LangOpts.DeclSpecKeyword = 1; // To get __declspec.
23790b57cec5SDimitry Andric   return LangOpts;
23800b57cec5SDimitry Andric }
23810b57cec5SDimitry Andric 
23820b57cec5SDimitry Andric const char *StyleOptionHelpDescription =
23830b57cec5SDimitry Andric     "Coding style, currently supports:\n"
23840b57cec5SDimitry Andric     "  LLVM, Google, Chromium, Mozilla, WebKit.\n"
23850b57cec5SDimitry Andric     "Use -style=file to load style configuration from\n"
23860b57cec5SDimitry Andric     ".clang-format file located in one of the parent\n"
23870b57cec5SDimitry Andric     "directories of the source file (or current\n"
23880b57cec5SDimitry Andric     "directory for stdin).\n"
23890b57cec5SDimitry Andric     "Use -style=\"{key: value, ...}\" to set specific\n"
23900b57cec5SDimitry Andric     "parameters, e.g.:\n"
23910b57cec5SDimitry Andric     "  -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
23920b57cec5SDimitry Andric 
23930b57cec5SDimitry Andric static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
23940b57cec5SDimitry Andric   if (FileName.endswith(".java"))
23950b57cec5SDimitry Andric     return FormatStyle::LK_Java;
23960b57cec5SDimitry Andric   if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
23970b57cec5SDimitry Andric     return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
23980b57cec5SDimitry Andric   if (FileName.endswith(".m") || FileName.endswith(".mm"))
23990b57cec5SDimitry Andric     return FormatStyle::LK_ObjC;
24000b57cec5SDimitry Andric   if (FileName.endswith_lower(".proto") ||
24010b57cec5SDimitry Andric       FileName.endswith_lower(".protodevel"))
24020b57cec5SDimitry Andric     return FormatStyle::LK_Proto;
24030b57cec5SDimitry Andric   if (FileName.endswith_lower(".textpb") ||
24040b57cec5SDimitry Andric       FileName.endswith_lower(".pb.txt") ||
24050b57cec5SDimitry Andric       FileName.endswith_lower(".textproto") ||
24060b57cec5SDimitry Andric       FileName.endswith_lower(".asciipb"))
24070b57cec5SDimitry Andric     return FormatStyle::LK_TextProto;
24080b57cec5SDimitry Andric   if (FileName.endswith_lower(".td"))
24090b57cec5SDimitry Andric     return FormatStyle::LK_TableGen;
24100b57cec5SDimitry Andric   if (FileName.endswith_lower(".cs"))
24110b57cec5SDimitry Andric     return FormatStyle::LK_CSharp;
24120b57cec5SDimitry Andric   return FormatStyle::LK_Cpp;
24130b57cec5SDimitry Andric }
24140b57cec5SDimitry Andric 
24150b57cec5SDimitry Andric FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
24160b57cec5SDimitry Andric   const auto GuessedLanguage = getLanguageByFileName(FileName);
24170b57cec5SDimitry Andric   if (GuessedLanguage == FormatStyle::LK_Cpp) {
24180b57cec5SDimitry Andric     auto Extension = llvm::sys::path::extension(FileName);
24190b57cec5SDimitry Andric     // If there's no file extension (or it's .h), we need to check the contents
24200b57cec5SDimitry Andric     // of the code to see if it contains Objective-C.
24210b57cec5SDimitry Andric     if (Extension.empty() || Extension == ".h") {
24220b57cec5SDimitry Andric       auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
24230b57cec5SDimitry Andric       Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
24240b57cec5SDimitry Andric       ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
24250b57cec5SDimitry Andric       Guesser.process();
24260b57cec5SDimitry Andric       if (Guesser.isObjC())
24270b57cec5SDimitry Andric         return FormatStyle::LK_ObjC;
24280b57cec5SDimitry Andric     }
24290b57cec5SDimitry Andric   }
24300b57cec5SDimitry Andric   return GuessedLanguage;
24310b57cec5SDimitry Andric }
24320b57cec5SDimitry Andric 
24330b57cec5SDimitry Andric const char *DefaultFormatStyle = "file";
24340b57cec5SDimitry Andric 
24350b57cec5SDimitry Andric const char *DefaultFallbackStyle = "LLVM";
24360b57cec5SDimitry Andric 
24370b57cec5SDimitry Andric llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
24380b57cec5SDimitry Andric                                      StringRef FallbackStyleName,
24390b57cec5SDimitry Andric                                      StringRef Code,
24400b57cec5SDimitry Andric                                      llvm::vfs::FileSystem *FS) {
24410b57cec5SDimitry Andric   if (!FS) {
24420b57cec5SDimitry Andric     FS = llvm::vfs::getRealFileSystem().get();
24430b57cec5SDimitry Andric   }
24440b57cec5SDimitry Andric   FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
24450b57cec5SDimitry Andric 
24460b57cec5SDimitry Andric   FormatStyle FallbackStyle = getNoStyle();
24470b57cec5SDimitry Andric   if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
24480b57cec5SDimitry Andric     return make_string_error("Invalid fallback style \"" + FallbackStyleName);
24490b57cec5SDimitry Andric 
24500b57cec5SDimitry Andric   if (StyleName.startswith("{")) {
24510b57cec5SDimitry Andric     // Parse YAML/JSON style from the command line.
24520b57cec5SDimitry Andric     if (std::error_code ec = parseConfiguration(StyleName, &Style))
24530b57cec5SDimitry Andric       return make_string_error("Error parsing -style: " + ec.message());
24540b57cec5SDimitry Andric     return Style;
24550b57cec5SDimitry Andric   }
24560b57cec5SDimitry Andric 
24570b57cec5SDimitry Andric   if (!StyleName.equals_lower("file")) {
24580b57cec5SDimitry Andric     if (!getPredefinedStyle(StyleName, Style.Language, &Style))
24590b57cec5SDimitry Andric       return make_string_error("Invalid value for -style");
24600b57cec5SDimitry Andric     return Style;
24610b57cec5SDimitry Andric   }
24620b57cec5SDimitry Andric 
24630b57cec5SDimitry Andric   // Look for .clang-format/_clang-format file in the file's parent directories.
24640b57cec5SDimitry Andric   SmallString<128> UnsuitableConfigFiles;
24650b57cec5SDimitry Andric   SmallString<128> Path(FileName);
24660b57cec5SDimitry Andric   if (std::error_code EC = FS->makeAbsolute(Path))
24670b57cec5SDimitry Andric     return make_string_error(EC.message());
24680b57cec5SDimitry Andric 
24690b57cec5SDimitry Andric   for (StringRef Directory = Path; !Directory.empty();
24700b57cec5SDimitry Andric        Directory = llvm::sys::path::parent_path(Directory)) {
24710b57cec5SDimitry Andric 
24720b57cec5SDimitry Andric     auto Status = FS->status(Directory);
24730b57cec5SDimitry Andric     if (!Status ||
24740b57cec5SDimitry Andric         Status->getType() != llvm::sys::fs::file_type::directory_file) {
24750b57cec5SDimitry Andric       continue;
24760b57cec5SDimitry Andric     }
24770b57cec5SDimitry Andric 
24780b57cec5SDimitry Andric     SmallString<128> ConfigFile(Directory);
24790b57cec5SDimitry Andric 
24800b57cec5SDimitry Andric     llvm::sys::path::append(ConfigFile, ".clang-format");
24810b57cec5SDimitry Andric     LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric     Status = FS->status(ConfigFile.str());
24840b57cec5SDimitry Andric     bool FoundConfigFile =
24850b57cec5SDimitry Andric         Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
24860b57cec5SDimitry Andric     if (!FoundConfigFile) {
24870b57cec5SDimitry Andric       // Try _clang-format too, since dotfiles are not commonly used on Windows.
24880b57cec5SDimitry Andric       ConfigFile = Directory;
24890b57cec5SDimitry Andric       llvm::sys::path::append(ConfigFile, "_clang-format");
24900b57cec5SDimitry Andric       LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
24910b57cec5SDimitry Andric       Status = FS->status(ConfigFile.str());
24920b57cec5SDimitry Andric       FoundConfigFile = Status && (Status->getType() ==
24930b57cec5SDimitry Andric                                    llvm::sys::fs::file_type::regular_file);
24940b57cec5SDimitry Andric     }
24950b57cec5SDimitry Andric 
24960b57cec5SDimitry Andric     if (FoundConfigFile) {
24970b57cec5SDimitry Andric       llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
24980b57cec5SDimitry Andric           FS->getBufferForFile(ConfigFile.str());
24990b57cec5SDimitry Andric       if (std::error_code EC = Text.getError())
25000b57cec5SDimitry Andric         return make_string_error(EC.message());
25010b57cec5SDimitry Andric       if (std::error_code ec =
25020b57cec5SDimitry Andric               parseConfiguration(Text.get()->getBuffer(), &Style)) {
25030b57cec5SDimitry Andric         if (ec == ParseError::Unsuitable) {
25040b57cec5SDimitry Andric           if (!UnsuitableConfigFiles.empty())
25050b57cec5SDimitry Andric             UnsuitableConfigFiles.append(", ");
25060b57cec5SDimitry Andric           UnsuitableConfigFiles.append(ConfigFile);
25070b57cec5SDimitry Andric           continue;
25080b57cec5SDimitry Andric         }
25090b57cec5SDimitry Andric         return make_string_error("Error reading " + ConfigFile + ": " +
25100b57cec5SDimitry Andric                                  ec.message());
25110b57cec5SDimitry Andric       }
25120b57cec5SDimitry Andric       LLVM_DEBUG(llvm::dbgs()
25130b57cec5SDimitry Andric                  << "Using configuration file " << ConfigFile << "\n");
25140b57cec5SDimitry Andric       return Style;
25150b57cec5SDimitry Andric     }
25160b57cec5SDimitry Andric   }
25170b57cec5SDimitry Andric   if (!UnsuitableConfigFiles.empty())
25180b57cec5SDimitry Andric     return make_string_error("Configuration file(s) do(es) not support " +
25190b57cec5SDimitry Andric                              getLanguageName(Style.Language) + ": " +
25200b57cec5SDimitry Andric                              UnsuitableConfigFiles);
25210b57cec5SDimitry Andric   return FallbackStyle;
25220b57cec5SDimitry Andric }
25230b57cec5SDimitry Andric 
25240b57cec5SDimitry Andric } // namespace format
25250b57cec5SDimitry Andric } // namespace clang
2526