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.
|
|
|
|
///
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2013-08-16 19:20:30 +08:00
|
|
|
#include "ContinuationIndenter.h"
|
2013-01-30 05:01:14 +08:00
|
|
|
#include "TokenAnnotator.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"
|
2013-01-16 22:55:28 +08:00
|
|
|
#include "clang/Format/Format.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"
|
2014-01-07 19:51:46 +08:00
|
|
|
#include "llvm/Support/YAMLTraits.h"
|
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)
|
|
|
|
|
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);
|
|
|
|
IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
|
2014-01-19 17:04:08 +08:00
|
|
|
IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
|
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);
|
2013-09-28 00:14:22 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
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);
|
|
|
|
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);
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
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
|
|
|
}
|
|
|
|
};
|
|
|
|
|
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()) {
|
2013-09-03 00:39:23 +08:00
|
|
|
StringRef StylesArray[] = { "LLVM", "Google", "Chromium",
|
2013-12-10 23:42:15 +08:00
|
|
|
"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
|
|
|
}
|
|
|
|
|
|
|
|
IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
|
2013-08-13 18:58:30 +08:00
|
|
|
IO.mapOptional("ConstructorInitializerIndentWidth",
|
|
|
|
Style.ConstructorInitializerIndentWidth);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlinesLeft);
|
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);
|
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);
|
2013-11-21 00:33:05 +08:00
|
|
|
IO.mapOptional("AllowShortFunctionsOnASingleLine",
|
|
|
|
Style.AllowShortFunctionsOnASingleLine);
|
2013-05-29 20:07:31 +08:00
|
|
|
IO.mapOptional("AlwaysBreakTemplateDeclarations",
|
|
|
|
Style.AlwaysBreakTemplateDeclarations);
|
2013-07-04 20:02:44 +08:00
|
|
|
IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
|
|
|
|
Style.AlwaysBreakBeforeMultilineStrings);
|
2013-07-27 00:56:36 +08:00
|
|
|
IO.mapOptional("BreakBeforeBinaryOperators",
|
|
|
|
Style.BreakBeforeBinaryOperators);
|
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);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("BinPackParameters", Style.BinPackParameters);
|
|
|
|
IO.mapOptional("ColumnLimit", Style.ColumnLimit);
|
|
|
|
IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
|
|
|
|
Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
|
|
|
|
IO.mapOptional("DerivePointerBinding", Style.DerivePointerBinding);
|
2013-07-10 22:02:49 +08:00
|
|
|
IO.mapOptional("ExperimentalAutoDetectBinPacking",
|
|
|
|
Style.ExperimentalAutoDetectBinPacking);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
|
|
|
|
IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
|
2014-03-21 21:43:14 +08:00
|
|
|
IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
|
|
|
|
Style.KeepEmptyLinesAtTheStartOfBlocks);
|
2013-08-01 07:16:02 +08:00
|
|
|
IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
|
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);
|
|
|
|
IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
|
2013-07-12 04:41:21 +08:00
|
|
|
IO.mapOptional("PenaltyBreakFirstLessLess",
|
|
|
|
Style.PenaltyBreakFirstLessLess);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
|
|
|
|
IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
|
|
|
|
Style.PenaltyReturnTypeOnItsOwnLine);
|
|
|
|
IO.mapOptional("PointerBindsToType", Style.PointerBindsToType);
|
|
|
|
IO.mapOptional("SpacesBeforeTrailingComments",
|
|
|
|
Style.SpacesBeforeTrailingComments);
|
2013-07-17 02:22:10 +08:00
|
|
|
IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("Standard", Style.Standard);
|
2013-05-13 16:42:42 +08:00
|
|
|
IO.mapOptional("IndentWidth", Style.IndentWidth);
|
2013-09-05 22:08:34 +08:00
|
|
|
IO.mapOptional("TabWidth", Style.TabWidth);
|
2013-05-13 17:22:11 +08:00
|
|
|
IO.mapOptional("UseTab", Style.UseTab);
|
2013-05-13 20:51:40 +08:00
|
|
|
IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
|
2013-06-22 01:25:42 +08:00
|
|
|
IO.mapOptional("IndentFunctionDeclarationAfterType",
|
|
|
|
Style.IndentFunctionDeclarationAfterType);
|
2013-08-20 20:36:34 +08:00
|
|
|
IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
|
2013-10-29 22:52:02 +08:00
|
|
|
IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
|
2013-08-21 16:39:01 +08:00
|
|
|
IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
|
2013-08-20 20:36:34 +08:00
|
|
|
IO.mapOptional("SpacesInCStyleCastParentheses",
|
|
|
|
Style.SpacesInCStyleCastParentheses);
|
2014-01-15 23:09:08 +08:00
|
|
|
IO.mapOptional("SpacesInContainerLiterals",
|
|
|
|
Style.SpacesInContainerLiterals);
|
2013-09-25 23:15:02 +08:00
|
|
|
IO.mapOptional("SpaceBeforeAssignmentOperators",
|
|
|
|
Style.SpaceBeforeAssignmentOperators);
|
2013-10-18 18:38:14 +08:00
|
|
|
IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
|
2014-01-02 23:13:14 +08:00
|
|
|
IO.mapOptional("CommentPragmas", Style.CommentPragmas);
|
2014-05-09 21:11:16 +08:00
|
|
|
IO.mapOptional("ForEachMacros", Style.ForEachMacros);
|
2013-12-10 18:18:34 +08:00
|
|
|
|
|
|
|
// For backward compatibility.
|
|
|
|
if (!IO.outputting()) {
|
|
|
|
IO.mapOptional("SpaceAfterControlStatementKeyword",
|
|
|
|
Style.SpaceBeforeParens);
|
|
|
|
}
|
|
|
|
IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
|
2014-05-22 23:12:22 +08:00
|
|
|
IO.mapOptional("DisableFormat", Style.DisableFormat);
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
};
|
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.
|
2013-12-10 18:30:34 +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
|
|
|
}
|
|
|
|
};
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
namespace clang {
|
|
|
|
namespace format {
|
|
|
|
|
|
|
|
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;
|
2013-08-01 07:55:15 +08:00
|
|
|
LLVMStyle.AlignTrailingComments = true;
|
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;
|
2013-01-15 00:24:39 +08:00
|
|
|
LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
|
2013-05-16 20:12:21 +08:00
|
|
|
LLVMStyle.AllowShortLoopsOnASingleLine = false;
|
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;
|
2013-07-27 00:56:36 +08:00
|
|
|
LLVMStyle.BreakBeforeBinaryOperators = false;
|
2013-11-08 08:57:11 +08:00
|
|
|
LLVMStyle.BreakBeforeTernaryOperators = true;
|
2013-07-27 00:56:36 +08:00
|
|
|
LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
|
|
|
|
LLVMStyle.BreakConstructorInitializersBeforeComma = false;
|
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;
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.DerivePointerBinding = 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");
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.IndentCaseLabels = false;
|
2013-07-27 00:56:36 +08:00
|
|
|
LLVMStyle.IndentFunctionDeclarationAfterType = false;
|
|
|
|
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-01-28 23:20:33 +08:00
|
|
|
LLVMStyle.ObjCSpaceAfterProperty = false;
|
2013-01-11 04:12:55 +08:00
|
|
|
LLVMStyle.ObjCSpaceBeforeProtocolList = true;
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.PointerBindsToType = false;
|
|
|
|
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;
|
2013-08-20 20:36:34 +08:00
|
|
|
LLVMStyle.SpacesInParentheses = false;
|
|
|
|
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;
|
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;
|
|
|
|
|
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;
|
|
|
|
GoogleStyle.DerivePointerBinding = true;
|
|
|
|
GoogleStyle.IndentCaseLabels = true;
|
2013-07-27 00:56:36 +08:00
|
|
|
GoogleStyle.IndentFunctionDeclarationAfterType = 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;
|
2013-05-06 22:11:27 +08:00
|
|
|
GoogleStyle.PointerBindsToType = true;
|
|
|
|
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-02-03 04:50:45 +08:00
|
|
|
if (Language == FormatStyle::LK_JavaScript) {
|
|
|
|
GoogleStyle.BreakBeforeTernaryOperators = false;
|
2014-05-09 18:28:58 +08:00
|
|
|
GoogleStyle.MaxEmptyLinesToKeep = 3;
|
2014-02-03 04:50:45 +08:00
|
|
|
GoogleStyle.SpacesInContainerLiterals = false;
|
|
|
|
} 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);
|
2013-01-30 00:03:49 +08:00
|
|
|
ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
|
2014-04-08 20:46:38 +08:00
|
|
|
ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
|
2013-04-24 21:46:00 +08:00
|
|
|
ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
|
2013-05-16 20:12:21 +08:00
|
|
|
ChromiumStyle.AllowShortLoopsOnASingleLine = false;
|
2013-02-27 17:47:53 +08:00
|
|
|
ChromiumStyle.BinPackParameters = false;
|
2013-02-06 22:22:40 +08:00
|
|
|
ChromiumStyle.DerivePointerBinding = false;
|
2013-07-27 00:56:36 +08:00
|
|
|
ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
|
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;
|
2014-03-02 20:37:31 +08:00
|
|
|
MozillaStyle.Cpp11BracedListStyle = false;
|
2013-05-06 22:11:27 +08:00
|
|
|
MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
|
|
|
|
MozillaStyle.DerivePointerBinding = true;
|
|
|
|
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;
|
|
|
|
MozillaStyle.PointerBindsToType = true;
|
2014-03-02 20:37:31 +08:00
|
|
|
MozillaStyle.Standard = FormatStyle::LS_Cpp03;
|
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;
|
2013-08-01 07:55:15 +08:00
|
|
|
Style.AlignTrailingComments = false;
|
2013-07-27 00:56:36 +08:00
|
|
|
Style.BreakBeforeBinaryOperators = true;
|
2013-08-01 07:16:02 +08:00
|
|
|
Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
|
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-01-28 23:20:33 +08:00
|
|
|
Style.ObjCSpaceAfterProperty = true;
|
2013-07-24 21:10:59 +08:00
|
|
|
Style.PointerBindsToType = true;
|
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();
|
|
|
|
Style.BreakBeforeBinaryOperators = true;
|
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;
|
|
|
|
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
|
|
|
}
|
|
|
|
|
|
|
|
llvm::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())
|
|
|
|
return llvm::make_error_code(llvm::errc::invalid_argument);
|
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)
|
2013-11-29 23:19:43 +08:00
|
|
|
return llvm::make_error_code(llvm::errc::invalid_argument);
|
|
|
|
// 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");
|
2013-11-29 23:19:43 +08:00
|
|
|
return llvm::make_error_code(llvm::errc::invalid_argument);
|
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-05-31 09:26:30 +08:00
|
|
|
return llvm::error_code();
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return llvm::make_error_code(llvm::errc::not_supported);
|
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.
|
|
|
|
FormatStyle NonConstStyle = Style;
|
|
|
|
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-08-16 19:20:30 +08:00
|
|
|
class NoColumnLimitFormatter {
|
2012-12-04 02:12:45 +08:00
|
|
|
public:
|
2013-08-21 16:39:01 +08:00
|
|
|
NoColumnLimitFormatter(ContinuationIndenter *Indenter) : Indenter(Indenter) {}
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-08-16 19:20:30 +08:00
|
|
|
/// \brief Formats the line starting at \p State, simply keeping all of the
|
|
|
|
/// input's line breaking decisions.
|
2013-12-16 22:35:51 +08:00
|
|
|
void format(unsigned FirstIndent, const AnnotatedLine *Line) {
|
2013-09-06 15:54:20 +08:00
|
|
|
LineState State =
|
|
|
|
Indenter->getInitialState(FirstIndent, Line, /*DryRun=*/false);
|
2014-05-09 16:15:10 +08:00
|
|
|
while (State.NextToken) {
|
2013-08-16 19:20:30 +08:00
|
|
|
bool Newline =
|
2013-12-16 22:35:51 +08:00
|
|
|
Indenter->mustBreak(State) ||
|
2013-08-16 19:20:30 +08:00
|
|
|
(Indenter->canBreak(State) && State.NextToken->NewlinesBefore > 0);
|
|
|
|
Indenter->addTokenToState(State, Newline, /*DryRun=*/false);
|
2013-07-24 21:10:59 +08:00
|
|
|
}
|
2013-08-16 19:20:30 +08:00
|
|
|
}
|
2013-08-21 16:39:01 +08:00
|
|
|
|
2013-08-16 19:20:30 +08:00
|
|
|
private:
|
|
|
|
ContinuationIndenter *Indenter;
|
|
|
|
};
|
2013-07-24 21:10:59 +08:00
|
|
|
|
2013-11-07 07:12:09 +08:00
|
|
|
class LineJoiner {
|
|
|
|
public:
|
|
|
|
LineJoiner(const FormatStyle &Style) : Style(Style) {}
|
|
|
|
|
|
|
|
/// \brief Calculates how many lines can be merged into 1 starting at \p I.
|
|
|
|
unsigned
|
|
|
|
tryFitMultipleLinesInOne(unsigned Indent,
|
2013-11-21 00:33:05 +08:00
|
|
|
SmallVectorImpl<AnnotatedLine *>::const_iterator I,
|
2013-11-07 07:12:09 +08:00
|
|
|
SmallVectorImpl<AnnotatedLine *>::const_iterator E) {
|
|
|
|
// We can never merge stuff if there are trailing line comments.
|
2013-12-24 21:31:25 +08:00
|
|
|
const AnnotatedLine *TheLine = *I;
|
2013-11-07 07:12:09 +08:00
|
|
|
if (TheLine->Last->Type == TT_LineComment)
|
|
|
|
return 0;
|
|
|
|
|
2013-12-04 21:25:26 +08:00
|
|
|
if (Style.ColumnLimit > 0 && Indent > Style.ColumnLimit)
|
|
|
|
return 0;
|
|
|
|
|
2013-11-09 01:33:27 +08:00
|
|
|
unsigned Limit =
|
|
|
|
Style.ColumnLimit == 0 ? UINT_MAX : Style.ColumnLimit - Indent;
|
2013-11-07 07:12:09 +08:00
|
|
|
// If we already exceed the column limit, we set 'Limit' to 0. The different
|
|
|
|
// tryMerge..() functions can then decide whether to still do merging.
|
|
|
|
Limit = TheLine->Last->TotalLength > Limit
|
|
|
|
? 0
|
|
|
|
: Limit - TheLine->Last->TotalLength;
|
|
|
|
|
2014-05-05 19:36:35 +08:00
|
|
|
if (I + 1 == E || I[1]->Type == LT_Invalid || I[1]->First->MustBreakBefore)
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
|
|
|
|
2014-04-08 20:46:38 +08:00
|
|
|
// FIXME: TheLine->Level != 0 might or might not be the right check to do.
|
|
|
|
// If necessary, change to something smarter.
|
|
|
|
bool MergeShortFunctions =
|
|
|
|
Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_All ||
|
|
|
|
(Style.AllowShortFunctionsOnASingleLine == FormatStyle::SFS_Inline &&
|
|
|
|
TheLine->Level != 0);
|
|
|
|
|
2013-12-24 21:31:25 +08:00
|
|
|
if (TheLine->Last->Type == TT_FunctionLBrace &&
|
|
|
|
TheLine->First != TheLine->Last) {
|
2014-04-08 20:46:38 +08:00
|
|
|
return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
|
2013-11-21 00:33:05 +08:00
|
|
|
}
|
2013-11-07 07:12:09 +08:00
|
|
|
if (TheLine->Last->is(tok::l_brace)) {
|
2013-12-10 18:30:34 +08:00
|
|
|
return Style.BreakBeforeBraces == FormatStyle::BS_Attach
|
2013-11-21 00:33:05 +08:00
|
|
|
? tryMergeSimpleBlock(I, E, Limit)
|
|
|
|
: 0;
|
|
|
|
}
|
|
|
|
if (I[1]->First->Type == TT_FunctionLBrace &&
|
|
|
|
Style.BreakBeforeBraces != FormatStyle::BS_Attach) {
|
2013-12-30 10:06:29 +08:00
|
|
|
// Check for Limit <= 2 to account for the " {".
|
2013-12-24 21:31:25 +08:00
|
|
|
if (Limit <= 2 || (Style.ColumnLimit == 0 && containsMustBreak(TheLine)))
|
|
|
|
return 0;
|
|
|
|
Limit -= 2;
|
|
|
|
|
2013-11-21 00:33:05 +08:00
|
|
|
unsigned MergedLines = 0;
|
2014-04-08 20:46:38 +08:00
|
|
|
if (MergeShortFunctions) {
|
2013-11-21 00:33:05 +08:00
|
|
|
MergedLines = tryMergeSimpleBlock(I + 1, E, Limit);
|
|
|
|
// If we managed to merge the block, count the function header, which is
|
|
|
|
// on a separate line.
|
|
|
|
if (MergedLines > 0)
|
|
|
|
++MergedLines;
|
|
|
|
}
|
|
|
|
return MergedLines;
|
|
|
|
}
|
|
|
|
if (TheLine->First->is(tok::kw_if)) {
|
|
|
|
return Style.AllowShortIfStatementsOnASingleLine
|
|
|
|
? tryMergeSimpleControlStatement(I, E, Limit)
|
|
|
|
: 0;
|
|
|
|
}
|
|
|
|
if (TheLine->First->isOneOf(tok::kw_for, tok::kw_while)) {
|
|
|
|
return Style.AllowShortLoopsOnASingleLine
|
|
|
|
? tryMergeSimpleControlStatement(I, E, Limit)
|
|
|
|
: 0;
|
|
|
|
}
|
|
|
|
if (TheLine->InPPDirective &&
|
|
|
|
(TheLine->First->HasUnescapedNewline || TheLine->First->IsFirst)) {
|
2013-11-07 07:12:09 +08:00
|
|
|
return tryMergeSimplePPDirective(I, E, Limit);
|
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
unsigned
|
2013-11-21 00:33:05 +08:00
|
|
|
tryMergeSimplePPDirective(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
|
2013-11-07 07:12:09 +08:00
|
|
|
SmallVectorImpl<AnnotatedLine *>::const_iterator E,
|
|
|
|
unsigned Limit) {
|
|
|
|
if (Limit == 0)
|
|
|
|
return 0;
|
2013-11-19 22:30:44 +08:00
|
|
|
if (!I[1]->InPPDirective || I[1]->First->HasUnescapedNewline)
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
2013-11-19 22:30:44 +08:00
|
|
|
if (I + 2 != E && I[2]->InPPDirective && !I[2]->First->HasUnescapedNewline)
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
2013-11-19 22:30:44 +08:00
|
|
|
if (1 + I[1]->Last->TotalLength > Limit)
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
unsigned tryMergeSimpleControlStatement(
|
2013-11-21 00:33:05 +08:00
|
|
|
SmallVectorImpl<AnnotatedLine *>::const_iterator I,
|
2013-11-07 07:12:09 +08:00
|
|
|
SmallVectorImpl<AnnotatedLine *>::const_iterator E, unsigned Limit) {
|
|
|
|
if (Limit == 0)
|
|
|
|
return 0;
|
2013-12-12 17:49:52 +08:00
|
|
|
if ((Style.BreakBeforeBraces == FormatStyle::BS_Allman ||
|
|
|
|
Style.BreakBeforeBraces == FormatStyle::BS_GNU) &&
|
2014-05-14 17:33:35 +08:00
|
|
|
(I[1]->First->is(tok::l_brace) && !Style.AllowShortBlocksOnASingleLine))
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
2013-11-19 22:30:44 +08:00
|
|
|
if (I[1]->InPPDirective != (*I)->InPPDirective ||
|
|
|
|
(I[1]->InPPDirective && I[1]->First->HasUnescapedNewline))
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
2014-02-11 18:08:11 +08:00
|
|
|
Limit = limitConsideringMacros(I + 1, E, Limit);
|
2013-11-07 07:12:09 +08:00
|
|
|
AnnotatedLine &Line = **I;
|
|
|
|
if (Line.Last->isNot(tok::r_paren))
|
|
|
|
return 0;
|
2013-11-19 22:30:44 +08:00
|
|
|
if (1 + I[1]->Last->TotalLength > Limit)
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
2013-11-19 22:30:44 +08:00
|
|
|
if (I[1]->First->isOneOf(tok::semi, tok::kw_if, tok::kw_for,
|
2013-11-21 00:33:05 +08:00
|
|
|
tok::kw_while) ||
|
2013-11-19 22:30:44 +08:00
|
|
|
I[1]->First->Type == TT_LineComment)
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
|
|
|
// Only inline simple if's (no nested if or else).
|
|
|
|
if (I + 2 != E && Line.First->is(tok::kw_if) &&
|
2013-11-19 22:30:44 +08:00
|
|
|
I[2]->First->is(tok::kw_else))
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
unsigned
|
2013-11-21 00:33:05 +08:00
|
|
|
tryMergeSimpleBlock(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
|
2013-11-07 07:12:09 +08:00
|
|
|
SmallVectorImpl<AnnotatedLine *>::const_iterator E,
|
|
|
|
unsigned Limit) {
|
|
|
|
AnnotatedLine &Line = **I;
|
2014-05-14 17:33:35 +08:00
|
|
|
|
|
|
|
// Don't merge ObjC @ keywords and methods.
|
|
|
|
if (Line.First->isOneOf(tok::at, tok::minus, tok::plus))
|
|
|
|
return 0;
|
|
|
|
|
|
|
|
// Check that the current line allows merging. This depends on whether we
|
|
|
|
// are in a control flow statements as well as several style flags.
|
|
|
|
if (Line.First->isOneOf(tok::kw_else, tok::kw_case))
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
2014-05-14 17:33:35 +08:00
|
|
|
if (Line.First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_do, tok::kw_try,
|
|
|
|
tok::kw_catch, tok::kw_for, tok::r_brace)) {
|
|
|
|
if (!Style.AllowShortBlocksOnASingleLine)
|
|
|
|
return 0;
|
|
|
|
if (!Style.AllowShortIfStatementsOnASingleLine &&
|
|
|
|
Line.First->is(tok::kw_if))
|
|
|
|
return 0;
|
|
|
|
if (!Style.AllowShortLoopsOnASingleLine &&
|
|
|
|
Line.First->isOneOf(tok::kw_while, tok::kw_do, tok::kw_for))
|
|
|
|
return 0;
|
|
|
|
// FIXME: Consider an option to allow short exception handling clauses on
|
|
|
|
// a single line.
|
|
|
|
if (Line.First->isOneOf(tok::kw_try, tok::kw_catch))
|
|
|
|
return 0;
|
|
|
|
}
|
2013-11-07 07:12:09 +08:00
|
|
|
|
2013-11-19 22:30:44 +08:00
|
|
|
FormatToken *Tok = I[1]->First;
|
2013-11-07 07:12:09 +08:00
|
|
|
if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
|
2014-05-09 16:15:10 +08:00
|
|
|
(Tok->getNextNonComment() == nullptr ||
|
2013-11-07 07:12:09 +08:00
|
|
|
Tok->getNextNonComment()->is(tok::semi))) {
|
|
|
|
// We merge empty blocks even if the line exceeds the column limit.
|
|
|
|
Tok->SpacesRequiredBefore = 0;
|
|
|
|
Tok->CanBreakBefore = true;
|
|
|
|
return 1;
|
|
|
|
} else if (Limit != 0 && Line.First->isNot(tok::kw_namespace)) {
|
2014-05-07 17:48:30 +08:00
|
|
|
// We don't merge short records.
|
|
|
|
if (Line.First->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct))
|
|
|
|
return 0;
|
|
|
|
|
2013-11-07 07:12:09 +08:00
|
|
|
// Check that we still have three lines and they fit into the limit.
|
2013-11-19 22:30:44 +08:00
|
|
|
if (I + 2 == E || I[2]->Type == LT_Invalid)
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
2014-02-11 18:08:11 +08:00
|
|
|
Limit = limitConsideringMacros(I + 2, E, Limit);
|
2013-11-07 07:12:09 +08:00
|
|
|
|
|
|
|
if (!nextTwoLinesFitInto(I, Limit))
|
|
|
|
return 0;
|
|
|
|
|
|
|
|
// Second, check that the next line does not contain any braces - if it
|
|
|
|
// does, readability declines when putting it into a single line.
|
2014-05-05 19:36:35 +08:00
|
|
|
if (I[1]->Last->Type == TT_LineComment)
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
|
|
|
do {
|
2014-05-22 21:25:26 +08:00
|
|
|
if (Tok->is(tok::l_brace) && Tok->BlockKind != BK_BracedInit)
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
|
|
|
Tok = Tok->Next;
|
2014-05-09 16:15:10 +08:00
|
|
|
} while (Tok);
|
2013-11-07 07:12:09 +08:00
|
|
|
|
2014-05-07 17:48:30 +08:00
|
|
|
// Last, check that the third line starts with a closing brace.
|
2013-11-19 22:30:44 +08:00
|
|
|
Tok = I[2]->First;
|
2014-05-07 17:48:30 +08:00
|
|
|
if (Tok->isNot(tok::r_brace))
|
2013-11-07 07:12:09 +08:00
|
|
|
return 0;
|
|
|
|
|
|
|
|
return 2;
|
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2014-02-07 21:45:27 +08:00
|
|
|
/// Returns the modified column limit for \p I if it is inside a macro and
|
|
|
|
/// needs a trailing '\'.
|
|
|
|
unsigned
|
2014-02-11 18:08:11 +08:00
|
|
|
limitConsideringMacros(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
|
2014-02-07 21:45:27 +08:00
|
|
|
SmallVectorImpl<AnnotatedLine *>::const_iterator E,
|
|
|
|
unsigned Limit) {
|
|
|
|
if (I[0]->InPPDirective && I + 1 != E &&
|
|
|
|
!I[1]->First->HasUnescapedNewline && !I[1]->First->is(tok::eof)) {
|
|
|
|
return Limit < 2 ? 0 : Limit - 2;
|
|
|
|
}
|
|
|
|
return Limit;
|
|
|
|
}
|
|
|
|
|
2013-11-07 07:12:09 +08:00
|
|
|
bool nextTwoLinesFitInto(SmallVectorImpl<AnnotatedLine *>::const_iterator I,
|
|
|
|
unsigned Limit) {
|
2014-05-05 19:36:35 +08:00
|
|
|
if (I[1]->First->MustBreakBefore || I[2]->First->MustBreakBefore)
|
|
|
|
return false;
|
2013-11-19 22:30:44 +08:00
|
|
|
return 1 + I[1]->Last->TotalLength + 1 + I[2]->Last->TotalLength <= Limit;
|
2013-11-07 07:12:09 +08:00
|
|
|
}
|
|
|
|
|
2013-12-24 21:31:25 +08:00
|
|
|
bool containsMustBreak(const AnnotatedLine *Line) {
|
|
|
|
for (const FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
|
|
|
|
if (Tok->MustBreakBefore)
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2013-11-07 07:12:09 +08:00
|
|
|
const FormatStyle &Style;
|
|
|
|
};
|
|
|
|
|
2013-08-16 19:20:30 +08:00
|
|
|
class UnwrappedLineFormatter {
|
|
|
|
public:
|
2013-11-25 19:08:59 +08:00
|
|
|
UnwrappedLineFormatter(ContinuationIndenter *Indenter,
|
2013-09-05 17:29:45 +08:00
|
|
|
WhitespaceManager *Whitespaces,
|
2013-11-06 03:10:03 +08:00
|
|
|
const FormatStyle &Style)
|
2013-11-25 19:08:59 +08:00
|
|
|
: Indenter(Indenter), Whitespaces(Whitespaces), Style(Style),
|
|
|
|
Joiner(Style) {}
|
2013-08-16 19:20:30 +08:00
|
|
|
|
2013-11-07 07:12:09 +08:00
|
|
|
unsigned format(const SmallVectorImpl<AnnotatedLine *> &Lines, bool DryRun,
|
2013-11-28 23:58:55 +08:00
|
|
|
int AdditionalIndent = 0, bool FixBadIndentation = false) {
|
2014-04-15 16:13:47 +08:00
|
|
|
// Try to look up already computed penalty in DryRun-mode.
|
2014-04-16 07:29:04 +08:00
|
|
|
std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned> CacheKey(
|
|
|
|
&Lines, AdditionalIndent);
|
2014-04-15 16:13:47 +08:00
|
|
|
auto CacheIt = PenaltyCache.find(CacheKey);
|
|
|
|
if (DryRun && CacheIt != PenaltyCache.end())
|
|
|
|
return CacheIt->second;
|
|
|
|
|
2013-11-06 03:10:03 +08:00
|
|
|
assert(!Lines.empty());
|
|
|
|
unsigned Penalty = 0;
|
|
|
|
std::vector<int> IndentForLevel;
|
|
|
|
for (unsigned i = 0, e = Lines[0]->Level; i != e; ++i)
|
|
|
|
IndentForLevel.push_back(Style.IndentWidth * i + AdditionalIndent);
|
2014-05-09 16:15:10 +08:00
|
|
|
const AnnotatedLine *PreviousLine = nullptr;
|
2013-11-07 07:12:09 +08:00
|
|
|
for (SmallVectorImpl<AnnotatedLine *>::const_iterator I = Lines.begin(),
|
|
|
|
E = Lines.end();
|
2013-11-06 03:10:03 +08:00
|
|
|
I != E; ++I) {
|
|
|
|
const AnnotatedLine &TheLine = **I;
|
|
|
|
const FormatToken *FirstTok = TheLine.First;
|
|
|
|
int Offset = getIndentOffset(*FirstTok);
|
|
|
|
|
|
|
|
// Determine indent and try to merge multiple unwrapped lines.
|
2013-12-17 20:38:55 +08:00
|
|
|
unsigned Indent;
|
|
|
|
if (TheLine.InPPDirective) {
|
|
|
|
Indent = TheLine.Level * Style.IndentWidth;
|
|
|
|
} else {
|
|
|
|
while (IndentForLevel.size() <= TheLine.Level)
|
|
|
|
IndentForLevel.push_back(-1);
|
|
|
|
IndentForLevel.resize(TheLine.Level + 1);
|
|
|
|
Indent = getIndent(IndentForLevel, TheLine.Level);
|
|
|
|
}
|
|
|
|
unsigned LevelIndent = Indent;
|
2013-11-06 03:10:03 +08:00
|
|
|
if (static_cast<int>(Indent) + Offset >= 0)
|
|
|
|
Indent += Offset;
|
2013-12-17 20:38:55 +08:00
|
|
|
|
|
|
|
// Merge multiple lines if possible.
|
2013-11-07 07:12:09 +08:00
|
|
|
unsigned MergedLines = Joiner.tryFitMultipleLinesInOne(Indent, I, E);
|
2013-12-04 20:21:08 +08:00
|
|
|
if (MergedLines > 0 && Style.ColumnLimit == 0) {
|
|
|
|
// Disallow line merging if there is a break at the start of one of the
|
|
|
|
// input lines.
|
|
|
|
for (unsigned i = 0; i < MergedLines; ++i) {
|
|
|
|
if (I[i + 1]->First->NewlinesBefore > 0)
|
|
|
|
MergedLines = 0;
|
|
|
|
}
|
|
|
|
}
|
2013-11-07 07:12:09 +08:00
|
|
|
if (!DryRun) {
|
|
|
|
for (unsigned i = 0; i < MergedLines; ++i) {
|
2013-11-19 22:30:44 +08:00
|
|
|
join(*I[i], *I[i + 1]);
|
2013-11-07 07:12:09 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
I += MergedLines;
|
2013-11-06 03:10:03 +08:00
|
|
|
|
2013-11-28 23:58:55 +08:00
|
|
|
bool FixIndentation =
|
|
|
|
FixBadIndentation && (LevelIndent != FirstTok->OriginalColumn);
|
2013-11-06 03:10:03 +08:00
|
|
|
if (TheLine.First->is(tok::eof)) {
|
2013-11-25 19:08:59 +08:00
|
|
|
if (PreviousLine && PreviousLine->Affected && !DryRun) {
|
|
|
|
// Remove the file's trailing whitespace.
|
2013-11-06 03:10:03 +08:00
|
|
|
unsigned Newlines = std::min(FirstTok->NewlinesBefore, 1u);
|
|
|
|
Whitespaces->replaceWhitespace(*TheLine.First, Newlines,
|
|
|
|
/*IndentLevel=*/0, /*Spaces=*/0,
|
|
|
|
/*TargetColumn=*/0);
|
|
|
|
}
|
2013-11-28 23:58:55 +08:00
|
|
|
} else if (TheLine.Type != LT_Invalid &&
|
|
|
|
(TheLine.Affected || FixIndentation)) {
|
2013-11-06 03:10:03 +08:00
|
|
|
if (FirstTok->WhitespaceRange.isValid()) {
|
|
|
|
if (!DryRun)
|
|
|
|
formatFirstToken(*TheLine.First, PreviousLine, TheLine.Level,
|
|
|
|
Indent, TheLine.InPPDirective);
|
|
|
|
} else {
|
|
|
|
Indent = LevelIndent = FirstTok->OriginalColumn;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If everything fits on a single line, just put it there.
|
|
|
|
unsigned ColumnLimit = Style.ColumnLimit;
|
|
|
|
if (I + 1 != E) {
|
2013-11-19 22:30:44 +08:00
|
|
|
AnnotatedLine *NextLine = I[1];
|
2013-11-06 03:10:03 +08:00
|
|
|
if (NextLine->InPPDirective && !NextLine->First->HasUnescapedNewline)
|
|
|
|
ColumnLimit = getColumnLimit(TheLine.InPPDirective);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (TheLine.Last->TotalLength + Indent <= ColumnLimit) {
|
|
|
|
LineState State = Indenter->getInitialState(Indent, &TheLine, DryRun);
|
2014-05-22 16:36:53 +08:00
|
|
|
while (State.NextToken) {
|
|
|
|
formatChildren(State, /*Newline=*/false, /*DryRun=*/false, Penalty);
|
2013-11-06 03:10:03 +08:00
|
|
|
Indenter->addTokenToState(State, /*Newline=*/false, DryRun);
|
2014-05-22 16:36:53 +08:00
|
|
|
}
|
2013-11-06 03:10:03 +08:00
|
|
|
} else if (Style.ColumnLimit == 0) {
|
2013-11-28 23:58:55 +08:00
|
|
|
// FIXME: Implement nested blocks for ColumnLimit = 0.
|
2013-11-06 03:10:03 +08:00
|
|
|
NoColumnLimitFormatter Formatter(Indenter);
|
|
|
|
if (!DryRun)
|
2013-12-16 22:35:51 +08:00
|
|
|
Formatter.format(Indent, &TheLine);
|
2013-11-06 03:10:03 +08:00
|
|
|
} else {
|
|
|
|
Penalty += format(TheLine, Indent, DryRun);
|
|
|
|
}
|
|
|
|
|
2013-12-17 20:38:55 +08:00
|
|
|
if (!TheLine.InPPDirective)
|
|
|
|
IndentForLevel[TheLine.Level] = LevelIndent;
|
2013-11-28 23:58:55 +08:00
|
|
|
} else if (TheLine.ChildrenAffected) {
|
|
|
|
format(TheLine.Children, DryRun);
|
2013-11-06 03:10:03 +08:00
|
|
|
} else {
|
|
|
|
// Format the first token if necessary, and notify the WhitespaceManager
|
|
|
|
// about the unchanged whitespace.
|
2014-05-09 16:15:10 +08:00
|
|
|
for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
|
2013-11-06 03:10:03 +08:00
|
|
|
if (Tok == TheLine.First &&
|
|
|
|
(Tok->NewlinesBefore > 0 || Tok->IsFirst)) {
|
|
|
|
unsigned LevelIndent = Tok->OriginalColumn;
|
|
|
|
if (!DryRun) {
|
2013-11-28 23:58:55 +08:00
|
|
|
// Remove trailing whitespace of the previous line.
|
2013-11-25 19:08:59 +08:00
|
|
|
if ((PreviousLine && PreviousLine->Affected) ||
|
|
|
|
TheLine.LeadingEmptyLinesAffected) {
|
2013-11-06 03:10:03 +08:00
|
|
|
formatFirstToken(*Tok, PreviousLine, TheLine.Level, LevelIndent,
|
|
|
|
TheLine.InPPDirective);
|
|
|
|
} else {
|
|
|
|
Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (static_cast<int>(LevelIndent) - Offset >= 0)
|
|
|
|
LevelIndent -= Offset;
|
2013-12-17 20:38:55 +08:00
|
|
|
if (Tok->isNot(tok::comment) && !TheLine.InPPDirective)
|
2013-11-06 03:10:03 +08:00
|
|
|
IndentForLevel[TheLine.Level] = LevelIndent;
|
|
|
|
} else if (!DryRun) {
|
|
|
|
Whitespaces->addUntouchableToken(*Tok, TheLine.InPPDirective);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (!DryRun) {
|
2014-05-09 16:15:10 +08:00
|
|
|
for (FormatToken *Tok = TheLine.First; Tok; Tok = Tok->Next) {
|
2013-11-06 03:10:03 +08:00
|
|
|
Tok->Finalized = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
PreviousLine = *I;
|
|
|
|
}
|
2014-04-15 16:13:47 +08:00
|
|
|
PenaltyCache[CacheKey] = Penalty;
|
2013-11-06 03:10:03 +08:00
|
|
|
return Penalty;
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
/// \brief Formats an \c AnnotatedLine and returns the penalty.
|
2013-09-05 17:29:45 +08:00
|
|
|
///
|
|
|
|
/// If \p DryRun is \c false, directly applies the changes.
|
2013-11-06 03:10:03 +08:00
|
|
|
unsigned format(const AnnotatedLine &Line, unsigned FirstIndent,
|
|
|
|
bool DryRun) {
|
2013-09-06 15:54:20 +08:00
|
|
|
LineState State = Indenter->getInitialState(FirstIndent, &Line, DryRun);
|
2013-02-01 19:00:45 +08:00
|
|
|
|
2013-02-08 16:22:00 +08:00
|
|
|
// If the ObjC method declaration does not fit on a line, we should format
|
|
|
|
// it with one arg per line.
|
2013-11-06 03:10:03 +08:00
|
|
|
if (State.Line->Type == LT_ObjCMethodDecl)
|
2013-02-08 16:22:00 +08:00
|
|
|
State.Stack.back().BreakBeforeParameter = true;
|
|
|
|
|
2013-02-01 19:00:45 +08:00
|
|
|
// Find best solution in solution space.
|
2013-09-05 17:29:45 +08:00
|
|
|
return analyzeSolutionSpace(State, DryRun);
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
2013-02-13 18:46:36 +08:00
|
|
|
/// \brief An edge in the solution space from \c Previous->State to \c State,
|
|
|
|
/// inserting a newline dependent on the \c NewLine.
|
|
|
|
struct StateNode {
|
|
|
|
StateNode(const LineState &State, bool NewLine, StateNode *Previous)
|
2013-02-22 05:33:55 +08:00
|
|
|
: State(State), NewLine(NewLine), Previous(Previous) {}
|
2013-02-13 18:46:36 +08:00
|
|
|
LineState State;
|
|
|
|
bool NewLine;
|
|
|
|
StateNode *Previous;
|
|
|
|
};
|
|
|
|
|
|
|
|
/// \brief A pair of <penalty, count> that is used to prioritize the BFS on.
|
|
|
|
///
|
|
|
|
/// In case of equal penalties, we want to prefer states that were inserted
|
|
|
|
/// first. During state generation we make sure that we insert states first
|
|
|
|
/// that break the line as late as possible.
|
|
|
|
typedef std::pair<unsigned, unsigned> OrderedPenalty;
|
2013-02-01 19:00:45 +08:00
|
|
|
|
2013-02-13 18:46:36 +08:00
|
|
|
/// \brief An item in the prioritized BFS search queue. The \c StateNode's
|
|
|
|
/// \c State has the given \c OrderedPenalty.
|
|
|
|
typedef std::pair<OrderedPenalty, StateNode *> QueueItem;
|
|
|
|
|
|
|
|
/// \brief The BFS queue type.
|
|
|
|
typedef std::priority_queue<QueueItem, std::vector<QueueItem>,
|
|
|
|
std::greater<QueueItem> > QueueType;
|
2013-02-01 19:00:45 +08:00
|
|
|
|
2013-11-06 03:10:03 +08:00
|
|
|
/// \brief Get the offset of the line relatively to the level.
|
|
|
|
///
|
|
|
|
/// For example, 'public:' labels in classes are offset by 1 or 2
|
|
|
|
/// characters to the left from their level.
|
|
|
|
int getIndentOffset(const FormatToken &RootToken) {
|
|
|
|
if (RootToken.isAccessSpecifier(false) || RootToken.isObjCAccessSpecifier())
|
|
|
|
return Style.AccessModifierOffset;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// \brief Add a new line and the required indent before the first Token
|
|
|
|
/// of the \c UnwrappedLine if there was no structural parsing error.
|
|
|
|
void formatFirstToken(FormatToken &RootToken,
|
|
|
|
const AnnotatedLine *PreviousLine, unsigned IndentLevel,
|
|
|
|
unsigned Indent, bool InPPDirective) {
|
|
|
|
unsigned Newlines =
|
|
|
|
std::min(RootToken.NewlinesBefore, Style.MaxEmptyLinesToKeep + 1);
|
|
|
|
// Remove empty lines before "}" where applicable.
|
|
|
|
if (RootToken.is(tok::r_brace) &&
|
|
|
|
(!RootToken.Next ||
|
|
|
|
(RootToken.Next->is(tok::semi) && !RootToken.Next->Next)))
|
|
|
|
Newlines = std::min(Newlines, 1u);
|
|
|
|
if (Newlines == 0 && !RootToken.IsFirst)
|
|
|
|
Newlines = 1;
|
2014-04-11 20:27:47 +08:00
|
|
|
if (RootToken.IsFirst && !RootToken.HasUnescapedNewline)
|
|
|
|
Newlines = 0;
|
2013-11-06 03:10:03 +08:00
|
|
|
|
2014-03-21 20:58:53 +08:00
|
|
|
// Remove empty lines after "{".
|
2014-03-21 21:43:14 +08:00
|
|
|
if (!Style.KeepEmptyLinesAtTheStartOfBlocks && PreviousLine &&
|
|
|
|
PreviousLine->Last->is(tok::l_brace) &&
|
2014-03-21 21:03:33 +08:00
|
|
|
PreviousLine->First->isNot(tok::kw_namespace))
|
2014-03-21 20:58:53 +08:00
|
|
|
Newlines = 1;
|
|
|
|
|
2013-11-06 03:10:03 +08:00
|
|
|
// Insert extra new line before access specifiers.
|
|
|
|
if (PreviousLine && PreviousLine->Last->isOneOf(tok::semi, tok::r_brace) &&
|
|
|
|
RootToken.isAccessSpecifier() && RootToken.NewlinesBefore == 1)
|
|
|
|
++Newlines;
|
|
|
|
|
|
|
|
// Remove empty lines after access specifiers.
|
|
|
|
if (PreviousLine && PreviousLine->First->isAccessSpecifier())
|
|
|
|
Newlines = std::min(1u, Newlines);
|
|
|
|
|
2013-11-21 00:33:05 +08:00
|
|
|
Whitespaces->replaceWhitespace(RootToken, Newlines, IndentLevel, Indent,
|
|
|
|
Indent, InPPDirective &&
|
|
|
|
!RootToken.HasUnescapedNewline);
|
2013-11-06 03:10:03 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
/// \brief Get the indent of \p Level from \p IndentForLevel.
|
|
|
|
///
|
|
|
|
/// \p IndentForLevel must contain the indent for the level \c l
|
|
|
|
/// at \p IndentForLevel[l], or a value < 0 if the indent for
|
|
|
|
/// that level is unknown.
|
|
|
|
unsigned getIndent(const std::vector<int> IndentForLevel, unsigned Level) {
|
|
|
|
if (IndentForLevel[Level] != -1)
|
|
|
|
return IndentForLevel[Level];
|
|
|
|
if (Level == 0)
|
|
|
|
return 0;
|
|
|
|
return getIndent(IndentForLevel, Level - 1) + Style.IndentWidth;
|
|
|
|
}
|
|
|
|
|
|
|
|
void join(AnnotatedLine &A, const AnnotatedLine &B) {
|
|
|
|
assert(!A.Last->Next);
|
|
|
|
assert(!B.First->Previous);
|
2013-11-25 19:08:59 +08:00
|
|
|
if (B.Affected)
|
|
|
|
A.Affected = true;
|
2013-11-06 03:10:03 +08:00
|
|
|
A.Last->Next = B.First;
|
|
|
|
B.First->Previous = A.Last;
|
2013-11-09 01:33:27 +08:00
|
|
|
B.First->CanBreakBefore = true;
|
2013-11-06 03:10:03 +08:00
|
|
|
unsigned LengthA = A.Last->TotalLength + B.First->SpacesRequiredBefore;
|
|
|
|
for (FormatToken *Tok = B.First; Tok; Tok = Tok->Next) {
|
|
|
|
Tok->TotalLength += LengthA;
|
|
|
|
A.Last = Tok;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
unsigned getColumnLimit(bool InPPDirective) const {
|
|
|
|
// In preprocessor directives reserve two chars for trailing " \"
|
|
|
|
return Style.ColumnLimit - (InPPDirective ? 2 : 0);
|
|
|
|
}
|
|
|
|
|
2014-05-22 19:47:01 +08:00
|
|
|
struct CompareLineStatePointers {
|
|
|
|
bool operator()(LineState *obj1, LineState *obj2) const {
|
|
|
|
return *obj1 < *obj2;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-02-01 19:00:45 +08:00
|
|
|
/// \brief Analyze the entire solution space starting from \p InitialState.
|
2012-12-04 02:12:45 +08:00
|
|
|
///
|
2013-02-01 19:00:45 +08:00
|
|
|
/// This implements a variant of Dijkstra's algorithm on the graph that spans
|
|
|
|
/// the solution space (\c LineStates are the nodes). The algorithm tries to
|
|
|
|
/// find the shortest path (the one with lowest penalty) from \p InitialState
|
2013-09-05 17:29:45 +08:00
|
|
|
/// to a state where all tokens are placed. Returns the penalty.
|
|
|
|
///
|
|
|
|
/// If \p DryRun is \c false, directly applies the changes.
|
|
|
|
unsigned analyzeSolutionSpace(LineState &InitialState, bool DryRun = false) {
|
2014-05-22 19:47:01 +08:00
|
|
|
std::set<LineState *, CompareLineStatePointers> Seen;
|
2013-02-13 18:46:36 +08:00
|
|
|
|
2013-11-06 03:10:03 +08:00
|
|
|
// Increasing count of \c StateNode items we have created. This is used to
|
|
|
|
// create a deterministic order independent of the container.
|
|
|
|
unsigned Count = 0;
|
|
|
|
QueueType Queue;
|
|
|
|
|
2013-02-01 19:00:45 +08:00
|
|
|
// Insert start element into queue.
|
2013-02-14 22:26:07 +08:00
|
|
|
StateNode *Node =
|
2014-05-09 16:15:10 +08:00
|
|
|
new (Allocator.Allocate()) StateNode(InitialState, false, nullptr);
|
2013-02-13 18:46:36 +08:00
|
|
|
Queue.push(QueueItem(OrderedPenalty(0, Count), Node));
|
|
|
|
++Count;
|
2013-02-01 19:00:45 +08:00
|
|
|
|
2013-09-05 17:29:45 +08:00
|
|
|
unsigned Penalty = 0;
|
|
|
|
|
2013-02-01 19:00:45 +08:00
|
|
|
// While not empty, take first element and follow edges.
|
|
|
|
while (!Queue.empty()) {
|
2013-09-05 17:29:45 +08:00
|
|
|
Penalty = Queue.top().first.first;
|
2013-02-14 22:26:07 +08:00
|
|
|
StateNode *Node = Queue.top().second;
|
2014-05-09 16:15:10 +08:00
|
|
|
if (!Node->State.NextToken) {
|
2013-05-10 19:56:10 +08:00
|
|
|
DEBUG(llvm::dbgs() << "\n---\nPenalty for line: " << Penalty << "\n");
|
2013-02-01 19:00:45 +08:00
|
|
|
break;
|
2013-02-04 15:21:18 +08:00
|
|
|
}
|
2013-02-13 18:46:36 +08:00
|
|
|
Queue.pop();
|
2013-02-01 19:00:45 +08:00
|
|
|
|
2013-05-22 13:27:42 +08:00
|
|
|
// Cut off the analysis of certain solutions if the analysis gets too
|
|
|
|
// complex. See description of IgnoreStackForComparison.
|
|
|
|
if (Count > 10000)
|
|
|
|
Node->State.IgnoreStackForComparison = true;
|
|
|
|
|
2014-05-22 19:47:01 +08:00
|
|
|
if (!Seen.insert(&Node->State).second)
|
2013-02-13 18:46:36 +08:00
|
|
|
// State already examined with lower penalty.
|
|
|
|
continue;
|
2013-02-01 19:00:45 +08:00
|
|
|
|
2013-10-12 05:25:45 +08:00
|
|
|
FormatDecision LastFormat = Node->State.NextToken->Decision;
|
|
|
|
if (LastFormat == FD_Unformatted || LastFormat == FD_Continue)
|
2013-11-06 03:10:03 +08:00
|
|
|
addNextStateToQueue(Penalty, Node, /*NewLine=*/false, &Count, &Queue);
|
2013-10-12 05:25:45 +08:00
|
|
|
if (LastFormat == FD_Unformatted || LastFormat == FD_Break)
|
2013-11-06 03:10:03 +08:00
|
|
|
addNextStateToQueue(Penalty, Node, /*NewLine=*/true, &Count, &Queue);
|
2013-02-01 19:00:45 +08:00
|
|
|
}
|
|
|
|
|
2013-10-12 05:25:45 +08:00
|
|
|
if (Queue.empty()) {
|
2013-02-01 19:00:45 +08:00
|
|
|
// We were unable to find a solution, do nothing.
|
|
|
|
// FIXME: Add diagnostic?
|
2013-10-12 05:25:45 +08:00
|
|
|
DEBUG(llvm::dbgs() << "Could not find a solution.\n");
|
2013-09-05 17:29:45 +08:00
|
|
|
return 0;
|
2013-10-12 05:25:45 +08:00
|
|
|
}
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-02-01 19:00:45 +08:00
|
|
|
// Reconstruct the solution.
|
2013-09-05 17:29:45 +08:00
|
|
|
if (!DryRun)
|
|
|
|
reconstructPath(InitialState, Queue.top().second);
|
|
|
|
|
2013-05-10 19:56:10 +08:00
|
|
|
DEBUG(llvm::dbgs() << "Total number of analyzed states: " << Count << "\n");
|
|
|
|
DEBUG(llvm::dbgs() << "---\n");
|
2013-09-05 17:29:45 +08:00
|
|
|
|
|
|
|
return Penalty;
|
2013-02-13 18:46:36 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
void reconstructPath(LineState &State, StateNode *Current) {
|
2013-05-29 23:10:11 +08:00
|
|
|
std::deque<StateNode *> Path;
|
|
|
|
// We do not need a break before the initial token.
|
|
|
|
while (Current->Previous) {
|
|
|
|
Path.push_front(Current);
|
|
|
|
Current = Current->Previous;
|
|
|
|
}
|
|
|
|
for (std::deque<StateNode *>::iterator I = Path.begin(), E = Path.end();
|
|
|
|
I != E; ++I) {
|
2013-09-05 17:29:45 +08:00
|
|
|
unsigned Penalty = 0;
|
|
|
|
formatChildren(State, (*I)->NewLine, /*DryRun=*/false, Penalty);
|
|
|
|
Penalty += Indenter->addTokenToState(State, (*I)->NewLine, false);
|
|
|
|
|
2013-05-29 23:10:11 +08:00
|
|
|
DEBUG({
|
|
|
|
if ((*I)->NewLine) {
|
clang-format: Add column layout formatting for braced lists
With this patch, braced lists (with more than 3 elements are formatted in a
column layout if possible). E.g.:
static const uint16_t CallerSavedRegs64Bit[] = {
X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
X86::R8, X86::R9, X86::R10, X86::R11, 0
};
Required other changes:
- FormatTokens can now have a special role that contains extra data and can do
special formattings. A comma separated list is currently the only
implementation.
- Move penalty calculation entirely into ContinuationIndenter (there was a last
piece still in UnwrappedLineFormatter).
Review: http://llvm-reviews.chandlerc.com/D1457
llvm-svn: 189018
2013-08-22 23:00:41 +08:00
|
|
|
llvm::dbgs() << "Penalty for placing "
|
2013-05-29 23:10:11 +08:00
|
|
|
<< (*I)->Previous->State.NextToken->Tok.getName() << ": "
|
clang-format: Add column layout formatting for braced lists
With this patch, braced lists (with more than 3 elements are formatted in a
column layout if possible). E.g.:
static const uint16_t CallerSavedRegs64Bit[] = {
X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
X86::R8, X86::R9, X86::R10, X86::R11, 0
};
Required other changes:
- FormatTokens can now have a special role that contains extra data and can do
special formattings. A comma separated list is currently the only
implementation.
- Move penalty calculation entirely into ContinuationIndenter (there was a last
piece still in UnwrappedLineFormatter).
Review: http://llvm-reviews.chandlerc.com/D1457
llvm-svn: 189018
2013-08-22 23:00:41 +08:00
|
|
|
<< Penalty << "\n";
|
2013-05-29 23:10:11 +08:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
2013-02-01 19:00:45 +08:00
|
|
|
}
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-02-13 18:54:19 +08:00
|
|
|
/// \brief Add the following state to the analysis queue \c Queue.
|
2013-02-01 19:00:45 +08:00
|
|
|
///
|
2013-02-13 18:54:19 +08:00
|
|
|
/// Assume the current state is \p PreviousNode and has been reached with a
|
2013-02-01 19:00:45 +08:00
|
|
|
/// penalty of \p Penalty. Insert a line break if \p NewLine is \c true.
|
2013-02-13 18:54:19 +08:00
|
|
|
void addNextStateToQueue(unsigned Penalty, StateNode *PreviousNode,
|
2013-11-06 03:10:03 +08:00
|
|
|
bool NewLine, unsigned *Count, QueueType *Queue) {
|
2013-08-16 19:20:30 +08:00
|
|
|
if (NewLine && !Indenter->canBreak(PreviousNode->State))
|
2013-02-01 19:00:45 +08:00
|
|
|
return;
|
2013-08-16 19:20:30 +08:00
|
|
|
if (!NewLine && Indenter->mustBreak(PreviousNode->State))
|
2013-02-01 19:00:45 +08:00
|
|
|
return;
|
2013-02-13 18:46:36 +08:00
|
|
|
|
|
|
|
StateNode *Node = new (Allocator.Allocate())
|
|
|
|
StateNode(PreviousNode->State, NewLine, PreviousNode);
|
2013-09-05 17:29:45 +08:00
|
|
|
if (!formatChildren(Node->State, NewLine, /*DryRun=*/true, Penalty))
|
|
|
|
return;
|
|
|
|
|
2013-08-16 19:20:30 +08:00
|
|
|
Penalty += Indenter->addTokenToState(Node->State, NewLine, true);
|
2013-02-13 18:46:36 +08:00
|
|
|
|
2013-11-06 03:10:03 +08:00
|
|
|
Queue->push(QueueItem(OrderedPenalty(Penalty, *Count), Node));
|
|
|
|
++(*Count);
|
2013-02-01 19:00:45 +08:00
|
|
|
}
|
2012-12-04 02:12:45 +08:00
|
|
|
|
2013-09-05 18:48:50 +08:00
|
|
|
/// \brief If the \p State's next token is an r_brace closing a nested block,
|
|
|
|
/// format the nested block before it.
|
2013-09-05 17:29:45 +08:00
|
|
|
///
|
|
|
|
/// Returns \c true if all children could be placed successfully and adapts
|
|
|
|
/// \p Penalty as well as \p State. If \p DryRun is false, also directly
|
|
|
|
/// creates changes using \c Whitespaces.
|
|
|
|
///
|
|
|
|
/// The crucial idea here is that children always get formatted upon
|
|
|
|
/// encountering the closing brace right after the nested block. Now, if we
|
|
|
|
/// are currently trying to keep the "}" on the same line (i.e. \p NewLine is
|
|
|
|
/// \c false), the entire block has to be kept on the same line (which is only
|
|
|
|
/// possible if it fits on the line, only contains a single statement, etc.
|
|
|
|
///
|
|
|
|
/// If \p NewLine is true, we format the nested block on separate lines, i.e.
|
|
|
|
/// break after the "{", format all lines with correct indentation and the put
|
|
|
|
/// the closing "}" on yet another new line.
|
|
|
|
///
|
|
|
|
/// This enables us to keep the simple structure of the
|
|
|
|
/// \c UnwrappedLineFormatter, where we only have two options for each token:
|
|
|
|
/// break or don't break.
|
|
|
|
bool formatChildren(LineState &State, bool NewLine, bool DryRun,
|
|
|
|
unsigned &Penalty) {
|
2013-11-06 03:10:03 +08:00
|
|
|
FormatToken &Previous = *State.NextToken->Previous;
|
2013-10-21 01:28:32 +08:00
|
|
|
const FormatToken *LBrace = State.NextToken->getPreviousNonComment();
|
|
|
|
if (!LBrace || LBrace->isNot(tok::l_brace) ||
|
|
|
|
LBrace->BlockKind != BK_Block || Previous.Children.size() == 0)
|
2013-09-05 18:48:50 +08:00
|
|
|
// The previous token does not open a block. Nothing to do. We don't
|
|
|
|
// assert so that we can simply call this function for all tokens.
|
2013-09-06 16:54:24 +08:00
|
|
|
return true;
|
2013-09-05 17:29:45 +08:00
|
|
|
|
|
|
|
if (NewLine) {
|
2014-05-21 20:51:23 +08:00
|
|
|
int AdditionalIndent = 0;
|
|
|
|
if (State.Stack.size() < 2 ||
|
|
|
|
!State.Stack[State.Stack.size() - 2].JSFunctionInlined) {
|
|
|
|
AdditionalIndent = State.Stack.back().Indent -
|
|
|
|
Previous.Children[0]->Level * Style.IndentWidth;
|
|
|
|
}
|
|
|
|
|
2013-11-28 23:58:55 +08:00
|
|
|
Penalty += format(Previous.Children, DryRun, AdditionalIndent,
|
|
|
|
/*FixBadIndentation=*/true);
|
2013-09-05 17:29:45 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2013-11-06 03:10:03 +08:00
|
|
|
// Cannot merge multiple statements into a single line.
|
2013-10-21 01:28:32 +08:00
|
|
|
if (Previous.Children.size() > 1)
|
2013-11-21 00:33:05 +08:00
|
|
|
return false;
|
2013-09-05 17:29:45 +08:00
|
|
|
|
2014-04-09 20:21:48 +08:00
|
|
|
// Cannot merge into one line if this line ends on a comment.
|
|
|
|
if (Previous.is(tok::comment))
|
|
|
|
return false;
|
|
|
|
|
2013-09-05 17:29:45 +08:00
|
|
|
// We can't put the closing "}" on a line with a trailing comment.
|
2013-10-21 01:28:32 +08:00
|
|
|
if (Previous.Children[0]->Last->isTrailingComment())
|
2013-09-05 17:29:45 +08:00
|
|
|
return false;
|
|
|
|
|
2014-04-15 16:28:06 +08:00
|
|
|
// If the child line exceeds the column limit, we wouldn't want to merge it.
|
|
|
|
// We add +2 for the trailing " }".
|
|
|
|
if (Style.ColumnLimit > 0 &&
|
|
|
|
Previous.Children[0]->Last->TotalLength + State.Column + 2 >
|
|
|
|
Style.ColumnLimit)
|
|
|
|
return false;
|
|
|
|
|
2013-09-05 17:29:45 +08:00
|
|
|
if (!DryRun) {
|
2013-09-28 00:14:22 +08:00
|
|
|
Whitespaces->replaceWhitespace(
|
2013-10-21 01:28:32 +08:00
|
|
|
*Previous.Children[0]->First,
|
2013-10-14 08:46:35 +08:00
|
|
|
/*Newlines=*/0, /*IndentLevel=*/0, /*Spaces=*/1,
|
2013-09-28 00:14:22 +08:00
|
|
|
/*StartOfTokenColumn=*/State.Column, State.Line->InPPDirective);
|
2013-09-05 17:29:45 +08:00
|
|
|
}
|
2013-11-06 03:10:03 +08:00
|
|
|
Penalty += format(*Previous.Children[0], State.Column + 1, DryRun);
|
2013-09-05 17:29:45 +08:00
|
|
|
|
2013-10-21 01:28:32 +08:00
|
|
|
State.Column += 1 + Previous.Children[0]->Last->TotalLength;
|
2013-09-05 17:29:45 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2013-08-16 19:20:30 +08:00
|
|
|
ContinuationIndenter *Indenter;
|
2013-09-05 17:29:45 +08:00
|
|
|
WhitespaceManager *Whitespaces;
|
2012-12-04 02:12:45 +08:00
|
|
|
FormatStyle Style;
|
2013-11-07 07:12:09 +08:00
|
|
|
LineJoiner Joiner;
|
2013-02-13 18:54:19 +08:00
|
|
|
|
|
|
|
llvm::SpecificBumpPtrAllocator<StateNode> Allocator;
|
2014-04-15 16:13:47 +08:00
|
|
|
|
|
|
|
// Cache to store the penalty of formatting a vector of AnnotatedLines
|
|
|
|
// starting from a specific additional offset. Improves performance if there
|
|
|
|
// are many nested blocks.
|
|
|
|
std::map<std::pair<const SmallVectorImpl<AnnotatedLine *> *, unsigned>,
|
|
|
|
unsigned> PenaltyCache;
|
2012-12-04 02:12:45 +08:00
|
|
|
};
|
|
|
|
|
2013-05-28 19:55:06 +08:00
|
|
|
class FormatTokenLexer {
|
2012-12-08 00:15:44 +08:00
|
|
|
public:
|
2013-08-29 23:21:40 +08:00
|
|
|
FormatTokenLexer(Lexer &Lex, SourceManager &SourceMgr, FormatStyle &Style,
|
2013-06-05 22:09:10 +08:00
|
|
|
encoding::Encoding Encoding)
|
2014-05-09 16:15:10 +08:00
|
|
|
: FormatTok(nullptr), IsFirstToken(true), GreaterStashed(false),
|
|
|
|
Column(0), TrailingWhitespace(0), Lex(Lex), SourceMgr(SourceMgr),
|
|
|
|
Style(Style), IdentTable(getFormattingLangOpts()), Encoding(Encoding),
|
2014-04-14 17:14:11 +08:00
|
|
|
FirstInLineIndex(0) {
|
2012-12-08 00:15:44 +08:00
|
|
|
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());
|
2013-11-21 20:43:57 +08:00
|
|
|
tryMergePreviousTokens();
|
2014-04-14 17:14:11 +08:00
|
|
|
if (Tokens.back()->NewlinesBefore > 0)
|
|
|
|
FirstInLineIndex = Tokens.size() - 1;
|
2013-05-28 19:55:06 +08:00
|
|
|
} while (Tokens.back()->Tok.isNot(tok::eof));
|
|
|
|
return Tokens;
|
|
|
|
}
|
|
|
|
|
|
|
|
IdentifierTable &getIdentTable() { return IdentTable; }
|
|
|
|
|
|
|
|
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;
|
2013-11-29 23:19:43 +08:00
|
|
|
|
|
|
|
if (Style.Language == FormatStyle::LK_JavaScript) {
|
2014-05-12 19:29:50 +08:00
|
|
|
if (tryMergeEscapeSequence())
|
|
|
|
return;
|
2014-05-08 15:01:45 +08:00
|
|
|
if (tryMergeJSRegexLiteral())
|
|
|
|
return;
|
|
|
|
|
2014-05-09 21:11:16 +08:00
|
|
|
static tok::TokenKind JSIdentity[] = { tok::equalequal, tok::equal };
|
|
|
|
static tok::TokenKind JSNotIdentity[] = { tok::exclaimequal, tok::equal };
|
|
|
|
static tok::TokenKind JSShiftEqual[] = { tok::greater, tok::greater,
|
|
|
|
tok::greaterequal };
|
2014-05-19 15:27:02 +08:00
|
|
|
static tok::TokenKind JSRightArrow[] = { tok::equal, tok::greater };
|
2013-11-29 23:19:43 +08:00
|
|
|
// FIXME: We probably need to change token type to mimic operator with the
|
|
|
|
// correct priority.
|
|
|
|
if (tryMergeTokens(JSIdentity))
|
|
|
|
return;
|
|
|
|
if (tryMergeTokens(JSNotIdentity))
|
|
|
|
return;
|
|
|
|
if (tryMergeTokens(JSShiftEqual))
|
|
|
|
return;
|
2014-05-19 15:27:02 +08:00
|
|
|
if (tryMergeTokens(JSRightArrow))
|
|
|
|
return;
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
2013-11-21 20:43:57 +08:00
|
|
|
}
|
|
|
|
|
2013-11-29 23:19:43 +08:00
|
|
|
bool tryMergeTokens(ArrayRef<tok::TokenKind> Kinds) {
|
|
|
|
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) {
|
|
|
|
if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
|
|
|
|
First[i]->WhitespaceRange.getEnd())
|
|
|
|
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;
|
2013-11-21 20:43:57 +08:00
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2014-05-12 19:29:50 +08:00
|
|
|
// Tries to merge an escape sequence, i.e. a "\\" and the following
|
2014-05-15 09:35:53 +08:00
|
|
|
// character. Use e.g. inside JavaScript regex literals.
|
2014-05-12 19:29:50 +08:00
|
|
|
bool tryMergeEscapeSequence() {
|
|
|
|
if (Tokens.size() < 2)
|
|
|
|
return false;
|
|
|
|
FormatToken *Previous = Tokens[Tokens.size() - 2];
|
|
|
|
if (Previous->isNot(tok::unknown) || Previous->TokenText != "\\" ||
|
|
|
|
Tokens.back()->NewlinesBefore != 0)
|
|
|
|
return false;
|
|
|
|
Previous->ColumnWidth += Tokens.back()->ColumnWidth;
|
|
|
|
StringRef Text = Previous->TokenText;
|
|
|
|
Previous->TokenText =
|
|
|
|
StringRef(Text.data(), Text.size() + Tokens.back()->TokenText.size());
|
|
|
|
Tokens.resize(Tokens.size() - 1);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2014-05-08 15:01:45 +08:00
|
|
|
// Try to determine whether the current token ends a JavaScript regex literal.
|
|
|
|
// We heuristically assume that this is a regex literal if we find two
|
|
|
|
// unescaped slashes on a line and the token before the first slash is one of
|
2014-05-08 15:45:18 +08:00
|
|
|
// "(;,{}![:?", a binary operator or 'return', as those cannot be followed by
|
|
|
|
// a division.
|
2014-05-08 15:01:45 +08:00
|
|
|
bool tryMergeJSRegexLiteral() {
|
2014-05-09 21:11:16 +08:00
|
|
|
if (Tokens.size() < 2 || Tokens.back()->isNot(tok::slash) ||
|
2014-05-12 19:29:50 +08:00
|
|
|
(Tokens[Tokens.size() - 2]->is(tok::unknown) &&
|
|
|
|
Tokens[Tokens.size() - 2]->TokenText == "\\"))
|
2014-05-08 15:01:45 +08:00
|
|
|
return false;
|
2014-05-09 21:11:16 +08:00
|
|
|
unsigned TokenCount = 0;
|
|
|
|
unsigned LastColumn = Tokens.back()->OriginalColumn;
|
|
|
|
for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
|
|
|
|
++TokenCount;
|
|
|
|
if (I[0]->is(tok::slash) && I + 1 != E &&
|
|
|
|
(I[1]->isOneOf(tok::l_paren, tok::semi, tok::l_brace, tok::r_brace,
|
|
|
|
tok::exclaim, tok::l_square, tok::colon, tok::comma,
|
|
|
|
tok::question, tok::kw_return) ||
|
|
|
|
I[1]->isBinaryOperator())) {
|
|
|
|
Tokens.resize(Tokens.size() - TokenCount);
|
|
|
|
Tokens.back()->Tok.setKind(tok::unknown);
|
|
|
|
Tokens.back()->Type = TT_RegexLiteral;
|
|
|
|
Tokens.back()->ColumnWidth += LastColumn - I[0]->OriginalColumn;
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// There can't be a newline inside a regex literal.
|
|
|
|
if (I[0]->NewlinesBefore > 0)
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return false;
|
2014-05-08 15:01:45 +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);
|
|
|
|
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2013-05-28 19:55:06 +08:00
|
|
|
FormatToken *getNextToken() {
|
2012-12-08 00:15:44 +08:00
|
|
|
if (GreaterStashed) {
|
2013-05-28 21:42:28 +08:00
|
|
|
// Create a synthesized second '>' token.
|
2013-08-29 23:21:40 +08:00
|
|
|
// FIXME: Increment Column and set OriginalColumn.
|
2013-05-28 21:42:28 +08:00
|
|
|
Token Greater = FormatTok->Tok;
|
|
|
|
FormatTok = new (Allocator.Allocate()) FormatToken;
|
|
|
|
FormatTok->Tok = Greater;
|
2013-05-23 18:56:37 +08:00
|
|
|
SourceLocation GreaterLocation =
|
2013-05-28 19:55:06 +08:00
|
|
|
FormatTok->Tok.getLocation().getLocWithOffset(1);
|
|
|
|
FormatTok->WhitespaceRange =
|
|
|
|
SourceRange(GreaterLocation, GreaterLocation);
|
2013-06-08 01:45:07 +08:00
|
|
|
FormatTok->TokenText = ">";
|
2013-09-10 17:38:25 +08:00
|
|
|
FormatTok->ColumnWidth = 1;
|
2012-12-08 00:15:44 +08:00
|
|
|
GreaterStashed = false;
|
|
|
|
return FormatTok;
|
|
|
|
}
|
|
|
|
|
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)) {
|
2013-08-29 23:21:40 +08:00
|
|
|
for (int i = 0, e = FormatTok->TokenText.size(); i != e; ++i) {
|
|
|
|
switch (FormatTok->TokenText[i]) {
|
|
|
|
case '\n':
|
|
|
|
++FormatTok->NewlinesBefore;
|
|
|
|
// FIXME: This is technically incorrect, as it could also
|
|
|
|
// be a literal backslash at the end of the line.
|
2013-09-11 20:25:57 +08:00
|
|
|
if (i == 0 || (FormatTok->TokenText[i - 1] != '\\' &&
|
|
|
|
(FormatTok->TokenText[i - 1] != '\r' || i == 1 ||
|
|
|
|
FormatTok->TokenText[i - 2] != '\\')))
|
2013-08-29 23:21:40 +08:00
|
|
|
FormatTok->HasUnescapedNewline = true;
|
|
|
|
FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
|
|
|
|
Column = 0;
|
|
|
|
break;
|
2013-10-12 03:45:02 +08:00
|
|
|
case '\r':
|
|
|
|
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 '\\':
|
|
|
|
++Column;
|
|
|
|
if (i + 1 == e || (FormatTok->TokenText[i + 1] != '\r' &&
|
|
|
|
FormatTok->TokenText[i + 1] != '\n'))
|
|
|
|
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
|
|
|
++Column;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-10-12 03:45:02 +08:00
|
|
|
if (FormatTok->Type == TT_ImplicitStringLiteral)
|
|
|
|
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;
|
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());
|
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;
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
2014-04-01 20:55:11 +08:00
|
|
|
FormatTok->IsForEachMacro =
|
|
|
|
std::binary_search(ForEachMacros.begin(), ForEachMacros.end(),
|
|
|
|
FormatTok->Tok.getIdentifierInfo());
|
|
|
|
|
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;
|
2012-12-08 00:15:44 +08:00
|
|
|
bool GreaterStashed;
|
2013-08-29 23:21:40 +08:00
|
|
|
unsigned Column;
|
2013-05-27 23:23:34 +08:00
|
|
|
unsigned TrailingWhitespace;
|
2012-12-08 00:15:44 +08:00
|
|
|
Lexer &Lex;
|
|
|
|
SourceManager &SourceMgr;
|
2013-08-29 23:21:40 +08:00
|
|
|
FormatStyle &Style;
|
2012-12-08 00:15:44 +08:00
|
|
|
IdentifierTable IdentTable;
|
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
|
|
|
|
2013-07-17 04:28:33 +08:00
|
|
|
void readRawToken(FormatToken &Tok) {
|
|
|
|
Lex.LexFromRawLexer(Tok.Tok);
|
|
|
|
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 == "''") {
|
|
|
|
Tok.Tok.setKind(tok::char_constant);
|
|
|
|
}
|
2013-07-17 04:28:33 +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++";
|
|
|
|
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";
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
class Formatter : public UnwrappedLineConsumer {
|
|
|
|
public:
|
2013-05-15 16:14:19 +08:00
|
|
|
Formatter(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
|
2012-12-04 02:12:45 +08:00
|
|
|
const std::vector<CharSourceRange> &Ranges)
|
2013-05-15 16:14:19 +08:00
|
|
|
: Style(Style), Lex(Lex), SourceMgr(SourceMgr),
|
2013-09-11 20:25:57 +08:00
|
|
|
Whitespaces(SourceMgr, Style, inputUsesCRLF(Lex.getBuffer())),
|
2013-11-06 03:10:03 +08:00
|
|
|
Ranges(Ranges.begin(), Ranges.end()), UnwrappedLines(1),
|
2013-10-12 05:25:45 +08:00
|
|
|
Encoding(encoding::detectEncoding(Lex.getBuffer())) {
|
2013-07-15 22:33:14 +08:00
|
|
|
DEBUG(llvm::dbgs() << "File encoding: "
|
|
|
|
<< (Encoding == encoding::Encoding_UTF8 ? "UTF8"
|
|
|
|
: "unknown")
|
|
|
|
<< "\n");
|
2013-11-29 23:19:43 +08:00
|
|
|
DEBUG(llvm::dbgs() << "Language: " << getLanguageName(Style.Language)
|
|
|
|
<< "\n");
|
2013-06-05 22:09:10 +08:00
|
|
|
}
|
2012-12-04 02:12:45 +08:00
|
|
|
|
|
|
|
tooling::Replacements format() {
|
2013-10-12 05:25:45 +08:00
|
|
|
tooling::Replacements Result;
|
2013-08-29 23:21:40 +08:00
|
|
|
FormatTokenLexer Tokens(Lex, SourceMgr, Style, Encoding);
|
2013-05-28 19:55:06 +08:00
|
|
|
|
|
|
|
UnwrappedLineParser Parser(Style, Tokens.lex(), *this);
|
2013-04-12 22:13:36 +08:00
|
|
|
bool StructuralError = 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;
|
|
|
|
for (unsigned i = 0, e = UnwrappedLines[Run].size(); i != e; ++i) {
|
|
|
|
AnnotatedLines.push_back(new AnnotatedLine(UnwrappedLines[Run][i]));
|
|
|
|
}
|
|
|
|
tooling::Replacements RunResult =
|
|
|
|
format(AnnotatedLines, StructuralError, Tokens);
|
|
|
|
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());
|
|
|
|
Whitespaces.reset();
|
|
|
|
}
|
|
|
|
return Result;
|
|
|
|
}
|
|
|
|
|
|
|
|
tooling::Replacements format(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
|
|
|
|
bool StructuralError, FormatTokenLexer &Tokens) {
|
2013-06-05 22:09:10 +08:00
|
|
|
TokenAnnotator Annotator(Style, Tokens.getIdentTable().get("in"));
|
2013-11-06 03:10:03 +08:00
|
|
|
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
|
|
|
|
Annotator.annotate(*AnnotatedLines[i]);
|
|
|
|
}
|
|
|
|
deriveLocalStyle(AnnotatedLines);
|
|
|
|
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
|
|
|
|
Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
|
2013-01-11 03:49:59 +08:00
|
|
|
}
|
2013-11-25 19:08:59 +08:00
|
|
|
computeAffectedLines(AnnotatedLines.begin(), AnnotatedLines.end());
|
2013-11-06 03:10:03 +08:00
|
|
|
|
|
|
|
Annotator.setCommentLineLevels(AnnotatedLines);
|
|
|
|
ContinuationIndenter Indenter(Style, SourceMgr, Whitespaces, Encoding,
|
|
|
|
BinPackInconclusiveFunctions);
|
2013-11-25 19:08:59 +08:00
|
|
|
UnwrappedLineFormatter Formatter(&Indenter, &Whitespaces, Style);
|
2013-11-06 03:10:03 +08:00
|
|
|
Formatter.format(AnnotatedLines, /*DryRun=*/false);
|
2013-01-18 16:44:07 +08:00
|
|
|
return Whitespaces.generateReplacements();
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2013-11-25 19:08:59 +08:00
|
|
|
// Determines which lines are affected by the SourceRanges given as input.
|
2013-11-28 23:58:55 +08:00
|
|
|
// Returns \c true if at least one line between I and E or one of their
|
|
|
|
// children is affected.
|
2013-11-25 19:08:59 +08:00
|
|
|
bool computeAffectedLines(SmallVectorImpl<AnnotatedLine *>::iterator I,
|
|
|
|
SmallVectorImpl<AnnotatedLine *>::iterator E) {
|
|
|
|
bool SomeLineAffected = false;
|
2014-05-09 16:15:10 +08:00
|
|
|
const AnnotatedLine *PreviousLine = nullptr;
|
2013-11-25 19:08:59 +08:00
|
|
|
while (I != E) {
|
|
|
|
AnnotatedLine *Line = *I;
|
|
|
|
Line->LeadingEmptyLinesAffected = affectsLeadingEmptyLines(*Line->First);
|
|
|
|
|
|
|
|
// If a line is part of a preprocessor directive, it needs to be formatted
|
|
|
|
// if any token within the directive is affected.
|
|
|
|
if (Line->InPPDirective) {
|
|
|
|
FormatToken *Last = Line->Last;
|
|
|
|
SmallVectorImpl<AnnotatedLine *>::iterator PPEnd = I + 1;
|
|
|
|
while (PPEnd != E && !(*PPEnd)->First->HasUnescapedNewline) {
|
|
|
|
Last = (*PPEnd)->Last;
|
|
|
|
++PPEnd;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (affectsTokenRange(*Line->First, *Last,
|
|
|
|
/*IncludeLeadingNewlines=*/false)) {
|
|
|
|
SomeLineAffected = true;
|
|
|
|
markAllAsAffected(I, PPEnd);
|
|
|
|
}
|
|
|
|
I = PPEnd;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2013-11-29 17:27:43 +08:00
|
|
|
if (nonPPLineAffected(Line, PreviousLine))
|
2013-11-25 19:08:59 +08:00
|
|
|
SomeLineAffected = true;
|
|
|
|
|
2013-11-29 17:27:43 +08:00
|
|
|
PreviousLine = Line;
|
2013-11-25 19:08:59 +08:00
|
|
|
++I;
|
|
|
|
}
|
|
|
|
return SomeLineAffected;
|
|
|
|
}
|
|
|
|
|
2013-11-28 23:58:55 +08:00
|
|
|
// Determines whether 'Line' is affected by the SourceRanges given as input.
|
|
|
|
// Returns \c true if line or one if its children is affected.
|
2013-11-29 17:27:43 +08:00
|
|
|
bool nonPPLineAffected(AnnotatedLine *Line,
|
|
|
|
const AnnotatedLine *PreviousLine) {
|
2013-11-28 23:58:55 +08:00
|
|
|
bool SomeLineAffected = false;
|
|
|
|
Line->ChildrenAffected =
|
|
|
|
computeAffectedLines(Line->Children.begin(), Line->Children.end());
|
|
|
|
if (Line->ChildrenAffected)
|
|
|
|
SomeLineAffected = true;
|
|
|
|
|
|
|
|
// Stores whether one of the line's tokens is directly affected.
|
|
|
|
bool SomeTokenAffected = false;
|
|
|
|
// Stores whether we need to look at the leading newlines of the next token
|
|
|
|
// in order to determine whether it was affected.
|
|
|
|
bool IncludeLeadingNewlines = false;
|
|
|
|
|
|
|
|
// Stores whether the first child line of any of this line's tokens is
|
|
|
|
// affected.
|
|
|
|
bool SomeFirstChildAffected = false;
|
|
|
|
|
|
|
|
for (FormatToken *Tok = Line->First; Tok; Tok = Tok->Next) {
|
|
|
|
// Determine whether 'Tok' was affected.
|
|
|
|
if (affectsTokenRange(*Tok, *Tok, IncludeLeadingNewlines))
|
|
|
|
SomeTokenAffected = true;
|
|
|
|
|
|
|
|
// Determine whether the first child of 'Tok' was affected.
|
|
|
|
if (!Tok->Children.empty() && Tok->Children.front()->Affected)
|
|
|
|
SomeFirstChildAffected = true;
|
|
|
|
|
|
|
|
IncludeLeadingNewlines = Tok->Children.empty();
|
|
|
|
}
|
|
|
|
|
|
|
|
// Was this line moved, i.e. has it previously been on the same line as an
|
|
|
|
// affected line?
|
2013-11-29 17:27:43 +08:00
|
|
|
bool LineMoved = PreviousLine && PreviousLine->Affected &&
|
|
|
|
Line->First->NewlinesBefore == 0;
|
|
|
|
|
2014-05-09 21:11:16 +08:00
|
|
|
bool IsContinuedComment =
|
|
|
|
Line->First->is(tok::comment) && Line->First->Next == nullptr &&
|
|
|
|
Line->First->NewlinesBefore < 2 && PreviousLine &&
|
|
|
|
PreviousLine->Affected && PreviousLine->Last->is(tok::comment);
|
2013-11-28 23:58:55 +08:00
|
|
|
|
2013-11-29 17:27:43 +08:00
|
|
|
if (SomeTokenAffected || SomeFirstChildAffected || LineMoved ||
|
|
|
|
IsContinuedComment) {
|
2013-11-28 23:58:55 +08:00
|
|
|
Line->Affected = true;
|
|
|
|
SomeLineAffected = true;
|
|
|
|
}
|
|
|
|
return SomeLineAffected;
|
|
|
|
}
|
|
|
|
|
2013-11-25 19:08:59 +08:00
|
|
|
// Marks all lines between I and E as well as all their children as affected.
|
|
|
|
void markAllAsAffected(SmallVectorImpl<AnnotatedLine *>::iterator I,
|
|
|
|
SmallVectorImpl<AnnotatedLine *>::iterator E) {
|
|
|
|
while (I != E) {
|
|
|
|
(*I)->Affected = true;
|
|
|
|
markAllAsAffected((*I)->Children.begin(), (*I)->Children.end());
|
|
|
|
++I;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns true if the range from 'First' to 'Last' intersects with one of the
|
|
|
|
// input ranges.
|
|
|
|
bool affectsTokenRange(const FormatToken &First, const FormatToken &Last,
|
|
|
|
bool IncludeLeadingNewlines) {
|
|
|
|
SourceLocation Start = First.WhitespaceRange.getBegin();
|
|
|
|
if (!IncludeLeadingNewlines)
|
|
|
|
Start = Start.getLocWithOffset(First.LastNewlineOffset);
|
2013-11-25 19:53:05 +08:00
|
|
|
SourceLocation End = Last.getStartOfNonWhitespace();
|
|
|
|
if (Last.TokenText.size() > 0)
|
|
|
|
End = End.getLocWithOffset(Last.TokenText.size() - 1);
|
2013-11-25 19:08:59 +08:00
|
|
|
CharSourceRange Range = CharSourceRange::getCharRange(Start, End);
|
|
|
|
return affectsCharSourceRange(Range);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns true if one of the input ranges intersect the leading empty lines
|
|
|
|
// before 'Tok'.
|
|
|
|
bool affectsLeadingEmptyLines(const FormatToken &Tok) {
|
|
|
|
CharSourceRange EmptyLineRange = CharSourceRange::getCharRange(
|
|
|
|
Tok.WhitespaceRange.getBegin(),
|
|
|
|
Tok.WhitespaceRange.getBegin().getLocWithOffset(Tok.LastNewlineOffset));
|
|
|
|
return affectsCharSourceRange(EmptyLineRange);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Returns true if 'Range' intersects with one of the input ranges.
|
|
|
|
bool affectsCharSourceRange(const CharSourceRange &Range) {
|
|
|
|
for (SmallVectorImpl<CharSourceRange>::const_iterator I = Ranges.begin(),
|
|
|
|
E = Ranges.end();
|
|
|
|
I != E; ++I) {
|
|
|
|
if (!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), I->getBegin()) &&
|
|
|
|
!SourceMgr.isBeforeInTranslationUnit(I->getEnd(), Range.getBegin()))
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2013-09-11 20:25:57 +08:00
|
|
|
static bool inputUsesCRLF(StringRef Text) {
|
|
|
|
return Text.count('\r') * 2 > Text.count('\n');
|
|
|
|
}
|
|
|
|
|
2013-10-12 05:25:45 +08:00
|
|
|
void
|
|
|
|
deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
|
2013-03-13 22:41:29 +08:00
|
|
|
unsigned CountBoundToVariable = 0;
|
|
|
|
unsigned CountBoundToType = 0;
|
|
|
|
bool HasCpp03IncompatibleFormat = false;
|
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-03-13 22:41:29 +08:00
|
|
|
if (Tok->Type == TT_PointerOrReference) {
|
2013-05-29 22:47:47 +08:00
|
|
|
bool SpacesBefore =
|
|
|
|
Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
|
|
|
|
bool SpacesAfter = Tok->Next->WhitespaceRange.getBegin() !=
|
|
|
|
Tok->Next->WhitespaceRange.getEnd();
|
2013-03-13 22:41:29 +08:00
|
|
|
if (SpacesBefore && !SpacesAfter)
|
|
|
|
++CountBoundToVariable;
|
|
|
|
else if (!SpacesBefore && SpacesAfter)
|
|
|
|
++CountBoundToType;
|
|
|
|
}
|
|
|
|
|
2013-10-12 13:16:06 +08:00
|
|
|
if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
|
|
|
|
if (Tok->is(tok::coloncolon) &&
|
|
|
|
Tok->Previous->Type == TT_TemplateOpener)
|
|
|
|
HasCpp03IncompatibleFormat = true;
|
|
|
|
if (Tok->Type == TT_TemplateCloser &&
|
|
|
|
Tok->Previous->Type == TT_TemplateCloser)
|
|
|
|
HasCpp03IncompatibleFormat = true;
|
|
|
|
}
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
if (Style.DerivePointerBinding) {
|
|
|
|
if (CountBoundToType > CountBoundToVariable)
|
|
|
|
Style.PointerBindsToType = true;
|
|
|
|
else if (CountBoundToType < CountBoundToVariable)
|
|
|
|
Style.PointerBindsToType = false;
|
|
|
|
}
|
|
|
|
if (Style.Standard == FormatStyle::LS_Auto) {
|
|
|
|
Style.Standard = HasCpp03IncompatibleFormat ? 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
|
|
|
}
|
|
|
|
|
2014-03-15 12:29:04 +08:00
|
|
|
void consumeUnwrappedLine(const UnwrappedLine &TheLine) override {
|
2013-10-12 05:25:45 +08:00
|
|
|
assert(!UnwrappedLines.empty());
|
|
|
|
UnwrappedLines.back().push_back(TheLine);
|
|
|
|
}
|
|
|
|
|
2014-03-15 12:29:04 +08:00
|
|
|
void finishRun() override {
|
2013-10-12 05:25:45 +08:00
|
|
|
UnwrappedLines.push_back(SmallVector<UnwrappedLine, 16>());
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
FormatStyle Style;
|
|
|
|
Lexer &Lex;
|
|
|
|
SourceManager &SourceMgr;
|
2013-01-18 16:44:07 +08:00
|
|
|
WhitespaceManager Whitespaces;
|
2013-11-06 03:10:03 +08:00
|
|
|
SmallVector<CharSourceRange, 8> Ranges;
|
2013-10-12 05:25:45 +08:00
|
|
|
SmallVector<SmallVector<UnwrappedLine, 16>, 2> UnwrappedLines;
|
2013-06-05 22:09:10 +08:00
|
|
|
|
|
|
|
encoding::Encoding Encoding;
|
2013-07-10 22:02:49 +08:00
|
|
|
bool BinPackInconclusiveFunctions;
|
2012-12-04 02:12:45 +08:00
|
|
|
};
|
|
|
|
|
2013-07-01 06:29:28 +08:00
|
|
|
} // end anonymous namespace
|
|
|
|
|
2013-04-15 22:28:00 +08:00
|
|
|
tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
|
|
|
|
SourceManager &SourceMgr,
|
2013-05-15 16:14:19 +08:00
|
|
|
std::vector<CharSourceRange> Ranges) {
|
2014-05-22 23:12:22 +08:00
|
|
|
if (Style.DisableFormat) {
|
|
|
|
tooling::Replacements EmptyResult;
|
|
|
|
return EmptyResult;
|
|
|
|
}
|
|
|
|
|
2013-05-15 16:14:19 +08:00
|
|
|
Formatter formatter(Style, Lex, SourceMgr, Ranges);
|
2012-12-04 02:12:45 +08:00
|
|
|
return formatter.format();
|
|
|
|
}
|
|
|
|
|
2013-05-16 18:40:07 +08:00
|
|
|
tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
|
|
|
|
std::vector<tooling::Range> Ranges,
|
|
|
|
StringRef FileName) {
|
|
|
|
FileManager Files((FileSystemOptions()));
|
|
|
|
DiagnosticsEngine Diagnostics(
|
|
|
|
IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
|
|
|
|
new DiagnosticOptions);
|
|
|
|
SourceManager SourceMgr(Diagnostics, Files);
|
|
|
|
llvm::MemoryBuffer *Buf = llvm::MemoryBuffer::getMemBuffer(Code, FileName);
|
|
|
|
const clang::FileEntry *Entry =
|
|
|
|
Files.getVirtualFile(FileName, Buf->getBufferSize(), 0);
|
|
|
|
SourceMgr.overrideFileContents(Entry, Buf);
|
|
|
|
FileID ID =
|
|
|
|
SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
|
2013-06-28 20:51:24 +08:00
|
|
|
Lexer Lex(ID, SourceMgr.getBuffer(ID), SourceMgr,
|
|
|
|
getFormattingLangOpts(Style.Standard));
|
2013-05-16 18:40:07 +08:00
|
|
|
SourceLocation StartOfFile = SourceMgr.getLocForStartOfFile(ID);
|
|
|
|
std::vector<CharSourceRange> CharRanges;
|
|
|
|
for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
|
|
|
|
SourceLocation Start = StartOfFile.getLocWithOffset(Ranges[i].getOffset());
|
|
|
|
SourceLocation End = Start.getLocWithOffset(Ranges[i].getLength());
|
|
|
|
CharRanges.push_back(CharSourceRange::getCharRange(Start, End));
|
|
|
|
}
|
|
|
|
return reformat(Style, Lex, SourceMgr, CharRanges);
|
|
|
|
}
|
|
|
|
|
2013-06-28 20:51:24 +08:00
|
|
|
LangOptions getFormattingLangOpts(FormatStyle::LanguageStandard Standard) {
|
2013-01-10 21:08:12 +08:00
|
|
|
LangOptions LangOpts;
|
|
|
|
LangOpts.CPlusPlus = 1;
|
2013-06-28 20:51:24 +08:00
|
|
|
LangOpts.CPlusPlus11 = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
|
2014-04-15 16:49:21 +08:00
|
|
|
LangOpts.CPlusPlus1y = Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
|
2013-03-22 18:01:29 +08:00
|
|
|
LangOpts.LineComment = 1;
|
2014-05-08 08:05:13 +08:00
|
|
|
LangOpts.CXXOperatorNames = 1;
|
2013-01-10 21:08:12 +08:00
|
|
|
LangOpts.Bool = 1;
|
|
|
|
LangOpts.ObjC1 = 1;
|
|
|
|
LangOpts.ObjC2 = 1;
|
|
|
|
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) {
|
2013-11-29 23:19:43 +08:00
|
|
|
if (FileName.endswith_lower(".js")) {
|
2013-12-10 19:28:13 +08:00
|
|
|
return FormatStyle::LK_JavaScript;
|
2014-01-19 17:04:08 +08:00
|
|
|
} else if (FileName.endswith_lower(".proto") ||
|
|
|
|
FileName.endswith_lower(".protodevel")) {
|
|
|
|
return FormatStyle::LK_Proto;
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
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,
|
|
|
|
StringRef FallbackStyle) {
|
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.
|
|
|
|
if (llvm::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)) {
|
|
|
|
if (!llvm::sys::fs::is_directory(Directory))
|
|
|
|
continue;
|
|
|
|
SmallString<128> ConfigFile(Directory);
|
|
|
|
|
|
|
|
llvm::sys::path::append(ConfigFile, ".clang-format");
|
|
|
|
DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
|
|
|
|
bool IsFile = false;
|
|
|
|
// Ignore errors from is_regular_file: we only need to know if we can read
|
|
|
|
// the file or not.
|
|
|
|
llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
|
|
|
|
|
|
|
|
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");
|
|
|
|
llvm::sys::fs::is_regular_file(Twine(ConfigFile), IsFile);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (IsFile) {
|
2014-03-08 04:03:18 +08:00
|
|
|
std::unique_ptr<llvm::MemoryBuffer> Text;
|
2013-10-26 03:00:49 +08:00
|
|
|
if (llvm::error_code ec =
|
|
|
|
llvm::MemoryBuffer::getFile(ConfigFile.c_str(), Text)) {
|
2013-09-30 21:31:48 +08:00
|
|
|
llvm::errs() << ec.message() << "\n";
|
2013-12-02 23:21:38 +08:00
|
|
|
break;
|
2013-09-30 21:31:48 +08:00
|
|
|
}
|
|
|
|
if (llvm::error_code ec = parseConfiguration(Text->getBuffer(), &Style)) {
|
2013-11-29 23:19:43 +08:00
|
|
|
if (ec == llvm::errc::not_supported) {
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
llvm::errs() << "Can't find usable .clang-format, using " << FallbackStyle
|
|
|
|
<< " style\n";
|
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
|