2012-12-04 02:12:45 +08:00
|
|
|
//===--- Format.cpp - Format C++ code -------------------------------------===//
|
|
|
|
//
|
|
|
|
// The LLVM Compiler Infrastructure
|
|
|
|
//
|
|
|
|
// This file is distributed under the University of Illinois Open Source
|
|
|
|
// License. See LICENSE.TXT for details.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
///
|
|
|
|
/// \file
|
|
|
|
/// \brief This file implements functions declared in Format.h. This will be
|
|
|
|
/// split into separate files as we go.
|
|
|
|
///
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2015-09-29 15:53:08 +08:00
|
|
|
#include "clang/Format/Format.h"
|
2016-04-25 23:09:22 +08:00
|
|
|
#include "AffectedRangeManager.h"
|
2013-08-16 19:20:30 +08:00
|
|
|
#include "ContinuationIndenter.h"
|
2013-01-30 05:01:14 +08:00
|
|
|
#include "TokenAnnotator.h"
|
2014-12-11 03:00:42 +08:00
|
|
|
#include "UnwrappedLineFormatter.h"
|
2012-12-04 17:13:33 +08:00
|
|
|
#include "UnwrappedLineParser.h"
|
2013-04-15 22:28:00 +08:00
|
|
|
#include "WhitespaceManager.h"
|
2013-05-16 18:40:07 +08:00
|
|
|
#include "clang/Basic/Diagnostic.h"
|
2014-05-11 00:31:55 +08:00
|
|
|
#include "clang/Basic/DiagnosticOptions.h"
|
2013-01-02 18:28:36 +08:00
|
|
|
#include "clang/Basic/SourceManager.h"
|
2016-04-14 22:47:37 +08:00
|
|
|
#include "clang/Basic/VirtualFileSystem.h"
|
2012-12-04 02:12:45 +08:00
|
|
|
#include "clang/Lex/Lexer.h"
|
2013-03-27 19:52:18 +08:00
|
|
|
#include "llvm/ADT/STLExtras.h"
|
2013-02-13 18:46:36 +08:00
|
|
|
#include "llvm/Support/Allocator.h"
|
2013-01-16 22:55:28 +08:00
|
|
|
#include "llvm/Support/Debug.h"
|
2013-09-30 21:31:48 +08:00
|
|
|
#include "llvm/Support/Path.h"
|
2015-07-04 01:25:16 +08:00
|
|
|
#include "llvm/Support/Regex.h"
|
2014-01-07 19:51:46 +08:00
|
|
|
#include "llvm/Support/YAMLTraits.h"
|
2016-04-25 23:09:22 +08:00
|
|
|
#include <memory>
|
2013-02-13 18:46:36 +08:00
|
|
|
#include <queue>
|
2012-12-04 21:02:32 +08:00
|
|
|
#include <string>
|
|
|
|
|
2014-04-22 11:17:02 +08:00
|
|
|
#define DEBUG_TYPE "format-formatter"
|
|
|
|
|
2013-12-10 18:30:34 +08:00
|
|
|
using clang::format::FormatStyle;
|
|
|
|
|
2014-04-01 20:55:11 +08:00
|
|
|
LLVM_YAML_IS_FLOW_SEQUENCE_VECTOR(std::string)
|
2015-10-06 19:54:18 +08:00
|
|
|
LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::IncludeCategory)
|
2014-04-01 20:55:11 +08:00
|
|
|
|
2013-05-07 23:32:14 +08:00
|
|
|
namespace llvm {
|
|
|
|
namespace yaml {
|
2013-12-10 18:30:34 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
|
|
|
|
IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
|
2014-09-15 19:21:46 +08:00
|
|
|
IO.enumCase(Value, "Java", FormatStyle::LK_Java);
|
2013-12-10 18:30:34 +08:00
|
|
|
IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
|
2014-01-19 17:04:08 +08:00
|
|
|
IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
|
2015-12-25 16:53:31 +08:00
|
|
|
IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-12-10 18:30:34 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
|
|
|
|
IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
|
|
|
|
IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
|
|
|
|
IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
|
|
|
|
IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
|
|
|
|
IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
|
2013-05-13 20:51:40 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-12-10 18:30:34 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
|
|
|
|
IO.enumCase(Value, "Never", FormatStyle::UT_Never);
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::UT_Never);
|
|
|
|
IO.enumCase(Value, "Always", FormatStyle::UT_Always);
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::UT_Always);
|
|
|
|
IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
|
2016-04-14 22:52:26 +08:00
|
|
|
IO.enumCase(Value, "ForContinuationAndIndentation",
|
|
|
|
FormatStyle::UT_ForContinuationAndIndentation);
|
2013-09-28 00:14:22 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2016-03-03 06:44:03 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
|
|
|
|
IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
|
|
|
|
IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
|
|
|
|
IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-04-08 20:46:38 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
|
|
|
|
IO.enumCase(Value, "None", FormatStyle::SFS_None);
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::SFS_None);
|
|
|
|
IO.enumCase(Value, "All", FormatStyle::SFS_All);
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::SFS_All);
|
|
|
|
IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
|
2014-11-26 18:43:58 +08:00
|
|
|
IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
|
2014-04-08 20:46:38 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-09-15 19:11:00 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
|
|
|
|
IO.enumCase(Value, "All", FormatStyle::BOS_All);
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::BOS_All);
|
|
|
|
IO.enumCase(Value, "None", FormatStyle::BOS_None);
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::BOS_None);
|
|
|
|
IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-12-10 18:30:34 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
|
|
|
|
IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
|
|
|
|
IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
|
2015-07-12 11:13:54 +08:00
|
|
|
IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
|
2013-12-10 18:30:34 +08:00
|
|
|
IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
|
|
|
|
IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
|
2013-12-12 17:49:52 +08:00
|
|
|
IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
|
2015-08-10 21:43:19 +08:00
|
|
|
IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
|
2015-09-29 22:57:55 +08:00
|
|
|
IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-12-19 06:20:15 +08:00
|
|
|
template <>
|
|
|
|
struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
|
|
|
|
IO.enumCase(Value, "None", FormatStyle::RTBS_None);
|
|
|
|
IO.enumCase(Value, "All", FormatStyle::RTBS_All);
|
|
|
|
IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
|
|
|
|
IO.enumCase(Value, "TopLevelDefinitions",
|
|
|
|
FormatStyle::RTBS_TopLevelDefinitions);
|
|
|
|
IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-09-29 22:57:55 +08:00
|
|
|
template <>
|
|
|
|
struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
|
|
|
|
static void
|
|
|
|
enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
|
2015-06-29 23:30:42 +08:00
|
|
|
IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
|
|
|
|
IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
|
|
|
|
IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
|
|
|
|
|
|
|
|
// For backward compatibility.
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-08-01 07:16:02 +08:00
|
|
|
template <>
|
2013-12-10 18:30:34 +08:00
|
|
|
struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
|
|
|
|
static void enumeration(IO &IO,
|
|
|
|
FormatStyle::NamespaceIndentationKind &Value) {
|
|
|
|
IO.enumCase(Value, "None", FormatStyle::NI_None);
|
|
|
|
IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
|
|
|
|
IO.enumCase(Value, "All", FormatStyle::NI_All);
|
2013-08-01 07:16:02 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-10-27 20:38:37 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
|
|
|
|
IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
|
|
|
|
IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
|
|
|
|
IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
|
|
|
|
|
|
|
|
// For backward compatibility.
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::BAS_Align);
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-02-19 07:48:37 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
|
2014-06-17 20:40:34 +08:00
|
|
|
IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
|
|
|
|
IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
|
|
|
|
IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
|
|
|
|
|
2014-07-15 03:42:55 +08:00
|
|
|
// For backward compatibility.
|
2014-06-17 20:40:34 +08:00
|
|
|
IO.enumCase(Value, "true", FormatStyle::PAS_Left);
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::PAS_Right);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-12-10 18:18:34 +08:00
|
|
|
template <>
|
2013-12-10 18:30:34 +08:00
|
|
|
struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
|
|
|
|
static void enumeration(IO &IO,
|
|
|
|
FormatStyle::SpaceBeforeParensOptions &Value) {
|
|
|
|
IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
|
2013-12-10 18:18:34 +08:00
|
|
|
IO.enumCase(Value, "ControlStatements",
|
2013-12-10 18:30:34 +08:00
|
|
|
FormatStyle::SBPO_ControlStatements);
|
|
|
|
IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
|
2013-12-10 18:18:34 +08:00
|
|
|
|
|
|
|
// For backward compatibility.
|
2013-12-10 18:30:34 +08:00
|
|
|
IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
|
2013-12-10 18:18:34 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-12-10 18:30:34 +08:00
|
|
|
template <> struct MappingTraits<FormatStyle> {
|
2013-12-10 19:28:13 +08:00
|
|
|
static void mapping(IO &IO, FormatStyle &Style) {
|
|
|
|
// When reading, read the language first, we need it for getPredefinedStyle.
|
|
|
|
IO.mapOptional("Language", Style.Language);
|
|
|
|
|
2013-05-10 19:56:10 +08:00
|
|
|
if (IO.outputting()) {
|
2015-02-19 07:48:37 +08:00
|
|
|
StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
|
|
|
|
"Mozilla", "WebKit", "GNU"};
|
2013-05-10 19:56:10 +08:00
|
|
|
ArrayRef<StringRef> Styles(StylesArray);
|
|
|
|
for (size_t i = 0, e = Styles.size(); i < e; ++i) {
|
|
|
|
StringRef StyleName(Styles[i]);
|
2013-12-10 18:30:34 +08:00
|
|
|
FormatStyle PredefinedStyle;
|
2013-12-10 19:28:13 +08:00
|
|
|
if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
|
2013-05-19 08:53:30 +08:00
|
|
|
Style == PredefinedStyle) {
|
2013-05-10 19:56:10 +08:00
|
|
|
IO.mapOptional("# BasedOnStyle", StyleName);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2013-05-07 23:32:14 +08:00
|
|
|
StringRef BasedOnStyle;
|
|
|
|
IO.mapOptional("BasedOnStyle", BasedOnStyle);
|
2013-11-29 23:19:43 +08:00
|
|
|
if (!BasedOnStyle.empty()) {
|
2013-12-10 19:28:13 +08:00
|
|
|
FormatStyle::LanguageKind OldLanguage = Style.Language;
|
|
|
|
FormatStyle::LanguageKind Language =
|
|
|
|
((FormatStyle *)IO.getContext())->Language;
|
|
|
|
if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
|
2013-05-19 08:53:30 +08:00
|
|
|
IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
|
|
|
|
return;
|
|
|
|
}
|
2013-12-10 19:28:13 +08:00
|
|
|
Style.Language = OldLanguage;
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
|
2015-06-28 22:52:34 +08:00
|
|
|
// For backward compatibility.
|
|
|
|
if (!IO.outputting()) {
|
|
|
|
IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
|
|
|
|
IO.mapOptional("IndentFunctionDeclarationAfterType",
|
|
|
|
Style.IndentWrappedFunctionNames);
|
|
|
|
IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
|
|
|
|
IO.mapOptional("SpaceAfterControlStatementKeyword",
|
|
|
|
Style.SpaceBeforeParens);
|
|
|
|
}
|
|
|
|
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
|
2014-11-19 07:55:27 +08:00
|
|
|
IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("AlignConsecutiveAssignments",
|
|
|
|
Style.AlignConsecutiveAssignments);
|
2015-10-01 18:06:54 +08:00
|
|
|
IO.mapOptional("AlignConsecutiveDeclarations",
|
|
|
|
Style.AlignConsecutiveDeclarations);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
|
2014-12-02 21:24:51 +08:00
|
|
|
IO.mapOptional("AlignOperands", Style.AlignOperands);
|
2013-08-01 07:55:15 +08:00
|
|
|
IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
|
|
|
|
Style.AllowAllParametersOfDeclarationOnNextLine);
|
2014-05-14 17:33:35 +08:00
|
|
|
IO.mapOptional("AllowShortBlocksOnASingleLine",
|
|
|
|
Style.AllowShortBlocksOnASingleLine);
|
2014-09-10 21:11:45 +08:00
|
|
|
IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
|
|
|
|
Style.AllowShortCaseLabelsOnASingleLine);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("AllowShortFunctionsOnASingleLine",
|
|
|
|
Style.AllowShortFunctionsOnASingleLine);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("AllowShortIfStatementsOnASingleLine",
|
|
|
|
Style.AllowShortIfStatementsOnASingleLine);
|
2013-05-16 20:12:21 +08:00
|
|
|
IO.mapOptional("AllowShortLoopsOnASingleLine",
|
|
|
|
Style.AllowShortLoopsOnASingleLine);
|
2014-08-05 20:16:31 +08:00
|
|
|
IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
|
|
|
|
Style.AlwaysBreakAfterDefinitionReturnType);
|
2015-12-19 06:20:15 +08:00
|
|
|
IO.mapOptional("AlwaysBreakAfterReturnType",
|
|
|
|
Style.AlwaysBreakAfterReturnType);
|
|
|
|
// If AlwaysBreakAfterDefinitionReturnType was specified but
|
|
|
|
// AlwaysBreakAfterReturnType was not, initialize the latter from the
|
|
|
|
// former for backwards compatibility.
|
|
|
|
if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
|
|
|
|
Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
|
|
|
|
if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
|
|
|
|
Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
|
|
|
|
else if (Style.AlwaysBreakAfterDefinitionReturnType ==
|
|
|
|
FormatStyle::DRTBS_TopLevel)
|
|
|
|
Style.AlwaysBreakAfterReturnType =
|
|
|
|
FormatStyle::RTBS_TopLevelDefinitions;
|
|
|
|
}
|
|
|
|
|
2013-07-04 20:02:44 +08:00
|
|
|
IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
|
|
|
|
Style.AlwaysBreakBeforeMultilineStrings);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("AlwaysBreakTemplateDeclarations",
|
|
|
|
Style.AlwaysBreakTemplateDeclarations);
|
|
|
|
IO.mapOptional("BinPackArguments", Style.BinPackArguments);
|
|
|
|
IO.mapOptional("BinPackParameters", Style.BinPackParameters);
|
2015-09-29 22:57:55 +08:00
|
|
|
IO.mapOptional("BraceWrapping", Style.BraceWrapping);
|
2013-07-27 00:56:36 +08:00
|
|
|
IO.mapOptional("BreakBeforeBinaryOperators",
|
|
|
|
Style.BreakBeforeBinaryOperators);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
|
2013-11-08 08:57:11 +08:00
|
|
|
IO.mapOptional("BreakBeforeTernaryOperators",
|
|
|
|
Style.BreakBeforeTernaryOperators);
|
2013-07-27 00:56:36 +08:00
|
|
|
IO.mapOptional("BreakConstructorInitializersBeforeComma",
|
|
|
|
Style.BreakConstructorInitializersBeforeComma);
|
2016-02-01 19:21:02 +08:00
|
|
|
IO.mapOptional("BreakAfterJavaFieldAnnotations",
|
|
|
|
Style.BreakAfterJavaFieldAnnotations);
|
|
|
|
IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("ColumnLimit", Style.ColumnLimit);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("CommentPragmas", Style.CommentPragmas);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
|
|
|
|
Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
|
2014-10-29 00:53:38 +08:00
|
|
|
IO.mapOptional("ConstructorInitializerIndentWidth",
|
|
|
|
Style.ConstructorInitializerIndentWidth);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
|
|
|
|
IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
|
2014-06-17 20:40:34 +08:00
|
|
|
IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("DisableFormat", Style.DisableFormat);
|
2013-07-10 22:02:49 +08:00
|
|
|
IO.mapOptional("ExperimentalAutoDetectBinPacking",
|
|
|
|
Style.ExperimentalAutoDetectBinPacking);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("ForEachMacros", Style.ForEachMacros);
|
2015-10-06 19:54:18 +08:00
|
|
|
IO.mapOptional("IncludeCategories", Style.IncludeCategories);
|
2016-03-21 22:11:27 +08:00
|
|
|
IO.mapOptional("IncludeIsMainRegex", Style.IncludeIsMainRegex);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("IndentWidth", Style.IndentWidth);
|
|
|
|
IO.mapOptional("IndentWrappedFunctionNames",
|
|
|
|
Style.IndentWrappedFunctionNames);
|
2014-03-21 21:43:14 +08:00
|
|
|
IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
|
|
|
|
Style.KeepEmptyLinesAtTheStartOfBlocks);
|
2015-07-04 01:25:16 +08:00
|
|
|
IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
|
|
|
|
IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
|
2013-08-01 07:16:02 +08:00
|
|
|
IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
|
2014-10-29 00:53:38 +08:00
|
|
|
IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
|
2014-01-28 23:20:33 +08:00
|
|
|
IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("ObjCSpaceBeforeProtocolList",
|
|
|
|
Style.ObjCSpaceBeforeProtocolList);
|
2013-10-25 22:29:37 +08:00
|
|
|
IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
|
|
|
|
Style.PenaltyBreakBeforeFirstCallParameter);
|
2013-06-08 00:02:52 +08:00
|
|
|
IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
|
2013-07-12 04:41:21 +08:00
|
|
|
IO.mapOptional("PenaltyBreakFirstLessLess",
|
|
|
|
Style.PenaltyBreakFirstLessLess);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
|
|
|
|
IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
|
|
|
|
Style.PenaltyReturnTypeOnItsOwnLine);
|
2014-06-17 20:40:34 +08:00
|
|
|
IO.mapOptional("PointerAlignment", Style.PointerAlignment);
|
2015-12-01 21:28:53 +08:00
|
|
|
IO.mapOptional("ReflowComments", Style.ReflowComments);
|
|
|
|
IO.mapOptional("SortIncludes", Style.SortIncludes);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
|
|
|
|
IO.mapOptional("SpaceBeforeAssignmentOperators",
|
|
|
|
Style.SpaceBeforeAssignmentOperators);
|
|
|
|
IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
|
|
|
|
IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("SpacesBeforeTrailingComments",
|
|
|
|
Style.SpacesBeforeTrailingComments);
|
2013-10-29 22:52:02 +08:00
|
|
|
IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
|
2014-01-15 23:09:08 +08:00
|
|
|
IO.mapOptional("SpacesInContainerLiterals",
|
|
|
|
Style.SpacesInContainerLiterals);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("SpacesInCStyleCastParentheses",
|
|
|
|
Style.SpacesInCStyleCastParentheses);
|
|
|
|
IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
|
|
|
|
IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
|
|
|
|
IO.mapOptional("Standard", Style.Standard);
|
|
|
|
IO.mapOptional("TabWidth", Style.TabWidth);
|
|
|
|
IO.mapOptional("UseTab", Style.UseTab);
|
2016-03-03 06:44:03 +08:00
|
|
|
IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
};
|
2013-11-29 23:19:43 +08:00
|
|
|
|
2015-09-29 22:57:55 +08:00
|
|
|
template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
|
|
|
|
static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
|
|
|
|
IO.mapOptional("AfterClass", Wrapping.AfterClass);
|
|
|
|
IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
|
|
|
|
IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
|
|
|
|
IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
|
|
|
|
IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
|
|
|
|
IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
|
|
|
|
IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
|
|
|
|
IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
|
|
|
|
IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
|
|
|
|
IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
|
|
|
|
IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-10-06 19:54:18 +08:00
|
|
|
template <> struct MappingTraits<FormatStyle::IncludeCategory> {
|
|
|
|
static void mapping(IO &IO, FormatStyle::IncludeCategory &Category) {
|
|
|
|
IO.mapOptional("Regex", Category.Regex);
|
|
|
|
IO.mapOptional("Priority", Category.Priority);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-11-29 23:19:43 +08:00
|
|
|
// Allows to read vector<FormatStyle> while keeping default values.
|
2013-12-10 19:28:13 +08:00
|
|
|
// IO.getContext() should contain a pointer to the FormatStyle structure, that
|
|
|
|
// will be used to get default values for missing keys.
|
|
|
|
// If the first element has no Language specified, it will be treated as the
|
|
|
|
// default one for the following elements.
|
2015-02-19 07:48:37 +08:00
|
|
|
template <> struct DocumentListTraits<std::vector<FormatStyle>> {
|
2013-12-10 19:28:13 +08:00
|
|
|
static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
|
|
|
|
return Seq.size();
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
2013-12-10 19:28:13 +08:00
|
|
|
static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
|
2013-12-10 18:30:34 +08:00
|
|
|
size_t Index) {
|
2013-12-10 19:28:13 +08:00
|
|
|
if (Index >= Seq.size()) {
|
|
|
|
assert(Index == Seq.size());
|
2013-12-10 18:30:34 +08:00
|
|
|
FormatStyle Template;
|
2013-12-10 19:28:13 +08:00
|
|
|
if (Seq.size() > 0 && Seq[0].Language == FormatStyle::LK_None) {
|
2013-11-29 23:19:43 +08:00
|
|
|
Template = Seq[0];
|
2013-12-10 19:28:13 +08:00
|
|
|
} else {
|
2014-05-09 21:11:16 +08:00
|
|
|
Template = *((const FormatStyle *)IO.getContext());
|
2013-12-10 18:30:34 +08:00
|
|
|
Template.Language = FormatStyle::LK_None;
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
2013-12-10 19:28:13 +08:00
|
|
|
Seq.resize(Index + 1, Template);
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
2013-12-10 19:28:13 +08:00
|
|
|
return Seq[Index];
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
|
|
|
};
|
2015-09-23 16:30:47 +08:00
|
|
|
} // namespace yaml
|
|
|
|
} // namespace llvm
|
2013-05-07 23:32:14 +08:00
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
namespace clang {
|
|
|
|
namespace format {
|
|
|
|
|
2014-06-12 11:31:26 +08:00
|
|
|
const std::error_category &getParseCategory() {
|
2014-06-12 10:50:04 +08:00
|
|
|
static ParseErrorCategory C;
|
|
|
|
return C;
|
|
|
|
}
|
|
|
|
std::error_code make_error_code(ParseError e) {
|
2014-06-12 11:31:26 +08:00
|
|
|
return std::error_code(static_cast<int>(e), getParseCategory());
|
2014-06-12 10:50:04 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
const char *ParseErrorCategory::name() const LLVM_NOEXCEPT {
|
|
|
|
return "clang-format.parse_error";
|
|
|
|
}
|
|
|
|
|
|
|
|
std::string ParseErrorCategory::message(int EV) const {
|
|
|
|
switch (static_cast<ParseError>(EV)) {
|
|
|
|
case ParseError::Success:
|
|
|
|
return "Success";
|
|
|
|
case ParseError::Error:
|
|
|
|
return "Invalid argument";
|
|
|
|
case ParseError::Unsuitable:
|
|
|
|
return "Unsuitable";
|
|
|
|
}
|
2014-06-13 03:33:26 +08:00
|
|
|
llvm_unreachable("unexpected parse error");
|
2014-06-12 10:50:04 +08:00
|
|
|
}
|
|
|
|
|
2015-09-29 22:57:55 +08:00
|
|
|
static FormatStyle expandPresets(const FormatStyle &Style) {
|
2015-10-07 12:06:10 +08:00
|
|
|
if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
|
|
|
|
return Style;
|
2015-09-29 22:57:55 +08:00
|
|
|
FormatStyle Expanded = Style;
|
|
|
|
Expanded.BraceWrapping = {false, false, false, false, false, false,
|
|
|
|
false, false, false, false, false};
|
|
|
|
switch (Style.BreakBeforeBraces) {
|
|
|
|
case FormatStyle::BS_Linux:
|
|
|
|
Expanded.BraceWrapping.AfterClass = true;
|
|
|
|
Expanded.BraceWrapping.AfterFunction = true;
|
|
|
|
Expanded.BraceWrapping.AfterNamespace = true;
|
|
|
|
break;
|
|
|
|
case FormatStyle::BS_Mozilla:
|
|
|
|
Expanded.BraceWrapping.AfterClass = true;
|
|
|
|
Expanded.BraceWrapping.AfterEnum = true;
|
|
|
|
Expanded.BraceWrapping.AfterFunction = true;
|
|
|
|
Expanded.BraceWrapping.AfterStruct = true;
|
|
|
|
Expanded.BraceWrapping.AfterUnion = true;
|
|
|
|
break;
|
|
|
|
case FormatStyle::BS_Stroustrup:
|
|
|
|
Expanded.BraceWrapping.AfterFunction = true;
|
|
|
|
Expanded.BraceWrapping.BeforeCatch = true;
|
|
|
|
Expanded.BraceWrapping.BeforeElse = true;
|
|
|
|
break;
|
|
|
|
case FormatStyle::BS_Allman:
|
|
|
|
Expanded.BraceWrapping.AfterClass = true;
|
|
|
|
Expanded.BraceWrapping.AfterControlStatement = true;
|
|
|
|
Expanded.BraceWrapping.AfterEnum = true;
|
|
|
|
Expanded.BraceWrapping.AfterFunction = true;
|
|
|
|
Expanded.BraceWrapping.AfterNamespace = true;
|
|
|
|
Expanded.BraceWrapping.AfterObjCDeclaration = true;
|
|
|
|
Expanded.BraceWrapping.AfterStruct = true;
|
|
|
|
Expanded.BraceWrapping.BeforeCatch = true;
|
|
|
|
Expanded.BraceWrapping.BeforeElse = true;
|
|
|
|
break;
|
|
|
|
case FormatStyle::BS_GNU:
|
|
|
|
Expanded.BraceWrapping = {true, true, true, true, true, true,
|
|
|
|
true, true, true, true, true};
|
|
|
|
break;
|
|
|
|
case FormatStyle::BS_WebKit:
|
|
|
|
Expanded.BraceWrapping.AfterFunction = true;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
return Expanded;
|
|
|
|
}
|
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
FormatStyle getLLVMStyle() {
|
|
|
|
FormatStyle LLVMStyle;
|
2013-11-29 23:19:43 +08:00
|
|
|
LLVMStyle.Language = FormatStyle::LK_Cpp;
|
2012-12-04 02:12:45 +08:00
|
|
|
LLVMStyle.AccessModifierOffset = -2;
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.AlignEscapedNewlinesLeft = false;
|
2015-10-27 20:38:37 +08:00
|
|
|
LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
|
2014-12-02 21:24:51 +08:00
|
|
|
LLVMStyle.AlignOperands = true;
|
2013-08-01 07:55:15 +08:00
|
|
|
LLVMStyle.AlignTrailingComments = true;
|
2015-04-29 21:06:49 +08:00
|
|
|
LLVMStyle.AlignConsecutiveAssignments = false;
|
2015-10-01 18:06:54 +08:00
|
|
|
LLVMStyle.AlignConsecutiveDeclarations = false;
|
2013-01-30 00:03:49 +08:00
|
|
|
LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
|
2014-04-08 20:46:38 +08:00
|
|
|
LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
|
2014-05-14 17:33:35 +08:00
|
|
|
LLVMStyle.AllowShortBlocksOnASingleLine = false;
|
2014-09-10 21:11:45 +08:00
|
|
|
LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
|
2013-01-15 00:24:39 +08:00
|
|
|
LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
|
2013-05-16 20:12:21 +08:00
|
|
|
LLVMStyle.AllowShortLoopsOnASingleLine = false;
|
2015-12-19 06:20:15 +08:00
|
|
|
LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
|
2015-06-29 23:30:42 +08:00
|
|
|
LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
|
2013-07-04 20:02:44 +08:00
|
|
|
LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
|
2013-07-27 00:56:36 +08:00
|
|
|
LLVMStyle.AlwaysBreakTemplateDeclarations = false;
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.BinPackParameters = true;
|
2014-10-09 17:52:05 +08:00
|
|
|
LLVMStyle.BinPackArguments = true;
|
2014-09-15 19:11:00 +08:00
|
|
|
LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
|
2013-11-08 08:57:11 +08:00
|
|
|
LLVMStyle.BreakBeforeTernaryOperators = true;
|
2013-07-27 00:56:36 +08:00
|
|
|
LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
|
2015-10-07 12:06:10 +08:00
|
|
|
LLVMStyle.BraceWrapping = {false, false, false, false, false, false,
|
|
|
|
false, false, false, false, false};
|
2015-10-16 00:03:01 +08:00
|
|
|
LLVMStyle.BreakAfterJavaFieldAnnotations = false;
|
2016-02-01 19:21:02 +08:00
|
|
|
LLVMStyle.BreakConstructorInitializersBeforeComma = false;
|
|
|
|
LLVMStyle.BreakStringLiterals = true;
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.ColumnLimit = 80;
|
2014-04-01 20:55:11 +08:00
|
|
|
LLVMStyle.CommentPragmas = "^ IWYU pragma:";
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
|
2013-08-13 18:58:30 +08:00
|
|
|
LLVMStyle.ConstructorInitializerIndentWidth = 4;
|
2014-04-01 20:55:11 +08:00
|
|
|
LLVMStyle.ContinuationIndentWidth = 4;
|
2014-03-02 20:37:31 +08:00
|
|
|
LLVMStyle.Cpp11BracedListStyle = true;
|
2014-06-17 20:40:34 +08:00
|
|
|
LLVMStyle.DerivePointerAlignment = false;
|
2013-07-10 22:02:49 +08:00
|
|
|
LLVMStyle.ExperimentalAutoDetectBinPacking = false;
|
2014-04-01 20:55:11 +08:00
|
|
|
LLVMStyle.ForEachMacros.push_back("foreach");
|
|
|
|
LLVMStyle.ForEachMacros.push_back("Q_FOREACH");
|
|
|
|
LLVMStyle.ForEachMacros.push_back("BOOST_FOREACH");
|
2015-09-29 15:53:08 +08:00
|
|
|
LLVMStyle.IncludeCategories = {{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
|
|
|
|
{"^(<|\"(gtest|isl|json)/)", 3},
|
|
|
|
{".*", 1}};
|
2016-03-21 22:11:27 +08:00
|
|
|
LLVMStyle.IncludeIsMainRegex = "$";
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.IndentCaseLabels = false;
|
2014-07-09 16:42:42 +08:00
|
|
|
LLVMStyle.IndentWrappedFunctionNames = false;
|
2013-07-27 00:56:36 +08:00
|
|
|
LLVMStyle.IndentWidth = 2;
|
2013-09-05 22:08:34 +08:00
|
|
|
LLVMStyle.TabWidth = 8;
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.MaxEmptyLinesToKeep = 1;
|
2014-03-21 21:43:14 +08:00
|
|
|
LLVMStyle.KeepEmptyLinesAtTheStartOfBlocks = true;
|
2013-08-01 07:16:02 +08:00
|
|
|
LLVMStyle.NamespaceIndentation = FormatStyle::NI_None;
|
2014-10-29 00:53:38 +08:00
|
|
|
LLVMStyle.ObjCBlockIndentWidth = 2;
|
2014-01-28 23:20:33 +08:00
|
|
|
LLVMStyle.ObjCSpaceAfterProperty = false;
|
2013-01-11 04:12:55 +08:00
|
|
|
LLVMStyle.ObjCSpaceBeforeProtocolList = true;
|
2014-06-17 20:40:34 +08:00
|
|
|
LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.SpacesBeforeTrailingComments = 1;
|
2014-03-02 20:37:31 +08:00
|
|
|
LLVMStyle.Standard = FormatStyle::LS_Cpp11;
|
2013-09-28 00:14:22 +08:00
|
|
|
LLVMStyle.UseTab = FormatStyle::UT_Never;
|
2016-03-03 06:44:03 +08:00
|
|
|
LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
|
2015-12-01 21:28:53 +08:00
|
|
|
LLVMStyle.ReflowComments = true;
|
2013-08-20 20:36:34 +08:00
|
|
|
LLVMStyle.SpacesInParentheses = false;
|
2014-08-26 19:41:14 +08:00
|
|
|
LLVMStyle.SpacesInSquareBrackets = false;
|
2013-08-20 20:36:34 +08:00
|
|
|
LLVMStyle.SpaceInEmptyParentheses = false;
|
2014-01-15 23:09:08 +08:00
|
|
|
LLVMStyle.SpacesInContainerLiterals = true;
|
2013-08-20 20:36:34 +08:00
|
|
|
LLVMStyle.SpacesInCStyleCastParentheses = false;
|
2014-09-03 15:37:29 +08:00
|
|
|
LLVMStyle.SpaceAfterCStyleCast = false;
|
2013-12-10 18:18:34 +08:00
|
|
|
LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
|
2013-09-25 23:15:02 +08:00
|
|
|
LLVMStyle.SpaceBeforeAssignmentOperators = true;
|
2013-10-29 22:52:02 +08:00
|
|
|
LLVMStyle.SpacesInAngles = false;
|
2013-07-12 04:41:21 +08:00
|
|
|
|
2013-12-20 00:45:34 +08:00
|
|
|
LLVMStyle.PenaltyBreakComment = 300;
|
2013-12-10 23:42:15 +08:00
|
|
|
LLVMStyle.PenaltyBreakFirstLessLess = 120;
|
|
|
|
LLVMStyle.PenaltyBreakString = 1000;
|
|
|
|
LLVMStyle.PenaltyExcessCharacter = 1000000;
|
2013-07-12 04:41:21 +08:00
|
|
|
LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 60;
|
2013-10-25 22:29:37 +08:00
|
|
|
LLVMStyle.PenaltyBreakBeforeFirstCallParameter = 19;
|
2013-07-12 04:41:21 +08:00
|
|
|
|
2014-05-22 23:12:22 +08:00
|
|
|
LLVMStyle.DisableFormat = false;
|
2015-11-16 20:38:56 +08:00
|
|
|
LLVMStyle.SortIncludes = true;
|
2014-05-22 23:12:22 +08:00
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
return LLVMStyle;
|
|
|
|
}
|
|
|
|
|
2014-02-03 04:50:45 +08:00
|
|
|
FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
|
2013-12-10 23:42:15 +08:00
|
|
|
FormatStyle GoogleStyle = getLLVMStyle();
|
2014-02-03 04:50:45 +08:00
|
|
|
GoogleStyle.Language = Language;
|
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
GoogleStyle.AccessModifierOffset = -1;
|
2013-05-06 22:11:27 +08:00
|
|
|
GoogleStyle.AlignEscapedNewlinesLeft = true;
|
2013-04-24 21:46:00 +08:00
|
|
|
GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
|
2013-05-24 02:05:18 +08:00
|
|
|
GoogleStyle.AllowShortLoopsOnASingleLine = true;
|
2013-07-04 20:02:44 +08:00
|
|
|
GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
|
2013-07-27 00:56:36 +08:00
|
|
|
GoogleStyle.AlwaysBreakTemplateDeclarations = true;
|
2013-05-06 22:11:27 +08:00
|
|
|
GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
|
2014-06-17 20:40:34 +08:00
|
|
|
GoogleStyle.DerivePointerAlignment = true;
|
2015-09-29 15:53:08 +08:00
|
|
|
GoogleStyle.IncludeCategories = {{"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
|
2016-03-21 22:11:27 +08:00
|
|
|
GoogleStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
|
2013-05-06 22:11:27 +08:00
|
|
|
GoogleStyle.IndentCaseLabels = true;
|
2014-03-21 21:43:14 +08:00
|
|
|
GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
|
2014-01-28 23:20:33 +08:00
|
|
|
GoogleStyle.ObjCSpaceAfterProperty = false;
|
2013-01-11 04:12:55 +08:00
|
|
|
GoogleStyle.ObjCSpaceBeforeProtocolList = false;
|
2014-06-17 20:40:34 +08:00
|
|
|
GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
|
2013-05-06 22:11:27 +08:00
|
|
|
GoogleStyle.SpacesBeforeTrailingComments = 2;
|
|
|
|
GoogleStyle.Standard = FormatStyle::LS_Auto;
|
2013-07-12 04:41:21 +08:00
|
|
|
|
|
|
|
GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
|
2013-10-25 22:29:37 +08:00
|
|
|
GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
|
2013-07-12 04:41:21 +08:00
|
|
|
|
2014-09-15 19:21:46 +08:00
|
|
|
if (Language == FormatStyle::LK_Java) {
|
2015-10-27 20:38:37 +08:00
|
|
|
GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
|
2014-12-02 21:24:51 +08:00
|
|
|
GoogleStyle.AlignOperands = false;
|
2015-01-05 04:40:45 +08:00
|
|
|
GoogleStyle.AlignTrailingComments = false;
|
2014-11-26 18:43:58 +08:00
|
|
|
GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
|
2015-01-05 04:40:45 +08:00
|
|
|
GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
|
2015-01-14 20:24:59 +08:00
|
|
|
GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
|
2014-09-15 19:21:46 +08:00
|
|
|
GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
|
|
|
|
GoogleStyle.ColumnLimit = 100;
|
|
|
|
GoogleStyle.SpaceAfterCStyleCast = true;
|
2014-11-14 16:22:46 +08:00
|
|
|
GoogleStyle.SpacesBeforeTrailingComments = 1;
|
2014-09-15 19:21:46 +08:00
|
|
|
} else if (Language == FormatStyle::LK_JavaScript) {
|
2015-10-27 20:38:37 +08:00
|
|
|
GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
|
2015-12-21 21:52:19 +08:00
|
|
|
GoogleStyle.AlignOperands = false;
|
2015-10-27 20:38:37 +08:00
|
|
|
GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
|
|
|
|
GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
|
2014-11-06 01:22:31 +08:00
|
|
|
GoogleStyle.BreakBeforeTernaryOperators = false;
|
2016-02-23 04:24:11 +08:00
|
|
|
GoogleStyle.CommentPragmas = "@(export|return|see|visibility) ";
|
2014-05-09 18:28:58 +08:00
|
|
|
GoogleStyle.MaxEmptyLinesToKeep = 3;
|
2014-02-03 04:50:45 +08:00
|
|
|
GoogleStyle.SpacesInContainerLiterals = false;
|
2016-03-03 06:44:03 +08:00
|
|
|
GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
|
2014-02-03 04:50:45 +08:00
|
|
|
} else if (Language == FormatStyle::LK_Proto) {
|
2014-04-08 20:46:38 +08:00
|
|
|
GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
|
2014-04-15 17:54:30 +08:00
|
|
|
GoogleStyle.SpacesInContainerLiterals = false;
|
2014-02-03 04:50:45 +08:00
|
|
|
}
|
2013-12-10 19:28:13 +08:00
|
|
|
|
2014-02-03 04:50:45 +08:00
|
|
|
return GoogleStyle;
|
2014-01-19 17:04:08 +08:00
|
|
|
}
|
|
|
|
|
2014-02-03 04:50:45 +08:00
|
|
|
FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
|
|
|
|
FormatStyle ChromiumStyle = getGoogleStyle(Language);
|
2014-11-27 00:43:18 +08:00
|
|
|
if (Language == FormatStyle::LK_Java) {
|
2015-01-05 04:40:45 +08:00
|
|
|
ChromiumStyle.AllowShortIfStatementsOnASingleLine = true;
|
2015-10-16 00:03:01 +08:00
|
|
|
ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
|
2014-11-27 00:43:18 +08:00
|
|
|
ChromiumStyle.ContinuationIndentWidth = 8;
|
2015-10-16 00:03:01 +08:00
|
|
|
ChromiumStyle.IndentWidth = 4;
|
2014-11-27 00:43:18 +08:00
|
|
|
} else {
|
|
|
|
ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
|
|
|
|
ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
|
|
|
|
ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
|
|
|
|
ChromiumStyle.AllowShortLoopsOnASingleLine = false;
|
|
|
|
ChromiumStyle.BinPackParameters = false;
|
|
|
|
ChromiumStyle.DerivePointerAlignment = false;
|
|
|
|
}
|
2015-12-23 06:42:56 +08:00
|
|
|
ChromiumStyle.SortIncludes = false;
|
2013-01-15 00:24:39 +08:00
|
|
|
return ChromiumStyle;
|
|
|
|
}
|
|
|
|
|
2013-05-06 22:11:27 +08:00
|
|
|
FormatStyle getMozillaStyle() {
|
|
|
|
FormatStyle MozillaStyle = getLLVMStyle();
|
|
|
|
MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
|
2015-06-29 23:18:58 +08:00
|
|
|
MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
|
2015-12-19 06:20:15 +08:00
|
|
|
MozillaStyle.AlwaysBreakAfterReturnType =
|
|
|
|
FormatStyle::RTBS_TopLevelDefinitions;
|
2015-06-29 23:30:42 +08:00
|
|
|
MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
|
|
|
|
FormatStyle::DRTBS_TopLevel;
|
2015-06-29 23:18:58 +08:00
|
|
|
MozillaStyle.AlwaysBreakTemplateDeclarations = true;
|
2015-07-12 11:13:54 +08:00
|
|
|
MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
|
2015-06-29 23:18:58 +08:00
|
|
|
MozillaStyle.BreakConstructorInitializersBeforeComma = true;
|
|
|
|
MozillaStyle.ConstructorInitializerIndentWidth = 2;
|
|
|
|
MozillaStyle.ContinuationIndentWidth = 2;
|
2014-03-02 20:37:31 +08:00
|
|
|
MozillaStyle.Cpp11BracedListStyle = false;
|
2013-05-06 22:11:27 +08:00
|
|
|
MozillaStyle.IndentCaseLabels = true;
|
2014-01-28 23:20:33 +08:00
|
|
|
MozillaStyle.ObjCSpaceAfterProperty = true;
|
2013-05-06 22:11:27 +08:00
|
|
|
MozillaStyle.ObjCSpaceBeforeProtocolList = false;
|
|
|
|
MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
|
2014-06-17 20:40:34 +08:00
|
|
|
MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
|
2013-05-06 22:11:27 +08:00
|
|
|
return MozillaStyle;
|
|
|
|
}
|
|
|
|
|
2013-07-24 21:10:59 +08:00
|
|
|
FormatStyle getWebKitStyle() {
|
|
|
|
FormatStyle Style = getLLVMStyle();
|
2013-08-01 07:16:02 +08:00
|
|
|
Style.AccessModifierOffset = -4;
|
2015-10-27 20:38:37 +08:00
|
|
|
Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
|
2014-12-02 21:24:51 +08:00
|
|
|
Style.AlignOperands = false;
|
2013-08-01 07:55:15 +08:00
|
|
|
Style.AlignTrailingComments = false;
|
2014-09-15 19:11:00 +08:00
|
|
|
Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
|
2015-08-10 21:43:19 +08:00
|
|
|
Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
|
2013-07-27 00:56:36 +08:00
|
|
|
Style.BreakConstructorInitializersBeforeComma = true;
|
2014-03-02 20:37:31 +08:00
|
|
|
Style.Cpp11BracedListStyle = false;
|
2013-08-01 07:16:02 +08:00
|
|
|
Style.ColumnLimit = 0;
|
2013-07-27 00:56:36 +08:00
|
|
|
Style.IndentWidth = 4;
|
2013-08-01 07:16:02 +08:00
|
|
|
Style.NamespaceIndentation = FormatStyle::NI_Inner;
|
2014-10-29 00:53:38 +08:00
|
|
|
Style.ObjCBlockIndentWidth = 4;
|
2014-01-28 23:20:33 +08:00
|
|
|
Style.ObjCSpaceAfterProperty = true;
|
2014-06-17 20:40:34 +08:00
|
|
|
Style.PointerAlignment = FormatStyle::PAS_Left;
|
2014-03-02 20:37:31 +08:00
|
|
|
Style.Standard = FormatStyle::LS_Cpp03;
|
2013-07-24 21:10:59 +08:00
|
|
|
return Style;
|
|
|
|
}
|
|
|
|
|
2013-12-10 23:42:15 +08:00
|
|
|
FormatStyle getGNUStyle() {
|
|
|
|
FormatStyle Style = getLLVMStyle();
|
2015-06-29 23:30:42 +08:00
|
|
|
Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
|
2015-12-19 06:20:15 +08:00
|
|
|
Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
|
2014-09-15 19:11:00 +08:00
|
|
|
Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
|
2013-12-12 17:49:52 +08:00
|
|
|
Style.BreakBeforeBraces = FormatStyle::BS_GNU;
|
2013-12-10 23:42:15 +08:00
|
|
|
Style.BreakBeforeTernaryOperators = true;
|
2014-03-02 20:37:31 +08:00
|
|
|
Style.Cpp11BracedListStyle = false;
|
2013-12-10 23:42:15 +08:00
|
|
|
Style.ColumnLimit = 79;
|
|
|
|
Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
|
2014-03-02 20:37:31 +08:00
|
|
|
Style.Standard = FormatStyle::LS_Cpp03;
|
2013-12-10 23:42:15 +08:00
|
|
|
return Style;
|
|
|
|
}
|
|
|
|
|
2014-05-22 23:12:22 +08:00
|
|
|
FormatStyle getNoStyle() {
|
|
|
|
FormatStyle NoStyle = getLLVMStyle();
|
|
|
|
NoStyle.DisableFormat = true;
|
2015-11-16 20:38:56 +08:00
|
|
|
NoStyle.SortIncludes = false;
|
2014-05-22 23:12:22 +08:00
|
|
|
return NoStyle;
|
|
|
|
}
|
|
|
|
|
2013-12-10 19:28:13 +08:00
|
|
|
bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
|
|
|
|
FormatStyle *Style) {
|
|
|
|
if (Name.equals_lower("llvm")) {
|
2013-05-19 08:53:30 +08:00
|
|
|
*Style = getLLVMStyle();
|
2013-12-10 19:28:13 +08:00
|
|
|
} else if (Name.equals_lower("chromium")) {
|
2014-02-03 04:50:45 +08:00
|
|
|
*Style = getChromiumStyle(Language);
|
2013-12-10 19:28:13 +08:00
|
|
|
} else if (Name.equals_lower("mozilla")) {
|
2013-05-19 08:53:30 +08:00
|
|
|
*Style = getMozillaStyle();
|
2013-12-10 19:28:13 +08:00
|
|
|
} else if (Name.equals_lower("google")) {
|
2014-02-03 04:50:45 +08:00
|
|
|
*Style = getGoogleStyle(Language);
|
2013-12-10 19:28:13 +08:00
|
|
|
} else if (Name.equals_lower("webkit")) {
|
2013-07-24 21:10:59 +08:00
|
|
|
*Style = getWebKitStyle();
|
2013-12-10 23:42:15 +08:00
|
|
|
} else if (Name.equals_lower("gnu")) {
|
|
|
|
*Style = getGNUStyle();
|
2014-05-22 23:12:22 +08:00
|
|
|
} else if (Name.equals_lower("none")) {
|
|
|
|
*Style = getNoStyle();
|
2013-12-10 19:28:13 +08:00
|
|
|
} else {
|
2013-05-19 08:53:30 +08:00
|
|
|
return false;
|
2013-12-10 19:28:13 +08:00
|
|
|
}
|
2013-05-07 23:32:14 +08:00
|
|
|
|
2013-12-10 19:28:13 +08:00
|
|
|
Style->Language = Language;
|
2013-05-19 08:53:30 +08:00
|
|
|
return true;
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
|
2014-06-12 22:02:15 +08:00
|
|
|
std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
|
2013-11-29 23:19:43 +08:00
|
|
|
assert(Style);
|
2013-12-10 19:28:13 +08:00
|
|
|
FormatStyle::LanguageKind Language = Style->Language;
|
|
|
|
assert(Language != FormatStyle::LK_None);
|
2013-05-20 23:18:01 +08:00
|
|
|
if (Text.trim().empty())
|
2014-06-12 10:50:04 +08:00
|
|
|
return make_error_code(ParseError::Error);
|
2013-11-29 23:19:43 +08:00
|
|
|
|
|
|
|
std::vector<FormatStyle> Styles;
|
2013-05-07 23:32:14 +08:00
|
|
|
llvm::yaml::Input Input(Text);
|
2013-12-10 19:28:13 +08:00
|
|
|
// DocumentListTraits<vector<FormatStyle>> uses the context to get default
|
|
|
|
// values for the fields, keys for which are missing from the configuration.
|
|
|
|
// Mapping also uses the context to get the language to find the correct
|
|
|
|
// base style.
|
|
|
|
Input.setContext(Style);
|
2013-11-29 23:19:43 +08:00
|
|
|
Input >> Styles;
|
|
|
|
if (Input.error())
|
|
|
|
return Input.error();
|
|
|
|
|
2013-12-10 19:28:13 +08:00
|
|
|
for (unsigned i = 0; i < Styles.size(); ++i) {
|
2013-11-29 23:19:43 +08:00
|
|
|
// Ensures that only the first configuration can skip the Language option.
|
2013-12-10 19:28:13 +08:00
|
|
|
if (Styles[i].Language == FormatStyle::LK_None && i != 0)
|
2014-06-12 10:50:04 +08:00
|
|
|
return make_error_code(ParseError::Error);
|
2013-11-29 23:19:43 +08:00
|
|
|
// Ensure that each language is configured at most once.
|
2013-12-10 19:28:13 +08:00
|
|
|
for (unsigned j = 0; j < i; ++j) {
|
|
|
|
if (Styles[i].Language == Styles[j].Language) {
|
|
|
|
DEBUG(llvm::dbgs()
|
|
|
|
<< "Duplicate languages in the config file on positions " << j
|
|
|
|
<< " and " << i << "\n");
|
2014-06-12 10:50:04 +08:00
|
|
|
return make_error_code(ParseError::Error);
|
2013-12-10 19:28:13 +08:00
|
|
|
}
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// Look for a suitable configuration starting from the end, so we can
|
|
|
|
// find the configuration for the specific language first, and the default
|
2013-12-10 19:28:13 +08:00
|
|
|
// configuration (which can only be at slot 0) after it.
|
|
|
|
for (int i = Styles.size() - 1; i >= 0; --i) {
|
|
|
|
if (Styles[i].Language == Language ||
|
2013-11-29 23:19:43 +08:00
|
|
|
Styles[i].Language == FormatStyle::LK_None) {
|
|
|
|
*Style = Styles[i];
|
2013-12-10 19:28:13 +08:00
|
|
|
Style->Language = Language;
|
2014-06-12 10:50:04 +08:00
|
|
|
return make_error_code(ParseError::Success);
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
|
|
|
}
|
2014-06-12 10:50:04 +08:00
|
|
|
return make_error_code(ParseError::Unsuitable);
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
std::string configurationAsText(const FormatStyle &Style) {
|
|
|
|
std::string Text;
|
|
|
|
llvm::raw_string_ostream Stream(Text);
|
|
|
|
llvm::yaml::Output Output(Stream);
|
|
|
|
// We use the same mapping method for input and output, so we need a non-const
|
|
|
|
// reference here.
|
2015-09-29 22:57:55 +08:00
|
|
|
FormatStyle NonConstStyle = expandPresets(Style);
|
2013-05-07 23:32:14 +08:00
|
|
|
Output << NonConstStyle;
|
2013-05-13 20:56:35 +08:00
|
|
|
return Stream.str();
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
|
2013-07-01 06:29:28 +08:00
|
|
|
namespace {
|
|
|
|
|
2013-05-28 19:55:06 +08:00
|
|
|
class FormatTokenLexer {
|
2012-12-08 00:15:44 +08:00
|
|
|
public:
|
2016-04-28 15:52:03 +08:00
|
|
|
FormatTokenLexer(const SourceManager &SourceMgr, FileID ID,
|
2016-04-25 23:09:22 +08:00
|
|
|
const FormatStyle &Style, encoding::Encoding Encoding)
|
2014-05-09 16:15:10 +08:00
|
|
|
: FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
|
2015-02-19 07:48:37 +08:00
|
|
|
LessStashed(false), Column(0), TrailingWhitespace(0),
|
|
|
|
SourceMgr(SourceMgr), ID(ID), Style(Style),
|
|
|
|
IdentTable(getFormattingLangOpts(Style)), Keywords(IdentTable),
|
2016-03-17 21:03:41 +08:00
|
|
|
Encoding(Encoding), FirstInLineIndex(0), FormattingDisabled(false),
|
|
|
|
MacroBlockBeginRegex(Style.MacroBlockBegin),
|
2015-07-04 01:25:16 +08:00
|
|
|
MacroBlockEndRegex(Style.MacroBlockEnd) {
|
2014-09-09 22:37:39 +08:00
|
|
|
Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
|
|
|
|
getFormattingLangOpts(Style)));
|
|
|
|
Lex->SetKeepWhitespaceMode(true);
|
2014-04-01 20:55:11 +08:00
|
|
|
|
2014-05-09 21:11:16 +08:00
|
|
|
for (const std::string &ForEachMacro : Style.ForEachMacros)
|
2014-04-01 20:55:11 +08:00
|
|
|
ForEachMacros.push_back(&IdentTable.get(ForEachMacro));
|
|
|
|
std::sort(ForEachMacros.begin(), ForEachMacros.end());
|
2012-12-08 00:15:44 +08:00
|
|
|
}
|
|
|
|
|
2013-05-28 19:55:06 +08:00
|
|
|
ArrayRef<FormatToken *> lex() {
|
|
|
|
assert(Tokens.empty());
|
2014-04-14 17:14:11 +08:00
|
|
|
assert(FirstInLineIndex == 0);
|
2013-05-28 19:55:06 +08:00
|
|
|
do {
|
|
|
|
Tokens.push_back(getNextToken());
|
2016-05-17 14:29:33 +08:00
|
|
|
if (Style.Language == FormatStyle::LK_JavaScript) {
|
2015-10-18 15:02:28 +08:00
|
|
|
tryParseJSRegexLiteral();
|
2016-05-17 14:29:33 +08:00
|
|
|
tryParseTemplateString();
|
|
|
|
}
|
2013-11-21 20:43:57 +08:00
|
|
|
tryMergePreviousTokens();
|
2015-02-20 21:47:38 +08:00
|
|
|
if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
|
2014-04-14 17:14:11 +08:00
|
|
|
FirstInLineIndex = Tokens.size() - 1;
|
2013-05-28 19:55:06 +08:00
|
|
|
} while (Tokens.back()->Tok.isNot(tok::eof));
|
|
|
|
return Tokens;
|
|
|
|
}
|
|
|
|
|
2014-11-04 20:41:02 +08:00
|
|
|
const AdditionalKeywords &getKeywords() { return Keywords; }
|
2013-05-28 19:55:06 +08:00
|
|
|
|
|
|
|
private:
|
2013-11-21 20:43:57 +08:00
|
|
|
void tryMergePreviousTokens() {
|
2013-11-29 23:19:43 +08:00
|
|
|
if (tryMerge_TMacro())
|
|
|
|
return;
|
2014-04-14 17:14:11 +08:00
|
|
|
if (tryMergeConflictMarkers())
|
|
|
|
return;
|
2015-02-19 07:48:37 +08:00
|
|
|
if (tryMergeLessLess())
|
|
|
|
return;
|
2013-11-29 23:19:43 +08:00
|
|
|
|
|
|
|
if (Style.Language == FormatStyle::LK_JavaScript) {
|
2015-03-09 00:06:46 +08:00
|
|
|
static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
|
|
|
|
static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
|
|
|
|
tok::equal};
|
|
|
|
static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
|
|
|
|
tok::greaterequal};
|
|
|
|
static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
|
2015-05-21 20:23:34 +08:00
|
|
|
// FIXME: Investigate what token type gives the correct operator priority.
|
|
|
|
if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
|
2013-11-29 23:19:43 +08:00
|
|
|
return;
|
2015-05-21 20:23:34 +08:00
|
|
|
if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
|
2013-11-29 23:19:43 +08:00
|
|
|
return;
|
2015-05-21 20:23:34 +08:00
|
|
|
if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
|
2013-11-29 23:19:43 +08:00
|
|
|
return;
|
2015-05-21 20:23:34 +08:00
|
|
|
if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
|
2014-05-19 15:27:02 +08:00
|
|
|
return;
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
2013-11-21 20:43:57 +08:00
|
|
|
}
|
|
|
|
|
2015-02-19 07:48:37 +08:00
|
|
|
bool tryMergeLessLess() {
|
|
|
|
// Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
|
2015-02-21 05:09:01 +08:00
|
|
|
if (Tokens.size() < 3)
|
|
|
|
return false;
|
2015-02-19 07:48:37 +08:00
|
|
|
|
2015-02-21 05:09:01 +08:00
|
|
|
bool FourthTokenIsLess = false;
|
|
|
|
if (Tokens.size() > 3)
|
|
|
|
FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
|
2015-02-19 07:48:37 +08:00
|
|
|
|
2015-02-21 05:09:01 +08:00
|
|
|
auto First = Tokens.end() - 3;
|
|
|
|
if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
|
|
|
|
First[0]->isNot(tok::less) || FourthTokenIsLess)
|
2015-02-19 07:48:37 +08:00
|
|
|
return false;
|
|
|
|
|
|
|
|
// Only merge if there currently is no whitespace between the two "<".
|
2015-02-21 05:09:01 +08:00
|
|
|
if (First[1]->WhitespaceRange.getBegin() !=
|
|
|
|
First[1]->WhitespaceRange.getEnd())
|
2015-02-19 07:48:37 +08:00
|
|
|
return false;
|
|
|
|
|
2015-02-21 05:09:01 +08:00
|
|
|
First[0]->Tok.setKind(tok::lessless);
|
|
|
|
First[0]->TokenText = "<<";
|
|
|
|
First[0]->ColumnWidth += 1;
|
2015-02-19 07:48:37 +08:00
|
|
|
Tokens.erase(Tokens.end() - 2);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2015-05-21 20:23:34 +08:00
|
|
|
bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds, TokenType NewType) {
|
2013-11-29 23:19:43 +08:00
|
|
|
if (Tokens.size() < Kinds.size())
|
2013-11-21 20:43:57 +08:00
|
|
|
return false;
|
2013-11-29 23:19:43 +08:00
|
|
|
|
|
|
|
SmallVectorImpl<FormatToken *>::const_iterator First =
|
|
|
|
Tokens.end() - Kinds.size();
|
|
|
|
if (!First[0]->is(Kinds[0]))
|
2013-11-21 20:43:57 +08:00
|
|
|
return false;
|
2013-11-29 23:19:43 +08:00
|
|
|
unsigned AddLength = 0;
|
|
|
|
for (unsigned i = 1; i < Kinds.size(); ++i) {
|
2015-02-19 07:48:37 +08:00
|
|
|
if (!First[i]->is(Kinds[i]) ||
|
|
|
|
First[i]->WhitespaceRange.getBegin() !=
|
|
|
|
First[i]->WhitespaceRange.getEnd())
|
2013-11-29 23:19:43 +08:00
|
|
|
return false;
|
|
|
|
AddLength += First[i]->TokenText.size();
|
|
|
|
}
|
|
|
|
Tokens.resize(Tokens.size() - Kinds.size() + 1);
|
|
|
|
First[0]->TokenText = StringRef(First[0]->TokenText.data(),
|
|
|
|
First[0]->TokenText.size() + AddLength);
|
|
|
|
First[0]->ColumnWidth += AddLength;
|
2015-05-21 20:23:34 +08:00
|
|
|
First[0]->Type = NewType;
|
2013-11-21 20:43:57 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2015-10-18 15:02:28 +08:00
|
|
|
// Returns \c true if \p Tok can only be followed by an operand in JavaScript.
|
|
|
|
bool precedesOperand(FormatToken *Tok) {
|
|
|
|
// NB: This is not entirely correct, as an r_paren can introduce an operand
|
|
|
|
// location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
|
|
|
|
// corner case to not matter in practice, though.
|
|
|
|
return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
|
|
|
|
tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
|
|
|
|
tok::colon, tok::question, tok::tilde) ||
|
|
|
|
Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
|
|
|
|
tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
|
|
|
|
tok::kw_typeof, Keywords.kw_instanceof,
|
|
|
|
Keywords.kw_in) ||
|
|
|
|
Tok->isBinaryOperator();
|
|
|
|
}
|
|
|
|
|
|
|
|
bool canPrecedeRegexLiteral(FormatToken *Prev) {
|
|
|
|
if (!Prev)
|
|
|
|
return true;
|
|
|
|
|
|
|
|
// Regex literals can only follow after prefix unary operators, not after
|
|
|
|
// postfix unary operators. If the '++' is followed by a non-operand
|
|
|
|
// introducing token, the slash here is the operand and not the start of a
|
|
|
|
// regex.
|
|
|
|
if (Prev->isOneOf(tok::plusplus, tok::minusminus))
|
|
|
|
return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
|
|
|
|
|
|
|
|
// The previous token must introduce an operand location where regex
|
|
|
|
// literals can occur.
|
|
|
|
if (!precedesOperand(Prev))
|
2014-05-12 19:29:50 +08:00
|
|
|
return false;
|
2015-10-18 15:02:28 +08:00
|
|
|
|
2014-05-12 19:29:50 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2015-10-18 15:02:28 +08:00
|
|
|
// Tries to parse a JavaScript Regex literal starting at the current token,
|
|
|
|
// if that begins with a slash and is in a location where JavaScript allows
|
|
|
|
// regex literals. Changes the current token to a regex literal and updates
|
|
|
|
// its text if successful.
|
|
|
|
void tryParseJSRegexLiteral() {
|
|
|
|
FormatToken *RegexToken = Tokens.back();
|
|
|
|
if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
|
|
|
|
return;
|
2015-06-25 00:01:02 +08:00
|
|
|
|
2015-10-18 15:02:28 +08:00
|
|
|
FormatToken *Prev = nullptr;
|
|
|
|
for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
|
|
|
|
// NB: Because previous pointers are not initialized yet, this cannot use
|
|
|
|
// Token.getPreviousNonComment.
|
|
|
|
if ((*I)->isNot(tok::comment)) {
|
|
|
|
Prev = *I;
|
|
|
|
break;
|
|
|
|
}
|
2015-06-25 00:01:02 +08:00
|
|
|
}
|
|
|
|
|
2015-10-18 15:02:28 +08:00
|
|
|
if (!canPrecedeRegexLiteral(Prev))
|
|
|
|
return;
|
2015-06-25 00:01:02 +08:00
|
|
|
|
2015-10-18 15:02:28 +08:00
|
|
|
// 'Manually' lex ahead in the current file buffer.
|
|
|
|
const char *Offset = Lex->getBufferLocation();
|
|
|
|
const char *RegexBegin = Offset - RegexToken->TokenText.size();
|
|
|
|
StringRef Buffer = Lex->getBuffer();
|
2015-10-12 11:13:48 +08:00
|
|
|
bool InCharacterClass = false;
|
2015-10-18 15:02:28 +08:00
|
|
|
bool HaveClosingSlash = false;
|
|
|
|
for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
|
|
|
|
// Regular expressions are terminated with a '/', which can only be
|
|
|
|
// escaped using '\' or a character class between '[' and ']'.
|
|
|
|
// See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
|
|
|
|
switch (*Offset) {
|
|
|
|
case '\\':
|
|
|
|
// Skip the escaped character.
|
|
|
|
++Offset;
|
|
|
|
break;
|
|
|
|
case '[':
|
2015-10-12 11:13:48 +08:00
|
|
|
InCharacterClass = true;
|
2015-10-18 15:02:28 +08:00
|
|
|
break;
|
|
|
|
case ']':
|
2015-10-12 11:13:48 +08:00
|
|
|
InCharacterClass = false;
|
2015-10-18 15:02:28 +08:00
|
|
|
break;
|
|
|
|
case '/':
|
|
|
|
if (!InCharacterClass)
|
|
|
|
HaveClosingSlash = true;
|
|
|
|
break;
|
2015-10-12 11:13:48 +08:00
|
|
|
}
|
2014-05-09 21:11:16 +08:00
|
|
|
}
|
2015-10-18 15:02:28 +08:00
|
|
|
|
|
|
|
RegexToken->Type = TT_RegexLiteral;
|
|
|
|
// Treat regex literals like other string_literals.
|
|
|
|
RegexToken->Tok.setKind(tok::string_literal);
|
|
|
|
RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
|
|
|
|
RegexToken->ColumnWidth = RegexToken->TokenText.size();
|
|
|
|
|
|
|
|
resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
|
2014-05-08 15:01:45 +08:00
|
|
|
}
|
|
|
|
|
2016-05-17 14:29:33 +08:00
|
|
|
void tryParseTemplateString() {
|
|
|
|
FormatToken *BacktickToken = Tokens.back();
|
|
|
|
if (!BacktickToken->is(tok::unknown) || BacktickToken->TokenText != "`")
|
|
|
|
return;
|
2015-02-20 21:47:38 +08:00
|
|
|
|
2016-05-17 14:29:33 +08:00
|
|
|
// 'Manually' lex ahead in the current file buffer.
|
|
|
|
const char *Offset = Lex->getBufferLocation();
|
|
|
|
const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`"
|
|
|
|
for (; Offset != Lex->getBuffer().end() && *Offset != '`'; ++Offset) {
|
|
|
|
if (*Offset == '\\')
|
|
|
|
++Offset; // Skip the escaped character.
|
|
|
|
}
|
2015-02-20 21:47:38 +08:00
|
|
|
|
2016-05-17 14:29:33 +08:00
|
|
|
StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1);
|
|
|
|
BacktickToken->Type = TT_TemplateString;
|
|
|
|
BacktickToken->Tok.setKind(tok::string_literal);
|
|
|
|
BacktickToken->TokenText = LiteralText;
|
|
|
|
|
|
|
|
// Adjust width for potentially multiline string literals.
|
|
|
|
size_t FirstBreak = LiteralText.find('\n');
|
|
|
|
StringRef FirstLineText = FirstBreak == StringRef::npos
|
|
|
|
? LiteralText
|
|
|
|
: LiteralText.substr(0, FirstBreak);
|
|
|
|
BacktickToken->ColumnWidth = encoding::columnWidthWithTabs(
|
|
|
|
FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
|
|
|
|
size_t LastBreak = LiteralText.rfind('\n');
|
|
|
|
if (LastBreak != StringRef::npos) {
|
|
|
|
BacktickToken->IsMultiline = true;
|
|
|
|
unsigned StartColumn = 0; // The template tail spans the entire line.
|
|
|
|
BacktickToken->LastLineColumnWidth = encoding::columnWidthWithTabs(
|
|
|
|
LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn,
|
|
|
|
Style.TabWidth, Encoding);
|
2015-02-20 21:47:38 +08:00
|
|
|
}
|
2016-05-17 14:29:33 +08:00
|
|
|
|
|
|
|
resetLexer(
|
|
|
|
SourceMgr.getFileOffset(Lex->getSourceLocation(Offset + 1)));
|
2015-02-20 21:47:38 +08:00
|
|
|
}
|
|
|
|
|
2013-11-21 20:43:57 +08:00
|
|
|
bool tryMerge_TMacro() {
|
2013-09-17 04:20:49 +08:00
|
|
|
if (Tokens.size() < 4)
|
2013-11-21 20:43:57 +08:00
|
|
|
return false;
|
2013-09-17 04:20:49 +08:00
|
|
|
FormatToken *Last = Tokens.back();
|
|
|
|
if (!Last->is(tok::r_paren))
|
2013-11-21 20:43:57 +08:00
|
|
|
return false;
|
2013-09-17 04:20:49 +08:00
|
|
|
|
|
|
|
FormatToken *String = Tokens[Tokens.size() - 2];
|
|
|
|
if (!String->is(tok::string_literal) || String->IsMultiline)
|
2013-11-21 20:43:57 +08:00
|
|
|
return false;
|
2013-09-17 04:20:49 +08:00
|
|
|
|
|
|
|
if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
|
2013-11-21 20:43:57 +08:00
|
|
|
return false;
|
2013-09-17 04:20:49 +08:00
|
|
|
|
|
|
|
FormatToken *Macro = Tokens[Tokens.size() - 4];
|
|
|
|
if (Macro->TokenText != "_T")
|
2013-11-21 20:43:57 +08:00
|
|
|
return false;
|
2013-09-17 04:20:49 +08:00
|
|
|
|
|
|
|
const char *Start = Macro->TokenText.data();
|
|
|
|
const char *End = Last->TokenText.data() + Last->TokenText.size();
|
|
|
|
String->TokenText = StringRef(Start, End - Start);
|
|
|
|
String->IsFirst = Macro->IsFirst;
|
|
|
|
String->LastNewlineOffset = Macro->LastNewlineOffset;
|
|
|
|
String->WhitespaceRange = Macro->WhitespaceRange;
|
|
|
|
String->OriginalColumn = Macro->OriginalColumn;
|
|
|
|
String->ColumnWidth = encoding::columnWidthWithTabs(
|
|
|
|
String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
|
2015-03-26 22:47:35 +08:00
|
|
|
String->NewlinesBefore = Macro->NewlinesBefore;
|
|
|
|
String->HasUnescapedNewline = Macro->HasUnescapedNewline;
|
2013-09-17 04:20:49 +08:00
|
|
|
|
|
|
|
Tokens.pop_back();
|
|
|
|
Tokens.pop_back();
|
|
|
|
Tokens.pop_back();
|
|
|
|
Tokens.back() = String;
|
2013-11-21 20:43:57 +08:00
|
|
|
return true;
|
2013-09-17 04:20:49 +08:00
|
|
|
}
|
|
|
|
|
2014-04-14 17:14:11 +08:00
|
|
|
bool tryMergeConflictMarkers() {
|
|
|
|
if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Conflict lines look like:
|
|
|
|
// <marker> <text from the vcs>
|
|
|
|
// For example:
|
|
|
|
// >>>>>>> /file/in/file/system at revision 1234
|
|
|
|
//
|
|
|
|
// We merge all tokens in a line that starts with a conflict marker
|
|
|
|
// into a single token with a special token type that the unwrapped line
|
|
|
|
// parser will use to correctly rebuild the underlying code.
|
|
|
|
|
|
|
|
FileID ID;
|
|
|
|
// Get the position of the first token in the line.
|
|
|
|
unsigned FirstInLineOffset;
|
|
|
|
std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
|
|
|
|
Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
|
|
|
|
StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
|
|
|
|
// Calculate the offset of the start of the current line.
|
|
|
|
auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
|
|
|
|
if (LineOffset == StringRef::npos) {
|
|
|
|
LineOffset = 0;
|
|
|
|
} else {
|
|
|
|
++LineOffset;
|
|
|
|
}
|
|
|
|
|
|
|
|
auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
|
|
|
|
StringRef LineStart;
|
|
|
|
if (FirstSpace == StringRef::npos) {
|
|
|
|
LineStart = Buffer.substr(LineOffset);
|
|
|
|
} else {
|
|
|
|
LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
|
|
|
|
}
|
|
|
|
|
|
|
|
TokenType Type = TT_Unknown;
|
|
|
|
if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
|
|
|
|
Type = TT_ConflictStart;
|
|
|
|
} else if (LineStart == "|||||||" || LineStart == "=======" ||
|
|
|
|
LineStart == "====") {
|
|
|
|
Type = TT_ConflictAlternative;
|
|
|
|
} else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
|
|
|
|
Type = TT_ConflictEnd;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Type != TT_Unknown) {
|
|
|
|
FormatToken *Next = Tokens.back();
|
|
|
|
|
|
|
|
Tokens.resize(FirstInLineIndex + 1);
|
|
|
|
// We do not need to build a complete token here, as we will skip it
|
|
|
|
// during parsing anyway (as we must not touch whitespace around conflict
|
|
|
|
// markers).
|
|
|
|
Tokens.back()->Type = Type;
|
|
|
|
Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
|
|
|
|
|
|
|
|
Tokens.push_back(Next);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2015-02-19 07:48:37 +08:00
|
|
|
FormatToken *getStashedToken() {
|
|
|
|
// Create a synthesized second '>' or '<' token.
|
|
|
|
Token Tok = FormatTok->Tok;
|
|
|
|
StringRef TokenText = FormatTok->TokenText;
|
|
|
|
|
|
|
|
unsigned OriginalColumn = FormatTok->OriginalColumn;
|
|
|
|
FormatTok = new (Allocator.Allocate()) FormatToken;
|
|
|
|
FormatTok->Tok = Tok;
|
|
|
|
SourceLocation TokLocation =
|
2015-02-25 07:23:24 +08:00
|
|
|
FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
|
|
|
|
FormatTok->Tok.setLocation(TokLocation);
|
2015-02-19 07:48:37 +08:00
|
|
|
FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
|
|
|
|
FormatTok->TokenText = TokenText;
|
|
|
|
FormatTok->ColumnWidth = 1;
|
2015-02-25 07:23:24 +08:00
|
|
|
FormatTok->OriginalColumn = OriginalColumn + 1;
|
|
|
|
|
2015-02-19 07:48:37 +08:00
|
|
|
return FormatTok;
|
|
|
|
}
|
|
|
|
|
2013-05-28 19:55:06 +08:00
|
|
|
FormatToken *getNextToken() {
|
2012-12-08 00:15:44 +08:00
|
|
|
if (GreaterStashed) {
|
|
|
|
GreaterStashed = false;
|
2015-02-19 07:48:37 +08:00
|
|
|
return getStashedToken();
|
|
|
|
}
|
|
|
|
if (LessStashed) {
|
|
|
|
LessStashed = false;
|
|
|
|
return getStashedToken();
|
2012-12-08 00:15:44 +08:00
|
|
|
}
|
|
|
|
|
2013-05-28 19:55:06 +08:00
|
|
|
FormatTok = new (Allocator.Allocate()) FormatToken;
|
2013-07-17 04:28:33 +08:00
|
|
|
readRawToken(*FormatTok);
|
2013-05-27 23:23:34 +08:00
|
|
|
SourceLocation WhitespaceStart =
|
2013-05-28 19:55:06 +08:00
|
|
|
FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
|
2013-11-13 22:04:17 +08:00
|
|
|
FormatTok->IsFirst = IsFirstToken;
|
|
|
|
IsFirstToken = false;
|
2012-12-08 00:15:44 +08:00
|
|
|
|
|
|
|
// Consume and record whitespace until we find a significant token.
|
2013-05-27 23:23:34 +08:00
|
|
|
unsigned WhitespaceLength = TrailingWhitespace;
|
2013-05-28 19:55:06 +08:00
|
|
|
while (FormatTok->Tok.is(tok::unknown)) {
|
2015-05-06 19:16:43 +08:00
|
|
|
StringRef Text = FormatTok->TokenText;
|
|
|
|
auto EscapesNewline = [&](int pos) {
|
|
|
|
// A '\r' here is just part of '\r\n'. Skip it.
|
|
|
|
if (pos >= 0 && Text[pos] == '\r')
|
|
|
|
--pos;
|
|
|
|
// See whether there is an odd number of '\' before this.
|
|
|
|
unsigned count = 0;
|
|
|
|
for (; pos >= 0; --pos, ++count)
|
2015-05-10 16:00:25 +08:00
|
|
|
if (Text[pos] != '\\')
|
2015-05-06 19:16:43 +08:00
|
|
|
break;
|
|
|
|
return count & 1;
|
|
|
|
};
|
2015-02-20 21:47:38 +08:00
|
|
|
// FIXME: This miscounts tok:unknown tokens that are not just
|
|
|
|
// whitespace, e.g. a '`' character.
|
2015-05-06 19:16:43 +08:00
|
|
|
for (int i = 0, e = Text.size(); i != e; ++i) {
|
|
|
|
switch (Text[i]) {
|
2013-08-29 23:21:40 +08:00
|
|
|
case '\n':
|
|
|
|
++FormatTok->NewlinesBefore;
|
2015-05-06 19:16:43 +08:00
|
|
|
FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
|
2013-08-29 23:21:40 +08:00
|
|
|
FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
|
|
|
|
Column = 0;
|
|
|
|
break;
|
2013-10-12 03:45:02 +08:00
|
|
|
case '\r':
|
2015-02-05 19:05:31 +08:00
|
|
|
FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
|
|
|
|
Column = 0;
|
|
|
|
break;
|
2013-10-12 03:45:02 +08:00
|
|
|
case '\f':
|
|
|
|
case '\v':
|
|
|
|
Column = 0;
|
|
|
|
break;
|
2013-08-29 23:21:40 +08:00
|
|
|
case ' ':
|
|
|
|
++Column;
|
|
|
|
break;
|
|
|
|
case '\t':
|
2013-09-05 22:08:34 +08:00
|
|
|
Column += Style.TabWidth - Column % Style.TabWidth;
|
2013-08-29 23:21:40 +08:00
|
|
|
break;
|
2013-10-12 03:45:02 +08:00
|
|
|
case '\\':
|
2015-05-06 19:16:43 +08:00
|
|
|
if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
|
2013-10-12 03:45:02 +08:00
|
|
|
FormatTok->Type = TT_ImplicitStringLiteral;
|
|
|
|
break;
|
2013-08-29 23:21:40 +08:00
|
|
|
default:
|
2013-10-12 03:45:02 +08:00
|
|
|
FormatTok->Type = TT_ImplicitStringLiteral;
|
2013-08-29 23:21:40 +08:00
|
|
|
break;
|
|
|
|
}
|
2016-01-10 05:12:45 +08:00
|
|
|
if (FormatTok->Type == TT_ImplicitStringLiteral)
|
|
|
|
break;
|
2013-08-29 23:21:40 +08:00
|
|
|
}
|
|
|
|
|
2014-11-25 18:05:17 +08:00
|
|
|
if (FormatTok->is(TT_ImplicitStringLiteral))
|
2013-10-12 03:45:02 +08:00
|
|
|
break;
|
2013-05-28 19:55:06 +08:00
|
|
|
WhitespaceLength += FormatTok->Tok.getLength();
|
2012-12-08 00:15:44 +08:00
|
|
|
|
2013-07-17 04:28:33 +08:00
|
|
|
readRawToken(*FormatTok);
|
2013-01-05 07:34:14 +08:00
|
|
|
}
|
2013-01-07 15:56:50 +08:00
|
|
|
|
2013-01-05 07:34:14 +08:00
|
|
|
// In case the token starts with escaped newlines, we want to
|
|
|
|
// take them into account as whitespace - this pattern is quite frequent
|
|
|
|
// in macro definitions.
|
|
|
|
// FIXME: Add a more explicit test.
|
2013-07-17 04:28:33 +08:00
|
|
|
while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\' &&
|
|
|
|
FormatTok->TokenText[1] == '\n') {
|
2014-04-11 20:27:47 +08:00
|
|
|
++FormatTok->NewlinesBefore;
|
2013-05-23 18:56:37 +08:00
|
|
|
WhitespaceLength += 2;
|
2015-05-06 19:16:43 +08:00
|
|
|
FormatTok->LastNewlineOffset = 2;
|
2013-08-29 23:21:40 +08:00
|
|
|
Column = 0;
|
2013-07-17 04:28:33 +08:00
|
|
|
FormatTok->TokenText = FormatTok->TokenText.substr(2);
|
2012-12-08 00:15:44 +08:00
|
|
|
}
|
2013-09-10 17:38:25 +08:00
|
|
|
|
|
|
|
FormatTok->WhitespaceRange = SourceRange(
|
|
|
|
WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
|
|
|
|
|
2013-08-29 23:21:40 +08:00
|
|
|
FormatTok->OriginalColumn = Column;
|
2012-12-08 00:15:44 +08:00
|
|
|
|
2013-06-08 01:45:07 +08:00
|
|
|
TrailingWhitespace = 0;
|
|
|
|
if (FormatTok->Tok.is(tok::comment)) {
|
2013-08-29 23:21:40 +08:00
|
|
|
// FIXME: Add the trimmed whitespace to Column.
|
2013-07-17 04:28:33 +08:00
|
|
|
StringRef UntrimmedText = FormatTok->TokenText;
|
2013-09-07 01:24:54 +08:00
|
|
|
FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
|
2013-07-17 04:28:33 +08:00
|
|
|
TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
|
2013-06-08 01:45:07 +08:00
|
|
|
} else if (FormatTok->Tok.is(tok::raw_identifier)) {
|
2013-07-17 04:28:33 +08:00
|
|
|
IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
|
2013-05-28 19:55:06 +08:00
|
|
|
FormatTok->Tok.setIdentifierInfo(&Info);
|
|
|
|
FormatTok->Tok.setKind(Info.getTokenID());
|
2014-11-19 22:11:11 +08:00
|
|
|
if (Style.Language == FormatStyle::LK_Java &&
|
2015-12-22 23:47:56 +08:00
|
|
|
FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
|
|
|
|
tok::kw_operator)) {
|
2014-11-19 22:11:11 +08:00
|
|
|
FormatTok->Tok.setKind(tok::identifier);
|
|
|
|
FormatTok->Tok.setIdentifierInfo(nullptr);
|
2015-11-20 23:58:50 +08:00
|
|
|
} else if (Style.Language == FormatStyle::LK_JavaScript &&
|
2015-12-22 23:47:56 +08:00
|
|
|
FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
|
|
|
|
tok::kw_operator)) {
|
2015-11-20 23:58:50 +08:00
|
|
|
FormatTok->Tok.setKind(tok::identifier);
|
|
|
|
FormatTok->Tok.setIdentifierInfo(nullptr);
|
2014-11-19 22:11:11 +08:00
|
|
|
}
|
2013-06-08 01:45:07 +08:00
|
|
|
} else if (FormatTok->Tok.is(tok::greatergreater)) {
|
2013-05-28 19:55:06 +08:00
|
|
|
FormatTok->Tok.setKind(tok::greater);
|
2013-07-17 04:28:33 +08:00
|
|
|
FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
|
2012-12-08 00:15:44 +08:00
|
|
|
GreaterStashed = true;
|
2015-02-19 07:48:37 +08:00
|
|
|
} else if (FormatTok->Tok.is(tok::lessless)) {
|
|
|
|
FormatTok->Tok.setKind(tok::less);
|
|
|
|
FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
|
|
|
|
LessStashed = true;
|
2012-12-08 00:15:44 +08:00
|
|
|
}
|
|
|
|
|
2013-06-08 01:45:07 +08:00
|
|
|
// Now FormatTok is the next non-whitespace token.
|
2013-09-10 17:38:25 +08:00
|
|
|
|
|
|
|
StringRef Text = FormatTok->TokenText;
|
|
|
|
size_t FirstNewlinePos = Text.find('\n');
|
2013-09-10 20:29:48 +08:00
|
|
|
if (FirstNewlinePos == StringRef::npos) {
|
|
|
|
// FIXME: ColumnWidth actually depends on the start column, we need to
|
|
|
|
// take this into account when the token is moved.
|
|
|
|
FormatTok->ColumnWidth =
|
|
|
|
encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
|
|
|
|
Column += FormatTok->ColumnWidth;
|
|
|
|
} else {
|
2013-09-10 17:38:25 +08:00
|
|
|
FormatTok->IsMultiline = true;
|
2013-09-10 20:29:48 +08:00
|
|
|
// FIXME: ColumnWidth actually depends on the start column, we need to
|
|
|
|
// take this into account when the token is moved.
|
|
|
|
FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
|
|
|
|
Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
|
|
|
|
|
2013-09-10 17:38:25 +08:00
|
|
|
// The last line of the token always starts in column 0.
|
|
|
|
// Thus, the length can be precomputed even in the presence of tabs.
|
|
|
|
FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
|
|
|
|
Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth,
|
|
|
|
Encoding);
|
2013-09-10 20:29:48 +08:00
|
|
|
Column = FormatTok->LastLineColumnWidth;
|
2013-09-02 21:58:14 +08:00
|
|
|
}
|
2013-09-10 17:38:25 +08:00
|
|
|
|
2015-07-04 01:25:16 +08:00
|
|
|
if (Style.Language == FormatStyle::LK_Cpp) {
|
|
|
|
if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
|
|
|
|
Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
|
|
|
|
tok::pp_define) &&
|
|
|
|
std::find(ForEachMacros.begin(), ForEachMacros.end(),
|
2016-04-25 23:09:22 +08:00
|
|
|
FormatTok->Tok.getIdentifierInfo()) !=
|
|
|
|
ForEachMacros.end()) {
|
2015-07-04 01:25:16 +08:00
|
|
|
FormatTok->Type = TT_ForEachMacro;
|
|
|
|
} else if (FormatTok->is(tok::identifier)) {
|
|
|
|
if (MacroBlockBeginRegex.match(Text)) {
|
|
|
|
FormatTok->Type = TT_MacroBlockBegin;
|
|
|
|
} else if (MacroBlockEndRegex.match(Text)) {
|
|
|
|
FormatTok->Type = TT_MacroBlockEnd;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2014-04-01 20:55:11 +08:00
|
|
|
|
2012-12-08 00:15:44 +08:00
|
|
|
return FormatTok;
|
|
|
|
}
|
|
|
|
|
2013-05-28 19:55:06 +08:00
|
|
|
FormatToken *FormatTok;
|
2013-11-13 22:04:17 +08:00
|
|
|
bool IsFirstToken;
|
2015-02-19 07:48:37 +08:00
|
|
|
bool GreaterStashed, LessStashed;
|
2013-08-29 23:21:40 +08:00
|
|
|
unsigned Column;
|
2013-05-27 23:23:34 +08:00
|
|
|
unsigned TrailingWhitespace;
|
2014-09-09 22:37:39 +08:00
|
|
|
std::unique_ptr<Lexer> Lex;
|
2016-04-28 15:52:03 +08:00
|
|
|
const SourceManager &SourceMgr;
|
2014-09-09 22:37:39 +08:00
|
|
|
FileID ID;
|
2016-04-25 23:09:22 +08:00
|
|
|
const FormatStyle &Style;
|
2012-12-08 00:15:44 +08:00
|
|
|
IdentifierTable IdentTable;
|
2014-11-04 20:41:02 +08:00
|
|
|
AdditionalKeywords Keywords;
|
2013-06-05 22:09:10 +08:00
|
|
|
encoding::Encoding Encoding;
|
2013-05-28 19:55:06 +08:00
|
|
|
llvm::SpecificBumpPtrAllocator<FormatToken> Allocator;
|
2014-04-14 17:14:11 +08:00
|
|
|
// Index (in 'Tokens') of the last token that starts a new line.
|
|
|
|
unsigned FirstInLineIndex;
|
2013-05-28 19:55:06 +08:00
|
|
|
SmallVector<FormatToken *, 16> Tokens;
|
2014-05-09 21:11:16 +08:00
|
|
|
SmallVector<IdentifierInfo *, 8> ForEachMacros;
|
2012-12-08 00:15:44 +08:00
|
|
|
|
2014-08-07 00:53:13 +08:00
|
|
|
bool FormattingDisabled;
|
2014-08-06 21:40:26 +08:00
|
|
|
|
2015-07-04 01:25:16 +08:00
|
|
|
llvm::Regex MacroBlockBeginRegex;
|
|
|
|
llvm::Regex MacroBlockEndRegex;
|
|
|
|
|
2013-07-17 04:28:33 +08:00
|
|
|
void readRawToken(FormatToken &Tok) {
|
2014-09-09 22:37:39 +08:00
|
|
|
Lex->LexFromRawLexer(Tok.Tok);
|
2013-07-17 04:28:33 +08:00
|
|
|
Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
|
|
|
|
Tok.Tok.getLength());
|
|
|
|
// For formatting, treat unterminated string literals like normal string
|
|
|
|
// literals.
|
2014-01-31 20:49:42 +08:00
|
|
|
if (Tok.is(tok::unknown)) {
|
|
|
|
if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
|
|
|
|
Tok.Tok.setKind(tok::string_literal);
|
|
|
|
Tok.IsUnterminatedLiteral = true;
|
|
|
|
} else if (Style.Language == FormatStyle::LK_JavaScript &&
|
|
|
|
Tok.TokenText == "''") {
|
2016-03-03 06:44:03 +08:00
|
|
|
Tok.Tok.setKind(tok::string_literal);
|
2014-01-31 20:49:42 +08:00
|
|
|
}
|
2013-07-17 04:28:33 +08:00
|
|
|
}
|
2014-09-11 22:47:20 +08:00
|
|
|
|
2016-03-03 06:44:03 +08:00
|
|
|
if (Style.Language == FormatStyle::LK_JavaScript &&
|
|
|
|
Tok.is(tok::char_constant)) {
|
|
|
|
Tok.Tok.setKind(tok::string_literal);
|
|
|
|
}
|
|
|
|
|
2014-09-11 22:47:20 +08:00
|
|
|
if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
|
|
|
|
Tok.TokenText == "/* clang-format on */")) {
|
2014-08-06 21:40:26 +08:00
|
|
|
FormattingDisabled = false;
|
2014-09-11 22:47:20 +08:00
|
|
|
}
|
|
|
|
|
2014-08-06 21:40:26 +08:00
|
|
|
Tok.Finalized = FormattingDisabled;
|
2014-09-11 22:47:20 +08:00
|
|
|
|
|
|
|
if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
|
|
|
|
Tok.TokenText == "/* clang-format off */")) {
|
2014-08-06 21:40:26 +08:00
|
|
|
FormattingDisabled = true;
|
2014-09-11 22:47:20 +08:00
|
|
|
}
|
2012-12-08 00:15:44 +08:00
|
|
|
}
|
2014-10-30 00:51:38 +08:00
|
|
|
|
|
|
|
void resetLexer(unsigned Offset) {
|
|
|
|
StringRef Buffer = SourceMgr.getBufferData(ID);
|
|
|
|
Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
|
|
|
|
getFormattingLangOpts(Style), Buffer.begin(),
|
|
|
|
Buffer.begin() + Offset, Buffer.end()));
|
|
|
|
Lex->SetKeepWhitespaceMode(true);
|
2015-07-02 22:01:34 +08:00
|
|
|
TrailingWhitespace = 0;
|
2014-10-30 00:51:38 +08:00
|
|
|
}
|
2012-12-08 00:15:44 +08:00
|
|
|
};
|
|
|
|
|
2013-11-29 23:19:43 +08:00
|
|
|
static StringRef getLanguageName(FormatStyle::LanguageKind Language) {
|
|
|
|
switch (Language) {
|
|
|
|
case FormatStyle::LK_Cpp:
|
|
|
|
return "C++";
|
2014-09-15 19:21:46 +08:00
|
|
|
case FormatStyle::LK_Java:
|
|
|
|
return "Java";
|
2013-11-29 23:19:43 +08:00
|
|
|
case FormatStyle::LK_JavaScript:
|
|
|
|
return "JavaScript";
|
2014-01-19 17:04:08 +08:00
|
|
|
case FormatStyle::LK_Proto:
|
|
|
|
return "Proto";
|
2013-11-29 23:19:43 +08:00
|
|
|
default:
|
|
|
|
return "Unknown";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
class Environment {
|
2012-12-04 02:12:45 +08:00
|
|
|
public:
|
2016-04-28 15:52:03 +08:00
|
|
|
Environment(SourceManager &SM, FileID ID, ArrayRef<CharSourceRange> Ranges)
|
|
|
|
: ID(ID), CharRanges(Ranges.begin(), Ranges.end()), SM(SM) {}
|
2016-04-25 23:09:22 +08:00
|
|
|
|
2016-04-28 15:52:03 +08:00
|
|
|
Environment(FileID ID, std::unique_ptr<FileManager> FileMgr,
|
2016-04-25 23:09:22 +08:00
|
|
|
std::unique_ptr<SourceManager> VirtualSM,
|
|
|
|
std::unique_ptr<DiagnosticsEngine> Diagnostics,
|
2016-04-28 15:51:47 +08:00
|
|
|
const std::vector<CharSourceRange> &CharRanges)
|
2016-04-28 15:52:03 +08:00
|
|
|
: ID(ID), CharRanges(CharRanges.begin(), CharRanges.end()),
|
2016-04-25 23:09:22 +08:00
|
|
|
SM(*VirtualSM), FileMgr(std::move(FileMgr)),
|
|
|
|
VirtualSM(std::move(VirtualSM)), Diagnostics(std::move(Diagnostics)) {}
|
|
|
|
|
|
|
|
// This sets up an virtual file system with file \p FileName containing \p
|
|
|
|
// Code.
|
|
|
|
static std::unique_ptr<Environment>
|
2016-04-28 15:52:03 +08:00
|
|
|
CreateVirtualEnvironment(StringRef Code, StringRef FileName,
|
2016-04-25 23:09:22 +08:00
|
|
|
ArrayRef<tooling::Range> Ranges) {
|
|
|
|
// This is referenced by `FileMgr` and will be released by `FileMgr` when it
|
|
|
|
// is deleted.
|
|
|
|
IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
|
|
|
|
new vfs::InMemoryFileSystem);
|
|
|
|
// This is passed to `SM` as reference, so the pointer has to be referenced
|
|
|
|
// in `Environment` so that `FileMgr` can out-live this function scope.
|
|
|
|
std::unique_ptr<FileManager> FileMgr(
|
|
|
|
new FileManager(FileSystemOptions(), InMemoryFileSystem));
|
|
|
|
// This is passed to `SM` as reference, so the pointer has to be referenced
|
|
|
|
// by `Environment` due to the same reason above.
|
|
|
|
std::unique_ptr<DiagnosticsEngine> Diagnostics(new DiagnosticsEngine(
|
|
|
|
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
|
|
|
|
new DiagnosticOptions));
|
|
|
|
// This will be stored as reference, so the pointer has to be stored in
|
|
|
|
// due to the same reason above.
|
|
|
|
std::unique_ptr<SourceManager> VirtualSM(
|
|
|
|
new SourceManager(*Diagnostics, *FileMgr));
|
|
|
|
InMemoryFileSystem->addFile(
|
|
|
|
FileName, 0, llvm::MemoryBuffer::getMemBuffer(
|
|
|
|
Code, FileName, /*RequiresNullTerminator=*/false));
|
|
|
|
FileID ID = VirtualSM->createFileID(
|
|
|
|
FileMgr->getFile(FileName), SourceLocation(), clang::SrcMgr::C_User);
|
|
|
|
assert(ID.isValid());
|
|
|
|
SourceLocation StartOfFile = VirtualSM->getLocForStartOfFile(ID);
|
|
|
|
std::vector<CharSourceRange> CharRanges;
|
|
|
|
for (const tooling::Range &Range : Ranges) {
|
|
|
|
SourceLocation Start = StartOfFile.getLocWithOffset(Range.getOffset());
|
|
|
|
SourceLocation End = Start.getLocWithOffset(Range.getLength());
|
|
|
|
CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
|
|
|
|
}
|
2016-04-28 15:52:03 +08:00
|
|
|
return llvm::make_unique<Environment>(ID, std::move(FileMgr),
|
2016-04-25 23:09:22 +08:00
|
|
|
std::move(VirtualSM),
|
|
|
|
std::move(Diagnostics), CharRanges);
|
|
|
|
}
|
|
|
|
|
|
|
|
FileID getFileID() const { return ID; }
|
|
|
|
|
|
|
|
StringRef getFileName() const { return FileName; }
|
|
|
|
|
|
|
|
ArrayRef<CharSourceRange> getCharRanges() const { return CharRanges; }
|
|
|
|
|
2016-04-28 15:52:03 +08:00
|
|
|
const SourceManager &getSourceManager() const { return SM; }
|
2016-04-25 23:09:22 +08:00
|
|
|
|
|
|
|
private:
|
|
|
|
FileID ID;
|
|
|
|
StringRef FileName;
|
|
|
|
SmallVector<CharSourceRange, 8> CharRanges;
|
|
|
|
SourceManager &SM;
|
|
|
|
|
|
|
|
// The order of these fields are important - they should be in the same order
|
|
|
|
// as they are created in `CreateVirtualEnvironment` so that they can be
|
|
|
|
// deleted in the reverse order as they are created.
|
|
|
|
std::unique_ptr<FileManager> FileMgr;
|
|
|
|
std::unique_ptr<SourceManager> VirtualSM;
|
|
|
|
std::unique_ptr<DiagnosticsEngine> Diagnostics;
|
|
|
|
};
|
|
|
|
|
|
|
|
class TokenAnalyzer : public UnwrappedLineConsumer {
|
|
|
|
public:
|
2016-04-28 15:52:03 +08:00
|
|
|
TokenAnalyzer(const Environment &Env, const FormatStyle &Style)
|
|
|
|
: Style(Style), Env(Env),
|
|
|
|
AffectedRangeMgr(Env.getSourceManager(), Env.getCharRanges()),
|
2016-04-25 23:09:22 +08:00
|
|
|
UnwrappedLines(1),
|
|
|
|
Encoding(encoding::detectEncoding(
|
|
|
|
Env.getSourceManager().getBufferData(Env.getFileID()))) {
|
2013-07-15 22:33:14 +08:00
|
|
|
DEBUG(llvm::dbgs() << "File encoding: "
|
|
|
|
<< (Encoding == encoding::Encoding_UTF8 ? "UTF8"
|
|
|
|
: "unknown")
|
|
|
|
<< "\n");
|
2016-04-28 15:52:03 +08:00
|
|
|
DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
|
2013-11-29 23:19:43 +08:00
|
|
|
<< "\n");
|
2013-06-05 22:09:10 +08:00
|
|
|
}
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
tooling::Replacements process() {
|
2013-10-12 05:25:45 +08:00
|
|
|
tooling::Replacements Result;
|
2016-04-28 15:52:03 +08:00
|
|
|
FormatTokenLexer Tokens(Env.getSourceManager(), Env.getFileID(), Style,
|
|
|
|
Encoding);
|
2013-05-28 19:55:06 +08:00
|
|
|
|
2016-04-28 15:52:03 +08:00
|
|
|
UnwrappedLineParser Parser(Style, Tokens.getKeywords(), Tokens.lex(),
|
|
|
|
*this);
|
2015-05-06 19:56:29 +08:00
|
|
|
Parser.parse();
|
2013-10-12 05:25:45 +08:00
|
|
|
assert(UnwrappedLines.rbegin()->empty());
|
|
|
|
for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE;
|
|
|
|
++Run) {
|
|
|
|
DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
|
|
|
|
SmallVector<AnnotatedLine *, 16> AnnotatedLines;
|
2016-04-25 23:09:22 +08:00
|
|
|
|
2016-04-28 15:52:03 +08:00
|
|
|
TokenAnnotator Annotator(Style, Tokens.getKeywords());
|
2013-10-12 05:25:45 +08:00
|
|
|
for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
|
|
|
|
AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
|
2016-04-25 23:09:22 +08:00
|
|
|
Annotator.annotate(*AnnotatedLines.back());
|
2013-10-12 05:25:45 +08:00
|
|
|
}
|
2016-04-25 23:09:22 +08:00
|
|
|
|
2015-05-07 20:26:30 +08:00
|
|
|
tooling::Replacements RunResult =
|
2016-04-25 23:09:22 +08:00
|
|
|
analyze(Annotator, AnnotatedLines, Tokens, Result);
|
|
|
|
|
2013-10-12 05:25:45 +08:00
|
|
|
DEBUG({
|
|
|
|
llvm::dbgs() << "Replacements for run " << Run << ":\n";
|
|
|
|
for (tooling::Replacements::iterator I = RunResult.begin(),
|
|
|
|
E = RunResult.end();
|
|
|
|
I != E; ++I) {
|
|
|
|
llvm::dbgs() << I->toString() << "\n";
|
|
|
|
}
|
|
|
|
});
|
|
|
|
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
|
|
|
|
delete AnnotatedLines[i];
|
|
|
|
}
|
|
|
|
Result.insert(RunResult.begin(), RunResult.end());
|
|
|
|
}
|
|
|
|
return Result;
|
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
protected:
|
|
|
|
virtual tooling::Replacements
|
|
|
|
analyze(TokenAnnotator &Annotator,
|
|
|
|
SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
|
|
|
|
FormatTokenLexer &Tokens, tooling::Replacements &Result) = 0;
|
|
|
|
|
|
|
|
void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
|
|
|
|
assert(!UnwrappedLines.empty());
|
|
|
|
UnwrappedLines.back().push_back(TheLine);
|
|
|
|
}
|
|
|
|
|
|
|
|
void finishRun() override {
|
|
|
|
UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
|
|
|
|
}
|
|
|
|
|
2016-04-28 15:52:03 +08:00
|
|
|
FormatStyle Style;
|
2016-04-25 23:09:22 +08:00
|
|
|
// Stores Style, FileID and SourceManager etc.
|
2016-04-28 15:52:03 +08:00
|
|
|
const Environment &Env;
|
2016-04-25 23:09:22 +08:00
|
|
|
// AffectedRangeMgr stores ranges to be fixed.
|
|
|
|
AffectedRangeManager AffectedRangeMgr;
|
|
|
|
SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
|
|
|
|
encoding::Encoding Encoding;
|
|
|
|
};
|
|
|
|
|
|
|
|
class Formatter : public TokenAnalyzer {
|
|
|
|
public:
|
2016-04-28 15:52:03 +08:00
|
|
|
Formatter(const Environment &Env, const FormatStyle &Style,
|
|
|
|
bool *IncompleteFormat)
|
|
|
|
: TokenAnalyzer(Env, Style), IncompleteFormat(IncompleteFormat) {}
|
2016-04-25 23:09:22 +08:00
|
|
|
|
|
|
|
tooling::Replacements
|
|
|
|
analyze(TokenAnnotator &Annotator,
|
|
|
|
SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
|
|
|
|
FormatTokenLexer &Tokens, tooling::Replacements &Result) override {
|
2013-11-06 03:10:03 +08:00
|
|
|
deriveLocalStyle(AnnotatedLines);
|
2016-04-25 23:09:22 +08:00
|
|
|
AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
|
|
|
|
AnnotatedLines.end());
|
|
|
|
|
2016-04-28 15:52:03 +08:00
|
|
|
if (Style.Language == FormatStyle::LK_JavaScript &&
|
|
|
|
Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
|
2016-03-17 21:03:41 +08:00
|
|
|
requoteJSStringLiteral(AnnotatedLines, Result);
|
|
|
|
|
2013-11-06 03:10:03 +08:00
|
|
|
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
|
|
|
|
Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
|
2013-01-11 03:49:59 +08:00
|
|
|
}
|
2013-11-06 03:10:03 +08:00
|
|
|
|
|
|
|
Annotator.setCommentLineLevels(AnnotatedLines);
|
2016-04-25 23:09:22 +08:00
|
|
|
|
|
|
|
WhitespaceManager Whitespaces(
|
2016-04-28 15:52:03 +08:00
|
|
|
Env.getSourceManager(), Style,
|
2016-04-25 23:09:22 +08:00
|
|
|
inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID())));
|
2016-04-28 15:52:03 +08:00
|
|
|
ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
|
2016-04-25 23:09:22 +08:00
|
|
|
Env.getSourceManager(), Whitespaces, Encoding,
|
2013-11-06 03:10:03 +08:00
|
|
|
BinPackInconclusiveFunctions);
|
2016-04-28 15:52:03 +08:00
|
|
|
UnwrappedLineFormatter(&Indenter, &Whitespaces, Style, Tokens.getKeywords(),
|
|
|
|
IncompleteFormat)
|
2015-05-11 16:21:35 +08:00
|
|
|
.format(AnnotatedLines);
|
2013-01-18 16:44:07 +08:00
|
|
|
return Whitespaces.generateReplacements();
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2016-03-17 21:03:41 +08:00
|
|
|
// If the last token is a double/single-quoted string literal, generates a
|
|
|
|
// replacement with a single/double quoted string literal, re-escaping the
|
|
|
|
// contents in the process.
|
|
|
|
void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
|
2016-04-25 23:09:22 +08:00
|
|
|
tooling::Replacements &Result) {
|
2016-03-17 21:03:41 +08:00
|
|
|
for (AnnotatedLine *Line : Lines) {
|
|
|
|
requoteJSStringLiteral(Line->Children, Result);
|
|
|
|
if (!Line->Affected)
|
|
|
|
continue;
|
|
|
|
for (FormatToken *FormatTok = Line->First; FormatTok;
|
|
|
|
FormatTok = FormatTok->Next) {
|
|
|
|
StringRef Input = FormatTok->TokenText;
|
2016-05-12 19:20:32 +08:00
|
|
|
if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
|
2016-03-17 21:03:41 +08:00
|
|
|
// NB: testing for not starting with a double quote to avoid
|
|
|
|
// breaking
|
|
|
|
// `template strings`.
|
2016-04-28 15:52:03 +08:00
|
|
|
(Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
|
2016-03-17 21:03:41 +08:00
|
|
|
!Input.startswith("\"")) ||
|
2016-04-28 15:52:03 +08:00
|
|
|
(Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
|
2016-03-17 21:03:41 +08:00
|
|
|
!Input.startswith("\'")))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// Change start and end quote.
|
2016-04-28 15:52:03 +08:00
|
|
|
bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
|
2016-03-17 21:03:41 +08:00
|
|
|
SourceLocation Start = FormatTok->Tok.getLocation();
|
|
|
|
auto Replace = [&](SourceLocation Start, unsigned Length,
|
|
|
|
StringRef ReplacementText) {
|
2016-04-25 23:09:22 +08:00
|
|
|
Result.insert(tooling::Replacement(Env.getSourceManager(), Start,
|
|
|
|
Length, ReplacementText));
|
2016-03-17 21:03:41 +08:00
|
|
|
};
|
|
|
|
Replace(Start, 1, IsSingle ? "'" : "\"");
|
|
|
|
Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
|
|
|
|
IsSingle ? "'" : "\"");
|
|
|
|
|
|
|
|
// Escape internal quotes.
|
|
|
|
size_t ColumnWidth = FormatTok->TokenText.size();
|
|
|
|
bool Escaped = false;
|
|
|
|
for (size_t i = 1; i < Input.size() - 1; i++) {
|
|
|
|
switch (Input[i]) {
|
2016-04-25 23:09:22 +08:00
|
|
|
case '\\':
|
|
|
|
if (!Escaped && i + 1 < Input.size() &&
|
|
|
|
((IsSingle && Input[i + 1] == '"') ||
|
|
|
|
(!IsSingle && Input[i + 1] == '\''))) {
|
|
|
|
// Remove this \, it's escaping a " or ' that no longer needs
|
|
|
|
// escaping
|
|
|
|
ColumnWidth--;
|
|
|
|
Replace(Start.getLocWithOffset(i), 1, "");
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
Escaped = !Escaped;
|
|
|
|
break;
|
|
|
|
case '\"':
|
|
|
|
case '\'':
|
|
|
|
if (!Escaped && IsSingle == (Input[i] == '\'')) {
|
|
|
|
// Escape the quote.
|
|
|
|
Replace(Start.getLocWithOffset(i), 0, "\\");
|
|
|
|
ColumnWidth++;
|
|
|
|
}
|
|
|
|
Escaped = false;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
Escaped = false;
|
|
|
|
break;
|
2016-03-17 21:03:41 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// For formatting, count the number of non-escaped single quotes in them
|
|
|
|
// and adjust ColumnWidth to take the added escapes into account.
|
2016-04-25 23:09:22 +08:00
|
|
|
// FIXME(martinprobst): this might conflict with code breaking a long
|
|
|
|
// string literal (which clang-format doesn't do, yet). For that to
|
|
|
|
// work, this code would have to modify TokenText directly.
|
2016-03-17 21:03:41 +08:00
|
|
|
FormatTok->ColumnWidth = ColumnWidth;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-09-11 20:25:57 +08:00
|
|
|
static bool inputUsesCRLF(StringRef Text) {
|
|
|
|
return Text.count('\r') * 2 > Text.count('\n');
|
|
|
|
}
|
|
|
|
|
2015-07-19 00:35:30 +08:00
|
|
|
bool
|
|
|
|
hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
|
2016-04-25 23:09:22 +08:00
|
|
|
for (const AnnotatedLine *Line : Lines) {
|
2015-07-19 00:35:30 +08:00
|
|
|
if (hasCpp03IncompatibleFormat(Line->Children))
|
|
|
|
return true;
|
|
|
|
for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
|
|
|
|
if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
|
|
|
|
if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
|
|
|
|
return true;
|
|
|
|
if (Tok->is(TT_TemplateCloser) &&
|
|
|
|
Tok->Previous->is(TT_TemplateCloser))
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
|
|
|
|
int AlignmentDiff = 0;
|
2016-04-25 23:09:22 +08:00
|
|
|
for (const AnnotatedLine *Line : Lines) {
|
2015-07-19 00:35:30 +08:00
|
|
|
AlignmentDiff += countVariableAlignments(Line->Children);
|
|
|
|
for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
|
|
|
|
if (!Tok->is(TT_PointerOrReference))
|
|
|
|
continue;
|
|
|
|
bool SpaceBefore =
|
|
|
|
Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
|
|
|
|
bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
|
|
|
|
Tok->Next->WhitespaceRange.getEnd();
|
|
|
|
if (SpaceBefore && !SpaceAfter)
|
|
|
|
++AlignmentDiff;
|
|
|
|
if (!SpaceBefore && SpaceAfter)
|
|
|
|
--AlignmentDiff;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return AlignmentDiff;
|
|
|
|
}
|
|
|
|
|
2013-10-12 05:25:45 +08:00
|
|
|
void
|
|
|
|
deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
|
2013-07-10 22:02:49 +08:00
|
|
|
bool HasBinPackedFunction = false;
|
|
|
|
bool HasOnePerLineFunction = false;
|
2013-03-13 22:41:29 +08:00
|
|
|
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
|
2013-09-05 17:29:45 +08:00
|
|
|
if (!AnnotatedLines[i]->First->Next)
|
2013-03-13 22:41:29 +08:00
|
|
|
continue;
|
2013-09-05 17:29:45 +08:00
|
|
|
FormatToken *Tok = AnnotatedLines[i]->First->Next;
|
2013-05-29 22:47:47 +08:00
|
|
|
while (Tok->Next) {
|
2013-07-10 22:02:49 +08:00
|
|
|
if (Tok->PackingKind == PPK_BinPacked)
|
|
|
|
HasBinPackedFunction = true;
|
|
|
|
if (Tok->PackingKind == PPK_OnePerLine)
|
|
|
|
HasOnePerLineFunction = true;
|
|
|
|
|
2013-05-29 22:47:47 +08:00
|
|
|
Tok = Tok->Next;
|
2013-03-13 22:41:29 +08:00
|
|
|
}
|
|
|
|
}
|
2016-04-28 15:52:03 +08:00
|
|
|
if (Style.DerivePointerAlignment)
|
|
|
|
Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
|
|
|
|
? FormatStyle::PAS_Left
|
|
|
|
: FormatStyle::PAS_Right;
|
|
|
|
if (Style.Standard == FormatStyle::LS_Auto)
|
|
|
|
Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
|
|
|
|
? FormatStyle::LS_Cpp11
|
|
|
|
: FormatStyle::LS_Cpp03;
|
2013-07-10 22:02:49 +08:00
|
|
|
BinPackInconclusiveFunctions =
|
|
|
|
HasBinPackedFunction || !HasOnePerLineFunction;
|
2013-03-13 22:41:29 +08:00
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
bool BinPackInconclusiveFunctions;
|
|
|
|
bool *IncompleteFormat;
|
|
|
|
};
|
|
|
|
|
|
|
|
// This class clean up the erroneous/redundant code around the given ranges in
|
|
|
|
// file.
|
|
|
|
class Cleaner : public TokenAnalyzer {
|
|
|
|
public:
|
2016-04-28 15:52:03 +08:00
|
|
|
Cleaner(const Environment &Env, const FormatStyle &Style)
|
|
|
|
: TokenAnalyzer(Env, Style),
|
2016-04-25 23:09:22 +08:00
|
|
|
DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
|
|
|
|
|
|
|
|
// FIXME: eliminate unused parameters.
|
|
|
|
tooling::Replacements
|
|
|
|
analyze(TokenAnnotator &Annotator,
|
|
|
|
SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
|
|
|
|
FormatTokenLexer &Tokens, tooling::Replacements &Result) override {
|
|
|
|
// FIXME: in the current implementation the granularity of affected range
|
|
|
|
// is an annotated line. However, this is not sufficient. Furthermore,
|
|
|
|
// redundant code introduced by replacements does not necessarily
|
|
|
|
// intercept with ranges of replacements that result in the redundancy.
|
|
|
|
// To determine if some redundant code is actually introduced by
|
|
|
|
// replacements(e.g. deletions), we need to come up with a more
|
|
|
|
// sophisticated way of computing affected ranges.
|
|
|
|
AffectedRangeMgr.computeAffectedLines(AnnotatedLines.begin(),
|
|
|
|
AnnotatedLines.end());
|
|
|
|
|
|
|
|
checkEmptyNamespace(AnnotatedLines);
|
|
|
|
|
2016-05-18 16:02:56 +08:00
|
|
|
for (auto &Line : AnnotatedLines) {
|
|
|
|
if (Line->Affected) {
|
|
|
|
cleanupRight(Line->First, tok::comma, tok::comma);
|
|
|
|
cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
|
|
|
|
cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
|
|
|
|
cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
return generateFixes();
|
2013-10-12 05:25:45 +08:00
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
private:
|
|
|
|
bool containsOnlyComments(const AnnotatedLine &Line) {
|
|
|
|
for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
|
|
|
|
if (Tok->isNot(tok::comment))
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
// Iterate through all lines and remove any empty (nested) namespaces.
|
|
|
|
void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
|
|
|
|
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
|
|
|
|
auto &Line = *AnnotatedLines[i];
|
|
|
|
if (Line.startsWith(tok::kw_namespace) ||
|
|
|
|
Line.startsWith(tok::kw_inline, tok::kw_namespace)) {
|
|
|
|
checkEmptyNamespace(AnnotatedLines, i, i);
|
|
|
|
}
|
|
|
|
}
|
2013-06-05 22:09:10 +08:00
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
for (auto Line : DeletedLines) {
|
|
|
|
FormatToken *Tok = AnnotatedLines[Line]->First;
|
|
|
|
while (Tok) {
|
|
|
|
deleteToken(Tok);
|
|
|
|
Tok = Tok->Next;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// The function checks if the namespace, which starts from \p CurrentLine, and
|
|
|
|
// its nested namespaces are empty and delete them if they are empty. It also
|
|
|
|
// sets \p NewLine to the last line checked.
|
|
|
|
// Returns true if the current namespace is empty.
|
|
|
|
bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
|
|
|
|
unsigned CurrentLine, unsigned &NewLine) {
|
|
|
|
unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
|
2016-04-28 15:52:03 +08:00
|
|
|
if (Style.BraceWrapping.AfterNamespace) {
|
2016-04-25 23:09:22 +08:00
|
|
|
// If the left brace is in a new line, we should consume it first so that
|
|
|
|
// it does not make the namespace non-empty.
|
|
|
|
// FIXME: error handling if there is no left brace.
|
|
|
|
if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
|
|
|
|
NewLine = CurrentLine;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
} else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
while (++CurrentLine < End) {
|
|
|
|
if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
|
|
|
|
break;
|
|
|
|
|
|
|
|
if (AnnotatedLines[CurrentLine]->startsWith(tok::kw_namespace) ||
|
|
|
|
AnnotatedLines[CurrentLine]->startsWith(tok::kw_inline,
|
|
|
|
tok::kw_namespace)) {
|
|
|
|
if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine))
|
|
|
|
return false;
|
|
|
|
CurrentLine = NewLine;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// If there is anything other than comments or nested namespaces in the
|
|
|
|
// current namespace, the namespace cannot be empty.
|
|
|
|
NewLine = CurrentLine;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
NewLine = CurrentLine;
|
|
|
|
if (CurrentLine >= End)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Check if the empty namespace is actually affected by changed ranges.
|
|
|
|
if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
|
|
|
|
AnnotatedLines[InitLine]->First->Tok.getLocation(),
|
|
|
|
AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
for (unsigned i = InitLine; i <= CurrentLine; ++i) {
|
|
|
|
DeletedLines.insert(i);
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2016-05-18 16:02:56 +08:00
|
|
|
// Checks pairs {start, start->next},..., {end->previous, end} and deletes one
|
|
|
|
// of the token in the pair if the left token has \p LK token kind and the
|
|
|
|
// right token has \p RK token kind. If \p DeleteLeft is true, the left token
|
|
|
|
// is deleted on match; otherwise, the right token is deleted.
|
|
|
|
template <typename LeftKind, typename RightKind>
|
|
|
|
void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
|
|
|
|
bool DeleteLeft) {
|
|
|
|
auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
|
|
|
|
for (auto *Res = Tok.Next; Res; Res = Res->Next)
|
|
|
|
if (!Res->is(tok::comment) &&
|
|
|
|
DeletedTokens.find(Res) == DeletedTokens.end())
|
|
|
|
return Res;
|
|
|
|
return nullptr;
|
|
|
|
};
|
|
|
|
for (auto *Left = Start; Left;) {
|
|
|
|
auto *Right = NextNotDeleted(*Left);
|
|
|
|
if (!Right)
|
|
|
|
break;
|
|
|
|
if (Left->is(LK) && Right->is(RK)) {
|
|
|
|
deleteToken(DeleteLeft ? Left : Right);
|
|
|
|
// If the right token is deleted, we should keep the left token
|
|
|
|
// unchanged and pair it with the new right token.
|
|
|
|
if (!DeleteLeft)
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
Left = Right;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
template <typename LeftKind, typename RightKind>
|
|
|
|
void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
|
|
|
|
cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
|
|
|
|
}
|
|
|
|
|
|
|
|
template <typename LeftKind, typename RightKind>
|
|
|
|
void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
|
|
|
|
cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
|
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
// Delete the given token.
|
|
|
|
inline void deleteToken(FormatToken *Tok) {
|
|
|
|
if (Tok)
|
|
|
|
DeletedTokens.insert(Tok);
|
|
|
|
}
|
|
|
|
|
|
|
|
tooling::Replacements generateFixes() {
|
|
|
|
tooling::Replacements Fixes;
|
|
|
|
std::vector<FormatToken *> Tokens;
|
|
|
|
std::copy(DeletedTokens.begin(), DeletedTokens.end(),
|
|
|
|
std::back_inserter(Tokens));
|
|
|
|
|
|
|
|
// Merge multiple continuous token deletions into one big deletion so that
|
|
|
|
// the number of replacements can be reduced. This makes computing affected
|
|
|
|
// ranges more efficient when we run reformat on the changed code.
|
|
|
|
unsigned Idx = 0;
|
|
|
|
while (Idx < Tokens.size()) {
|
|
|
|
unsigned St = Idx, End = Idx;
|
|
|
|
while ((End + 1) < Tokens.size() &&
|
|
|
|
Tokens[End]->Next == Tokens[End + 1]) {
|
|
|
|
End++;
|
|
|
|
}
|
|
|
|
auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
|
|
|
|
Tokens[End]->Tok.getEndLoc());
|
|
|
|
Fixes.insert(tooling::Replacement(Env.getSourceManager(), SR, ""));
|
|
|
|
Idx = End + 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Fixes;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Class for less-than inequality comparason for the set `RedundantTokens`.
|
|
|
|
// We store tokens in the order they appear in the translation unit so that
|
|
|
|
// we do not need to sort them in `generateFixes()`.
|
|
|
|
struct FormatTokenLess {
|
2016-04-28 15:52:03 +08:00
|
|
|
FormatTokenLess(const SourceManager &SM) : SM(SM) {}
|
2016-04-25 23:09:22 +08:00
|
|
|
|
|
|
|
bool operator()(const FormatToken *LHS, const FormatToken *RHS) {
|
|
|
|
return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
|
|
|
|
RHS->Tok.getLocation());
|
|
|
|
}
|
2016-04-28 15:52:03 +08:00
|
|
|
const SourceManager &SM;
|
2016-04-25 23:09:22 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
// Tokens to be deleted.
|
|
|
|
std::set<FormatToken *, FormatTokenLess> DeletedTokens;
|
|
|
|
// The line numbers of lines to be deleted.
|
|
|
|
std::set<unsigned> DeletedLines;
|
2012-12-04 02:12:45 +08:00
|
|
|
};
|
|
|
|
|
2015-09-23 16:30:47 +08:00
|
|
|
struct IncludeDirective {
|
|
|
|
StringRef Filename;
|
|
|
|
StringRef Text;
|
|
|
|
unsigned Offset;
|
2015-12-16 18:10:16 +08:00
|
|
|
int Category;
|
2015-09-23 16:30:47 +08:00
|
|
|
};
|
|
|
|
|
2013-07-01 06:29:28 +08:00
|
|
|
} // end anonymous namespace
|
|
|
|
|
2015-09-23 16:30:47 +08:00
|
|
|
// Determines whether 'Ranges' intersects with ('Start', 'End').
|
|
|
|
static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
|
|
|
|
unsigned End) {
|
|
|
|
for (auto Range : Ranges) {
|
|
|
|
if (Range.getOffset() < End &&
|
|
|
|
Range.getOffset() + Range.getLength() > Start)
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sorts a block of includes given by 'Includes' alphabetically adding the
|
|
|
|
// necessary replacement to 'Replaces'. 'Includes' must be in strict source
|
|
|
|
// order.
|
|
|
|
static void sortIncludes(const FormatStyle &Style,
|
|
|
|
const SmallVectorImpl<IncludeDirective> &Includes,
|
|
|
|
ArrayRef<tooling::Range> Ranges, StringRef FileName,
|
2015-11-23 16:36:35 +08:00
|
|
|
tooling::Replacements &Replaces, unsigned *Cursor) {
|
2015-09-23 16:30:47 +08:00
|
|
|
if (!affectsRange(Ranges, Includes.front().Offset,
|
|
|
|
Includes.back().Offset + Includes.back().Text.size()))
|
|
|
|
return;
|
|
|
|
SmallVector<unsigned, 16> Indices;
|
|
|
|
for (unsigned i = 0, e = Includes.size(); i != e; ++i)
|
|
|
|
Indices.push_back(i);
|
2016-03-04 01:34:14 +08:00
|
|
|
std::stable_sort(
|
|
|
|
Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
|
|
|
|
return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
|
|
|
|
std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
|
|
|
|
});
|
2015-09-23 16:30:47 +08:00
|
|
|
|
|
|
|
// If the #includes are out of order, we generate a single replacement fixing
|
|
|
|
// the entire block. Otherwise, no replacement is generated.
|
|
|
|
bool OutOfOrder = false;
|
|
|
|
for (unsigned i = 1, e = Indices.size(); i != e; ++i) {
|
|
|
|
if (Indices[i] != i) {
|
|
|
|
OutOfOrder = true;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!OutOfOrder)
|
|
|
|
return;
|
|
|
|
|
2015-11-23 16:36:35 +08:00
|
|
|
std::string result;
|
|
|
|
bool CursorMoved = false;
|
|
|
|
for (unsigned Index : Indices) {
|
|
|
|
if (!result.empty())
|
|
|
|
result += "\n";
|
|
|
|
result += Includes[Index].Text;
|
|
|
|
|
|
|
|
if (Cursor && !CursorMoved) {
|
|
|
|
unsigned Start = Includes[Index].Offset;
|
|
|
|
unsigned End = Start + Includes[Index].Text.size();
|
|
|
|
if (*Cursor >= Start && *Cursor < End) {
|
|
|
|
*Cursor = Includes.front().Offset + result.size() + *Cursor - End;
|
|
|
|
CursorMoved = true;
|
|
|
|
}
|
|
|
|
}
|
2015-09-23 16:30:47 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// Sorting #includes shouldn't change their total number of characters.
|
|
|
|
// This would otherwise mess up 'Ranges'.
|
|
|
|
assert(result.size() ==
|
|
|
|
Includes.back().Offset + Includes.back().Text.size() -
|
|
|
|
Includes.front().Offset);
|
|
|
|
|
|
|
|
Replaces.insert(tooling::Replacement(FileName, Includes.front().Offset,
|
|
|
|
result.size(), result));
|
|
|
|
}
|
|
|
|
|
|
|
|
tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
|
|
|
|
ArrayRef<tooling::Range> Ranges,
|
2015-11-23 16:36:35 +08:00
|
|
|
StringRef FileName, unsigned *Cursor) {
|
2015-09-23 16:30:47 +08:00
|
|
|
tooling::Replacements Replaces;
|
2015-11-16 20:38:56 +08:00
|
|
|
if (!Style.SortIncludes)
|
|
|
|
return Replaces;
|
|
|
|
|
2015-09-23 16:30:47 +08:00
|
|
|
unsigned Prev = 0;
|
|
|
|
unsigned SearchFrom = 0;
|
2015-09-29 15:53:08 +08:00
|
|
|
llvm::Regex IncludeRegex(
|
2015-10-22 01:13:45 +08:00
|
|
|
R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))");
|
2015-09-23 16:30:47 +08:00
|
|
|
SmallVector<StringRef, 4> Matches;
|
|
|
|
SmallVector<IncludeDirective, 16> IncludesInBlock;
|
2015-09-29 15:53:08 +08:00
|
|
|
|
|
|
|
// In compiled files, consider the first #include to be the main #include of
|
|
|
|
// the file if it is not a system #include. This ensures that the header
|
|
|
|
// doesn't have hidden dependencies
|
|
|
|
// (http://llvm.org/docs/CodingStandards.html#include-style).
|
|
|
|
//
|
|
|
|
// FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
|
|
|
|
// cases where the first #include is unlikely to be the main header.
|
2015-12-21 20:14:17 +08:00
|
|
|
bool IsSource = FileName.endswith(".c") || FileName.endswith(".cc") ||
|
|
|
|
FileName.endswith(".cpp") || FileName.endswith(".c++") ||
|
|
|
|
FileName.endswith(".cxx") || FileName.endswith(".m") ||
|
|
|
|
FileName.endswith(".mm");
|
|
|
|
StringRef FileStem = llvm::sys::path::stem(FileName);
|
2015-12-21 21:40:49 +08:00
|
|
|
bool FirstIncludeBlock = true;
|
2015-12-22 01:28:24 +08:00
|
|
|
bool MainIncludeFound = false;
|
2015-09-29 15:53:08 +08:00
|
|
|
|
|
|
|
// Create pre-compiled regular expressions for the #include categories.
|
|
|
|
SmallVector<llvm::Regex, 4> CategoryRegexs;
|
2015-10-06 19:54:18 +08:00
|
|
|
for (const auto &Category : Style.IncludeCategories)
|
|
|
|
CategoryRegexs.emplace_back(Category.Regex);
|
2015-09-29 15:53:08 +08:00
|
|
|
|
2015-11-21 17:17:08 +08:00
|
|
|
bool FormattingOff = false;
|
|
|
|
|
2015-09-23 16:30:47 +08:00
|
|
|
for (;;) {
|
|
|
|
auto Pos = Code.find('\n', SearchFrom);
|
|
|
|
StringRef Line =
|
|
|
|
Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
|
2015-11-21 17:17:08 +08:00
|
|
|
|
|
|
|
StringRef Trimmed = Line.trim();
|
|
|
|
if (Trimmed == "// clang-format off")
|
|
|
|
FormattingOff = true;
|
|
|
|
else if (Trimmed == "// clang-format on")
|
|
|
|
FormattingOff = false;
|
|
|
|
|
|
|
|
if (!FormattingOff && !Line.endswith("\\")) {
|
2015-09-23 16:30:47 +08:00
|
|
|
if (IncludeRegex.match(Line, &Matches)) {
|
2015-10-22 01:13:45 +08:00
|
|
|
StringRef IncludeName = Matches[2];
|
2015-12-21 20:14:17 +08:00
|
|
|
int Category = INT_MAX;
|
|
|
|
for (unsigned i = 0, e = CategoryRegexs.size(); i != e; ++i) {
|
|
|
|
if (CategoryRegexs[i].match(IncludeName)) {
|
|
|
|
Category = Style.IncludeCategories[i].Priority;
|
|
|
|
break;
|
2015-09-29 15:53:08 +08:00
|
|
|
}
|
2015-09-23 16:30:47 +08:00
|
|
|
}
|
2015-12-22 01:28:24 +08:00
|
|
|
if (IsSource && !MainIncludeFound && Category > 0 &&
|
|
|
|
FirstIncludeBlock && IncludeName.startswith("\"")) {
|
2015-12-21 20:14:17 +08:00
|
|
|
StringRef HeaderStem =
|
|
|
|
llvm::sys::path::stem(IncludeName.drop_front(1).drop_back(1));
|
2015-12-22 01:28:24 +08:00
|
|
|
if (FileStem.startswith(HeaderStem)) {
|
2016-03-21 22:11:27 +08:00
|
|
|
llvm::Regex MainIncludeRegex(
|
|
|
|
(HeaderStem + Style.IncludeIsMainRegex).str());
|
|
|
|
if (MainIncludeRegex.match(FileStem)) {
|
|
|
|
Category = 0;
|
|
|
|
MainIncludeFound = true;
|
|
|
|
}
|
2015-12-22 01:28:24 +08:00
|
|
|
}
|
2015-12-21 20:14:17 +08:00
|
|
|
}
|
2015-10-22 01:13:45 +08:00
|
|
|
IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
|
2015-09-23 16:30:47 +08:00
|
|
|
} else if (!IncludesInBlock.empty()) {
|
2015-11-23 16:36:35 +08:00
|
|
|
sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
|
|
|
|
Cursor);
|
2015-09-23 16:30:47 +08:00
|
|
|
IncludesInBlock.clear();
|
2015-12-21 21:40:49 +08:00
|
|
|
FirstIncludeBlock = false;
|
2015-09-23 16:30:47 +08:00
|
|
|
}
|
|
|
|
Prev = Pos + 1;
|
|
|
|
}
|
|
|
|
if (Pos == StringRef::npos || Pos + 1 == Code.size())
|
|
|
|
break;
|
|
|
|
SearchFrom = Pos + 1;
|
|
|
|
}
|
|
|
|
if (!IncludesInBlock.empty())
|
2015-11-23 16:36:35 +08:00
|
|
|
sortIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
|
2015-09-23 16:30:47 +08:00
|
|
|
return Replaces;
|
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
template <typename T>
|
|
|
|
static tooling::Replacements
|
|
|
|
processReplacements(T ProcessFunc, StringRef Code,
|
|
|
|
const tooling::Replacements &Replaces,
|
|
|
|
const FormatStyle &Style) {
|
2016-03-01 20:37:30 +08:00
|
|
|
if (Replaces.empty())
|
|
|
|
return tooling::Replacements();
|
|
|
|
|
|
|
|
std::string NewCode = applyAllReplacements(Code, Replaces);
|
|
|
|
std::vector<tooling::Range> ChangedRanges =
|
2016-03-30 00:31:53 +08:00
|
|
|
tooling::calculateChangedRanges(Replaces);
|
2016-03-01 20:37:30 +08:00
|
|
|
StringRef FileName = Replaces.begin()->getFilePath();
|
2016-04-25 23:09:22 +08:00
|
|
|
|
2016-03-01 20:37:30 +08:00
|
|
|
tooling::Replacements FormatReplaces =
|
2016-04-25 23:09:22 +08:00
|
|
|
ProcessFunc(Style, NewCode, ChangedRanges, FileName);
|
2016-03-01 20:37:30 +08:00
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
return mergeReplacements(Replaces, FormatReplaces);
|
|
|
|
}
|
2016-03-24 18:21:00 +08:00
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
tooling::Replacements formatReplacements(StringRef Code,
|
|
|
|
const tooling::Replacements &Replaces,
|
|
|
|
const FormatStyle &Style) {
|
|
|
|
// We need to use lambda function here since there are two versions of
|
|
|
|
// `reformat`.
|
|
|
|
auto Reformat = [](const FormatStyle &Style, StringRef Code,
|
|
|
|
std::vector<tooling::Range> Ranges,
|
|
|
|
StringRef FileName) -> tooling::Replacements {
|
|
|
|
return reformat(Style, Code, Ranges, FileName);
|
|
|
|
};
|
|
|
|
return processReplacements(Reformat, Code, Replaces, Style);
|
2016-03-01 20:37:30 +08:00
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
tooling::Replacements
|
|
|
|
cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
|
|
|
|
const FormatStyle &Style) {
|
|
|
|
// We need to use lambda function here since there are two versions of
|
|
|
|
// `cleanup`.
|
|
|
|
auto Cleanup = [](const FormatStyle &Style, StringRef Code,
|
|
|
|
std::vector<tooling::Range> Ranges,
|
|
|
|
StringRef FileName) -> tooling::Replacements {
|
|
|
|
return cleanup(Style, Code, Ranges, FileName);
|
|
|
|
};
|
|
|
|
return processReplacements(Cleanup, Code, Replaces, Style);
|
|
|
|
}
|
|
|
|
|
|
|
|
tooling::Replacements reformat(const FormatStyle &Style, SourceManager &SM,
|
|
|
|
FileID ID, ArrayRef<CharSourceRange> Ranges,
|
2015-05-07 20:26:30 +08:00
|
|
|
bool *IncompleteFormat) {
|
2015-09-29 22:57:55 +08:00
|
|
|
FormatStyle Expanded = expandPresets(Style);
|
|
|
|
if (Expanded.DisableFormat)
|
2014-09-09 22:37:39 +08:00
|
|
|
return tooling::Replacements();
|
2016-04-25 23:09:22 +08:00
|
|
|
|
2016-04-28 15:52:03 +08:00
|
|
|
Environment Env(SM, ID, Ranges);
|
|
|
|
Formatter Format(Env, Expanded, IncompleteFormat);
|
2016-04-25 23:09:22 +08:00
|
|
|
return Format.process();
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
2013-05-16 18:40:07 +08:00
|
|
|
tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
|
2014-10-04 02:52:48 +08:00
|
|
|
ArrayRef<tooling::Range> Ranges,
|
2015-06-17 21:08:06 +08:00
|
|
|
StringRef FileName, bool *IncompleteFormat) {
|
2016-04-25 23:09:22 +08:00
|
|
|
FormatStyle Expanded = expandPresets(Style);
|
|
|
|
if (Expanded.DisableFormat)
|
2014-09-09 22:37:39 +08:00
|
|
|
return tooling::Replacements();
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
std::unique_ptr<Environment> Env =
|
2016-04-28 15:52:03 +08:00
|
|
|
Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
|
|
|
|
Formatter Format(*Env, Expanded, IncompleteFormat);
|
2016-04-25 23:09:22 +08:00
|
|
|
return Format.process();
|
|
|
|
}
|
|
|
|
|
|
|
|
tooling::Replacements cleanup(const FormatStyle &Style, SourceManager &SM,
|
|
|
|
FileID ID, ArrayRef<CharSourceRange> Ranges) {
|
2016-04-28 15:52:03 +08:00
|
|
|
Environment Env(SM, ID, Ranges);
|
|
|
|
Cleaner Clean(Env, Style);
|
2016-04-25 23:09:22 +08:00
|
|
|
return Clean.process();
|
|
|
|
}
|
|
|
|
|
|
|
|
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
|
|
|
|
ArrayRef<tooling::Range> Ranges,
|
|
|
|
StringRef FileName) {
|
|
|
|
std::unique_ptr<Environment> Env =
|
2016-04-28 15:52:03 +08:00
|
|
|
Environment::CreateVirtualEnvironment(Code, FileName, Ranges);
|
|
|
|
Cleaner Clean(*Env, Style);
|
2016-04-25 23:09:22 +08:00
|
|
|
return Clean.process();
|
2013-05-16 18:40:07 +08:00
|
|
|
}
|
|
|
|
|
2014-09-05 02:23:42 +08:00
|
|
|
LangOptions getFormattingLangOpts(const FormatStyle &Style) {
|
2013-01-10 21:08:12 +08:00
|
|
|
LangOptions LangOpts;
|
|
|
|
LangOpts.CPlusPlus = 1;
|
2014-09-05 02:23:42 +08:00
|
|
|
LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
|
|
|
|
LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
|
2013-03-22 18:01:29 +08:00
|
|
|
LangOpts.LineComment = 1;
|
2015-04-04 05:15:46 +08:00
|
|
|
bool AlternativeOperators = Style.Language == FormatStyle::LK_Cpp;
|
2014-11-14 17:02:28 +08:00
|
|
|
LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
|
2013-01-10 21:08:12 +08:00
|
|
|
LangOpts.Bool = 1;
|
|
|
|
LangOpts.ObjC1 = 1;
|
|
|
|
LangOpts.ObjC2 = 1;
|
2016-04-25 23:09:22 +08:00
|
|
|
LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
|
2015-10-05 01:51:05 +08:00
|
|
|
LangOpts.DeclSpecKeyword = 1; // To get __declspec.
|
2013-01-10 21:08:12 +08:00
|
|
|
return LangOpts;
|
|
|
|
}
|
|
|
|
|
2013-09-30 21:31:48 +08:00
|
|
|
const char *StyleOptionHelpDescription =
|
|
|
|
"Coding style, currently supports:\n"
|
|
|
|
" LLVM, Google, Chromium, Mozilla, WebKit.\n"
|
|
|
|
"Use -style=file to load style configuration from\n"
|
|
|
|
".clang-format file located in one of the parent\n"
|
|
|
|
"directories of the source file (or current\n"
|
|
|
|
"directory for stdin).\n"
|
|
|
|
"Use -style=\"{key: value, ...}\" to set specific\n"
|
|
|
|
"parameters, e.g.:\n"
|
|
|
|
" -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
|
|
|
|
|
2013-12-10 19:28:13 +08:00
|
|
|
static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
|
2015-12-25 16:53:31 +08:00
|
|
|
if (FileName.endswith(".java"))
|
2014-09-15 19:21:46 +08:00
|
|
|
return FormatStyle::LK_Java;
|
2015-12-25 16:53:31 +08:00
|
|
|
if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
|
|
|
|
return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
|
|
|
|
if (FileName.endswith_lower(".proto") ||
|
|
|
|
FileName.endswith_lower(".protodevel"))
|
2014-01-19 17:04:08 +08:00
|
|
|
return FormatStyle::LK_Proto;
|
2015-12-25 16:53:31 +08:00
|
|
|
if (FileName.endswith_lower(".td"))
|
|
|
|
return FormatStyle::LK_TableGen;
|
2013-12-10 19:28:13 +08:00
|
|
|
return FormatStyle::LK_Cpp;
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
|
|
|
|
2013-12-02 23:21:38 +08:00
|
|
|
FormatStyle getStyle(StringRef StyleName, StringRef FileName,
|
2016-03-24 21:22:42 +08:00
|
|
|
StringRef FallbackStyle, vfs::FileSystem *FS) {
|
|
|
|
if (!FS) {
|
|
|
|
FS = vfs::getRealFileSystem().get();
|
|
|
|
}
|
2013-12-10 19:28:13 +08:00
|
|
|
FormatStyle Style = getLLVMStyle();
|
|
|
|
Style.Language = getLanguageByFileName(FileName);
|
|
|
|
if (!getPredefinedStyle(FallbackStyle, Style.Language, &Style)) {
|
2013-12-02 23:21:38 +08:00
|
|
|
llvm::errs() << "Invalid fallback style \"" << FallbackStyle
|
|
|
|
<< "\" using LLVM style\n";
|
2013-12-10 19:28:13 +08:00
|
|
|
return Style;
|
2013-12-02 23:21:38 +08:00
|
|
|
}
|
2013-09-30 21:31:48 +08:00
|
|
|
|
|
|
|
if (StyleName.startswith("{")) {
|
|
|
|
// Parse YAML/JSON style from the command line.
|
2014-06-12 22:02:15 +08:00
|
|
|
if (std::error_code ec = parseConfiguration(StyleName, &Style)) {
|
2013-10-14 08:46:35 +08:00
|
|
|
llvm::errs() << "Error parsing -style: " << ec.message() << ", using "
|
|
|
|
<< FallbackStyle << " style\n";
|
2013-09-30 21:31:48 +08:00
|
|
|
}
|
|
|
|
return Style;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!StyleName.equals_lower("file")) {
|
2013-12-10 19:28:13 +08:00
|
|
|
if (!getPredefinedStyle(StyleName, Style.Language, &Style))
|
2013-09-30 21:31:48 +08:00
|
|
|
llvm::errs() << "Invalid value for -style, using " << FallbackStyle
|
|
|
|
<< " style\n";
|
|
|
|
return Style;
|
|
|
|
}
|
|
|
|
|
2013-12-10 19:28:13 +08:00
|
|
|
// Look for .clang-format/_clang-format file in the file's parent directories.
|
2013-11-29 23:19:43 +08:00
|
|
|
SmallString<128> UnsuitableConfigFiles;
|
2013-09-30 21:31:48 +08:00
|
|
|
SmallString<128> Path(FileName);
|
|
|
|
llvm::sys::fs::make_absolute(Path);
|
2013-10-14 08:46:35 +08:00
|
|
|
for (StringRef Directory = Path; !Directory.empty();
|
2013-09-30 21:31:48 +08:00
|
|
|
Directory = llvm::sys::path::parent_path(Directory)) {
|
2016-03-24 21:22:42 +08:00
|
|
|
|
|
|
|
auto Status = FS->status(Directory);
|
|
|
|
if (!Status ||
|
|
|
|
Status->getType() != llvm::sys::fs::file_type::directory_file) {
|
2013-09-30 21:31:48 +08:00
|
|
|
continue;
|
2016-03-24 21:22:42 +08:00
|
|
|
}
|
|
|
|
|
2013-09-30 21:31:48 +08:00
|
|
|
SmallString<128> ConfigFile(Directory);
|
|
|
|
|
|
|
|
llvm::sys::path::append(ConfigFile, ".clang-format");
|
|
|
|
DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
|
2016-03-24 21:22:37 +08:00
|
|
|
|
2016-03-24 21:22:42 +08:00
|
|
|
Status = FS->status(ConfigFile.str());
|
|
|
|
bool IsFile =
|
|
|
|
Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
|
2013-09-30 21:31:48 +08:00
|
|
|
if (!IsFile) {
|
|
|
|
// Try _clang-format too, since dotfiles are not commonly used on Windows.
|
|
|
|
ConfigFile = Directory;
|
|
|
|
llvm::sys::path::append(ConfigFile, "_clang-format");
|
|
|
|
DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
|
2016-03-24 21:22:42 +08:00
|
|
|
Status = FS->status(ConfigFile.str());
|
|
|
|
IsFile = Status &&
|
|
|
|
(Status->getType() == llvm::sys::fs::file_type::regular_file);
|
2013-09-30 21:31:48 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if (IsFile) {
|
2014-07-07 01:43:24 +08:00
|
|
|
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
|
2016-03-24 21:22:42 +08:00
|
|
|
FS->getBufferForFile(ConfigFile.str());
|
2014-07-07 01:43:24 +08:00
|
|
|
if (std::error_code EC = Text.getError()) {
|
|
|
|
llvm::errs() << EC.message() << "\n";
|
2013-12-02 23:21:38 +08:00
|
|
|
break;
|
2013-09-30 21:31:48 +08:00
|
|
|
}
|
2014-07-07 01:43:24 +08:00
|
|
|
if (std::error_code ec =
|
|
|
|
parseConfiguration(Text.get()->getBuffer(), &Style)) {
|
2014-06-12 10:50:04 +08:00
|
|
|
if (ec == ParseError::Unsuitable) {
|
2013-11-29 23:19:43 +08:00
|
|
|
if (!UnsuitableConfigFiles.empty())
|
|
|
|
UnsuitableConfigFiles.append(", ");
|
|
|
|
UnsuitableConfigFiles.append(ConfigFile);
|
2013-12-02 23:21:38 +08:00
|
|
|
continue;
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
2013-12-02 23:21:38 +08:00
|
|
|
llvm::errs() << "Error reading " << ConfigFile << ": " << ec.message()
|
|
|
|
<< "\n";
|
|
|
|
break;
|
2013-09-30 21:31:48 +08:00
|
|
|
}
|
|
|
|
DEBUG(llvm::dbgs() << "Using configuration file " << ConfigFile << "\n");
|
|
|
|
return Style;
|
|
|
|
}
|
|
|
|
}
|
2013-11-29 23:19:43 +08:00
|
|
|
if (!UnsuitableConfigFiles.empty()) {
|
|
|
|
llvm::errs() << "Configuration file(s) do(es) not support "
|
|
|
|
<< getLanguageName(Style.Language) << ": "
|
|
|
|
<< UnsuitableConfigFiles << "\n";
|
|
|
|
}
|
2013-09-30 21:31:48 +08:00
|
|
|
return Style;
|
|
|
|
}
|
|
|
|
|
2013-01-07 21:26:07 +08:00
|
|
|
} // namespace format
|
|
|
|
} // namespace clang
|