2012-12-04 02:12:45 +08:00
|
|
|
//===--- Format.cpp - Format C++ code -------------------------------------===//
|
|
|
|
//
|
2019-01-19 16:50:56 +08:00
|
|
|
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
|
|
|
|
// See https://llvm.org/LICENSE.txt for license information.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
|
2012-12-04 02:12:45 +08:00
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
///
|
|
|
|
/// \file
|
2018-05-09 09:00:01 +08:00
|
|
|
/// This file implements functions declared in Format.h. This will be
|
2012-12-04 02:12:45 +08:00
|
|
|
/// split into separate files as we go.
|
|
|
|
///
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
2015-09-29 15:53:08 +08:00
|
|
|
#include "clang/Format/Format.h"
|
2016-04-25 23:09:22 +08:00
|
|
|
#include "AffectedRangeManager.h"
|
2013-08-16 19:20:30 +08:00
|
|
|
#include "ContinuationIndenter.h"
|
2017-10-30 22:01:50 +08:00
|
|
|
#include "FormatInternal.h"
|
2016-05-20 19:24:24 +08:00
|
|
|
#include "FormatTokenLexer.h"
|
2017-02-27 21:28:36 +08:00
|
|
|
#include "NamespaceEndCommentsFixer.h"
|
2016-05-20 19:24:24 +08:00
|
|
|
#include "SortJavaScriptImports.h"
|
|
|
|
#include "TokenAnalyzer.h"
|
2013-01-30 05:01:14 +08:00
|
|
|
#include "TokenAnnotator.h"
|
2014-12-11 03:00:42 +08:00
|
|
|
#include "UnwrappedLineFormatter.h"
|
2012-12-04 17:13:33 +08:00
|
|
|
#include "UnwrappedLineParser.h"
|
2017-06-21 20:03:12 +08:00
|
|
|
#include "UsingDeclarationsSorter.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"
|
2012-12-04 02:12:45 +08:00
|
|
|
#include "clang/Lex/Lexer.h"
|
2018-06-04 17:04:12 +08:00
|
|
|
#include "clang/Tooling/Inclusions/HeaderIncludes.h"
|
2013-03-27 19:52:18 +08:00
|
|
|
#include "llvm/ADT/STLExtras.h"
|
2018-01-18 01:33:08 +08:00
|
|
|
#include "llvm/ADT/StringRef.h"
|
2013-02-13 18:46:36 +08:00
|
|
|
#include "llvm/Support/Allocator.h"
|
2013-01-16 22:55:28 +08:00
|
|
|
#include "llvm/Support/Debug.h"
|
2013-09-30 21:31:48 +08:00
|
|
|
#include "llvm/Support/Path.h"
|
2015-07-04 01:25:16 +08:00
|
|
|
#include "llvm/Support/Regex.h"
|
2018-10-10 21:27:25 +08:00
|
|
|
#include "llvm/Support/VirtualFileSystem.h"
|
2014-01-07 19:51:46 +08:00
|
|
|
#include "llvm/Support/YAMLTraits.h"
|
2016-06-01 23:19:53 +08:00
|
|
|
#include <algorithm>
|
2016-04-25 23:09:22 +08:00
|
|
|
#include <memory>
|
2018-05-05 01:55:13 +08:00
|
|
|
#include <mutex>
|
2012-12-04 21:02:32 +08:00
|
|
|
#include <string>
|
2018-05-05 01:55:13 +08:00
|
|
|
#include <unordered_map>
|
2012-12-04 21:02:32 +08:00
|
|
|
|
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;
|
|
|
|
|
2017-11-01 12:43:22 +08:00
|
|
|
LLVM_YAML_IS_SEQUENCE_VECTOR(clang::format::FormatStyle::RawStringFormat)
|
2014-04-01 20:55:11 +08:00
|
|
|
|
2013-05-07 23:32:14 +08:00
|
|
|
namespace llvm {
|
|
|
|
namespace yaml {
|
2013-12-10 18:30:34 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::LanguageKind &Value) {
|
|
|
|
IO.enumCase(Value, "Cpp", FormatStyle::LK_Cpp);
|
2014-09-15 19:21:46 +08:00
|
|
|
IO.enumCase(Value, "Java", FormatStyle::LK_Java);
|
2013-12-10 18:30:34 +08:00
|
|
|
IO.enumCase(Value, "JavaScript", FormatStyle::LK_JavaScript);
|
2016-12-12 20:42:29 +08:00
|
|
|
IO.enumCase(Value, "ObjC", FormatStyle::LK_ObjC);
|
2014-01-19 17:04:08 +08:00
|
|
|
IO.enumCase(Value, "Proto", FormatStyle::LK_Proto);
|
2015-12-25 16:53:31 +08:00
|
|
|
IO.enumCase(Value, "TableGen", FormatStyle::LK_TableGen);
|
2017-07-03 23:05:14 +08:00
|
|
|
IO.enumCase(Value, "TextProto", FormatStyle::LK_TextProto);
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-12-10 18:30:34 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::LanguageStandard &Value) {
|
|
|
|
IO.enumCase(Value, "Cpp03", FormatStyle::LS_Cpp03);
|
|
|
|
IO.enumCase(Value, "C++03", FormatStyle::LS_Cpp03);
|
|
|
|
IO.enumCase(Value, "Cpp11", FormatStyle::LS_Cpp11);
|
|
|
|
IO.enumCase(Value, "C++11", FormatStyle::LS_Cpp11);
|
|
|
|
IO.enumCase(Value, "Auto", FormatStyle::LS_Auto);
|
2013-05-13 20:51:40 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-12-10 18:30:34 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::UseTabStyle &Value) {
|
|
|
|
IO.enumCase(Value, "Never", FormatStyle::UT_Never);
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::UT_Never);
|
|
|
|
IO.enumCase(Value, "Always", FormatStyle::UT_Always);
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::UT_Always);
|
|
|
|
IO.enumCase(Value, "ForIndentation", FormatStyle::UT_ForIndentation);
|
2016-04-14 22:52:26 +08:00
|
|
|
IO.enumCase(Value, "ForContinuationAndIndentation",
|
|
|
|
FormatStyle::UT_ForContinuationAndIndentation);
|
2013-09-28 00:14:22 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2016-03-03 06:44:03 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::JavaScriptQuoteStyle &Value) {
|
|
|
|
IO.enumCase(Value, "Leave", FormatStyle::JSQS_Leave);
|
|
|
|
IO.enumCase(Value, "Single", FormatStyle::JSQS_Single);
|
|
|
|
IO.enumCase(Value, "Double", FormatStyle::JSQS_Double);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-04-08 20:46:38 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::ShortFunctionStyle &Value) {
|
|
|
|
IO.enumCase(Value, "None", FormatStyle::SFS_None);
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::SFS_None);
|
|
|
|
IO.enumCase(Value, "All", FormatStyle::SFS_All);
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::SFS_All);
|
|
|
|
IO.enumCase(Value, "Inline", FormatStyle::SFS_Inline);
|
2017-06-21 21:56:02 +08:00
|
|
|
IO.enumCase(Value, "InlineOnly", FormatStyle::SFS_InlineOnly);
|
2014-11-26 18:43:58 +08:00
|
|
|
IO.enumCase(Value, "Empty", FormatStyle::SFS_Empty);
|
2014-04-08 20:46:38 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2019-03-13 16:26:39 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::ShortIfStyle &Value) {
|
|
|
|
IO.enumCase(Value, "Never", FormatStyle::SIS_Never);
|
|
|
|
IO.enumCase(Value, "Always", FormatStyle::SIS_Always);
|
|
|
|
IO.enumCase(Value, "WithoutElse", FormatStyle::SIS_WithoutElse);
|
|
|
|
|
|
|
|
// For backward compatibility.
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::SIS_Never);
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::SIS_WithoutElse);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2018-02-03 04:15:14 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::BinPackStyle &Value) {
|
|
|
|
IO.enumCase(Value, "Auto", FormatStyle::BPS_Auto);
|
|
|
|
IO.enumCase(Value, "Always", FormatStyle::BPS_Always);
|
|
|
|
IO.enumCase(Value, "Never", FormatStyle::BPS_Never);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2014-09-15 19:11:00 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::BinaryOperatorStyle &Value) {
|
|
|
|
IO.enumCase(Value, "All", FormatStyle::BOS_All);
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::BOS_All);
|
|
|
|
IO.enumCase(Value, "None", FormatStyle::BOS_None);
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::BOS_None);
|
|
|
|
IO.enumCase(Value, "NonAssignment", FormatStyle::BOS_NonAssignment);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-12-10 18:30:34 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::BraceBreakingStyle &Value) {
|
|
|
|
IO.enumCase(Value, "Attach", FormatStyle::BS_Attach);
|
|
|
|
IO.enumCase(Value, "Linux", FormatStyle::BS_Linux);
|
2015-07-12 11:13:54 +08:00
|
|
|
IO.enumCase(Value, "Mozilla", FormatStyle::BS_Mozilla);
|
2013-12-10 18:30:34 +08:00
|
|
|
IO.enumCase(Value, "Stroustrup", FormatStyle::BS_Stroustrup);
|
|
|
|
IO.enumCase(Value, "Allman", FormatStyle::BS_Allman);
|
2013-12-12 17:49:52 +08:00
|
|
|
IO.enumCase(Value, "GNU", FormatStyle::BS_GNU);
|
2015-08-10 21:43:19 +08:00
|
|
|
IO.enumCase(Value, "WebKit", FormatStyle::BS_WebKit);
|
2015-09-29 22:57:55 +08:00
|
|
|
IO.enumCase(Value, "Custom", FormatStyle::BS_Custom);
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2017-09-20 17:51:03 +08:00
|
|
|
template <>
|
|
|
|
struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {
|
|
|
|
static void
|
|
|
|
enumeration(IO &IO, FormatStyle::BreakConstructorInitializersStyle &Value) {
|
2017-05-24 19:36:58 +08:00
|
|
|
IO.enumCase(Value, "BeforeColon", FormatStyle::BCIS_BeforeColon);
|
|
|
|
IO.enumCase(Value, "BeforeComma", FormatStyle::BCIS_BeforeComma);
|
|
|
|
IO.enumCase(Value, "AfterColon", FormatStyle::BCIS_AfterColon);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2018-06-11 22:41:26 +08:00
|
|
|
template <>
|
|
|
|
struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {
|
2019-03-01 17:09:54 +08:00
|
|
|
static void enumeration(IO &IO,
|
|
|
|
FormatStyle::BreakInheritanceListStyle &Value) {
|
2018-06-11 22:41:26 +08:00
|
|
|
IO.enumCase(Value, "BeforeColon", FormatStyle::BILS_BeforeColon);
|
|
|
|
IO.enumCase(Value, "BeforeComma", FormatStyle::BILS_BeforeComma);
|
|
|
|
IO.enumCase(Value, "AfterColon", FormatStyle::BILS_AfterColon);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
clang-format: Add preprocessor directive indentation
Summary:
This is an implementation for [bug 17362](https://bugs.llvm.org/attachment.cgi?bugid=17362) which adds support for indenting preprocessor statements inside if/ifdef/endif. This takes previous work from fmauch (https://github.com/fmauch/clang/tree/preprocessor_indent) and makes it into a full feature.
The context of this patch is that I'm a VMware intern, and I implemented this because VMware needs the feature. As such, some decisions were made based on what VMware wants, and I would appreciate suggestions on expanding this if necessary to use-cases other people may want.
This adds a new enum config option, `IndentPPDirectives`. Values are:
* `PPDIS_None` (in config: `None`):
```
#if FOO
#if BAR
#include <foo>
#endif
#endif
```
* `PPDIS_AfterHash` (in config: `AfterHash`):
```
#if FOO
# if BAR
# include <foo>
# endif
#endif
```
This is meant to work whether spaces or tabs are used for indentation. Preprocessor indentation is independent of indentation for non-preprocessor lines.
Preprocessor indentation also attempts to ignore include guards with the checks:
1. Include guards cover the entire file
2. Include guards don't have `#else`
3. Include guards begin with
```
#ifndef <var>
#define <var>
```
This patch allows `UnwrappedLineParser::PPBranchLevel` to be decremented to -1 (the initial value is -1) so the variable can be used for indent tracking.
Defects:
* This patch does not handle the case where there's code between the `#ifndef` and `#define` but all other conditions hold. This is because when the #define line is parsed, `UnwrappedLineParser::Lines` doesn't hold the previous code line yet, so we can't detect it. This is out of the scope of this patch.
* This patch does not handle cases where legitimate lines may be outside an include guard. Examples are `#pragma once` and `#pragma GCC diagnostic`, or anything else that does not change the meaning of the file if it's included multiple times.
* This does not detect when there is a single non-preprocessor line in front of an include-guard-like structure where other conditions hold because `ScopedLineState` hides the line.
* Preprocessor indentation throws off `TokenAnnotator::setCommentLineLevels` so the indentation of comments immediately before indented preprocessor lines is toggled on each run. Fixing this issue appears to be a major change and too much complexity for this patch.
Contributed by @euhlmann!
Reviewers: djasper, klimek, krasimir
Reviewed By: djasper, krasimir
Subscribers: krasimir, mzeren-vmw, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D35955
llvm-svn: 312125
2017-08-30 22:34:57 +08:00
|
|
|
template <>
|
|
|
|
struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::PPDirectiveIndentStyle &Value) {
|
|
|
|
IO.enumCase(Value, "None", FormatStyle::PPDIS_None);
|
|
|
|
IO.enumCase(Value, "AfterHash", FormatStyle::PPDIS_AfterHash);
|
[clang-format] BeforeHash added to IndentPPDirectives
Summary:
The option BeforeHash added to IndentPPDirectives.
Fixes Bug 36019. https://bugs.llvm.org/show_bug.cgi?id=36019
Reviewers: djasper, klimek, krasimir, sammccall, mprobst, Nicola, MyDeveloperDay
Reviewed By: klimek, MyDeveloperDay
Subscribers: kadircet, MyDeveloperDay, mnussbaum, geleji, ufna, cfe-commits
Patch by to-mix.
Differential Revision: https://reviews.llvm.org/D52150
llvm-svn: 356613
2019-03-21 04:49:43 +08:00
|
|
|
IO.enumCase(Value, "BeforeHash", FormatStyle::PPDIS_BeforeHash);
|
clang-format: Add preprocessor directive indentation
Summary:
This is an implementation for [bug 17362](https://bugs.llvm.org/attachment.cgi?bugid=17362) which adds support for indenting preprocessor statements inside if/ifdef/endif. This takes previous work from fmauch (https://github.com/fmauch/clang/tree/preprocessor_indent) and makes it into a full feature.
The context of this patch is that I'm a VMware intern, and I implemented this because VMware needs the feature. As such, some decisions were made based on what VMware wants, and I would appreciate suggestions on expanding this if necessary to use-cases other people may want.
This adds a new enum config option, `IndentPPDirectives`. Values are:
* `PPDIS_None` (in config: `None`):
```
#if FOO
#if BAR
#include <foo>
#endif
#endif
```
* `PPDIS_AfterHash` (in config: `AfterHash`):
```
#if FOO
# if BAR
# include <foo>
# endif
#endif
```
This is meant to work whether spaces or tabs are used for indentation. Preprocessor indentation is independent of indentation for non-preprocessor lines.
Preprocessor indentation also attempts to ignore include guards with the checks:
1. Include guards cover the entire file
2. Include guards don't have `#else`
3. Include guards begin with
```
#ifndef <var>
#define <var>
```
This patch allows `UnwrappedLineParser::PPBranchLevel` to be decremented to -1 (the initial value is -1) so the variable can be used for indent tracking.
Defects:
* This patch does not handle the case where there's code between the `#ifndef` and `#define` but all other conditions hold. This is because when the #define line is parsed, `UnwrappedLineParser::Lines` doesn't hold the previous code line yet, so we can't detect it. This is out of the scope of this patch.
* This patch does not handle cases where legitimate lines may be outside an include guard. Examples are `#pragma once` and `#pragma GCC diagnostic`, or anything else that does not change the meaning of the file if it's included multiple times.
* This does not detect when there is a single non-preprocessor line in front of an include-guard-like structure where other conditions hold because `ScopedLineState` hides the line.
* Preprocessor indentation throws off `TokenAnnotator::setCommentLineLevels` so the indentation of comments immediately before indented preprocessor lines is toggled on each run. Fixing this issue appears to be a major change and too much complexity for this patch.
Contributed by @euhlmann!
Reviewers: djasper, klimek, krasimir
Reviewed By: djasper, krasimir
Subscribers: krasimir, mzeren-vmw, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D35955
llvm-svn: 312125
2017-08-30 22:34:57 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-12-19 06:20:15 +08:00
|
|
|
template <>
|
|
|
|
struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::ReturnTypeBreakingStyle &Value) {
|
|
|
|
IO.enumCase(Value, "None", FormatStyle::RTBS_None);
|
|
|
|
IO.enumCase(Value, "All", FormatStyle::RTBS_All);
|
|
|
|
IO.enumCase(Value, "TopLevel", FormatStyle::RTBS_TopLevel);
|
|
|
|
IO.enumCase(Value, "TopLevelDefinitions",
|
|
|
|
FormatStyle::RTBS_TopLevelDefinitions);
|
|
|
|
IO.enumCase(Value, "AllDefinitions", FormatStyle::RTBS_AllDefinitions);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2018-05-16 16:25:03 +08:00
|
|
|
template <>
|
|
|
|
struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {
|
2019-03-01 17:09:54 +08:00
|
|
|
static void enumeration(IO &IO,
|
|
|
|
FormatStyle::BreakTemplateDeclarationsStyle &Value) {
|
2018-05-16 16:25:03 +08:00
|
|
|
IO.enumCase(Value, "No", FormatStyle::BTDS_No);
|
|
|
|
IO.enumCase(Value, "MultiLine", FormatStyle::BTDS_MultiLine);
|
|
|
|
IO.enumCase(Value, "Yes", FormatStyle::BTDS_Yes);
|
|
|
|
|
|
|
|
// For backward compatibility.
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::BTDS_MultiLine);
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::BTDS_Yes);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-09-29 22:57:55 +08:00
|
|
|
template <>
|
|
|
|
struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {
|
|
|
|
static void
|
|
|
|
enumeration(IO &IO, FormatStyle::DefinitionReturnTypeBreakingStyle &Value) {
|
2015-06-29 23:30:42 +08:00
|
|
|
IO.enumCase(Value, "None", FormatStyle::DRTBS_None);
|
|
|
|
IO.enumCase(Value, "All", FormatStyle::DRTBS_All);
|
|
|
|
IO.enumCase(Value, "TopLevel", FormatStyle::DRTBS_TopLevel);
|
|
|
|
|
|
|
|
// For backward compatibility.
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::DRTBS_None);
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::DRTBS_All);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-08-01 07:16:02 +08:00
|
|
|
template <>
|
2013-12-10 18:30:34 +08:00
|
|
|
struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {
|
|
|
|
static void enumeration(IO &IO,
|
|
|
|
FormatStyle::NamespaceIndentationKind &Value) {
|
|
|
|
IO.enumCase(Value, "None", FormatStyle::NI_None);
|
|
|
|
IO.enumCase(Value, "Inner", FormatStyle::NI_Inner);
|
|
|
|
IO.enumCase(Value, "All", FormatStyle::NI_All);
|
2013-08-01 07:16:02 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-10-27 20:38:37 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::BracketAlignmentStyle &Value) {
|
|
|
|
IO.enumCase(Value, "Align", FormatStyle::BAS_Align);
|
|
|
|
IO.enumCase(Value, "DontAlign", FormatStyle::BAS_DontAlign);
|
|
|
|
IO.enumCase(Value, "AlwaysBreak", FormatStyle::BAS_AlwaysBreak);
|
|
|
|
|
|
|
|
// For backward compatibility.
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::BAS_Align);
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::BAS_DontAlign);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2017-09-20 17:51:03 +08:00
|
|
|
template <>
|
|
|
|
struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {
|
|
|
|
static void enumeration(IO &IO,
|
|
|
|
FormatStyle::EscapedNewlineAlignmentStyle &Value) {
|
2017-05-08 23:08:00 +08:00
|
|
|
IO.enumCase(Value, "DontAlign", FormatStyle::ENAS_DontAlign);
|
|
|
|
IO.enumCase(Value, "Left", FormatStyle::ENAS_Left);
|
|
|
|
IO.enumCase(Value, "Right", FormatStyle::ENAS_Right);
|
|
|
|
|
|
|
|
// For backward compatibility.
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::ENAS_Left);
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::ENAS_Right);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2015-02-19 07:48:37 +08:00
|
|
|
template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {
|
|
|
|
static void enumeration(IO &IO, FormatStyle::PointerAlignmentStyle &Value) {
|
2014-06-17 20:40:34 +08:00
|
|
|
IO.enumCase(Value, "Middle", FormatStyle::PAS_Middle);
|
|
|
|
IO.enumCase(Value, "Left", FormatStyle::PAS_Left);
|
|
|
|
IO.enumCase(Value, "Right", FormatStyle::PAS_Right);
|
|
|
|
|
2014-07-15 03:42:55 +08:00
|
|
|
// For backward compatibility.
|
2014-06-17 20:40:34 +08:00
|
|
|
IO.enumCase(Value, "true", FormatStyle::PAS_Left);
|
|
|
|
IO.enumCase(Value, "false", FormatStyle::PAS_Right);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-12-10 18:18:34 +08:00
|
|
|
template <>
|
2013-12-10 18:30:34 +08:00
|
|
|
struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensOptions> {
|
|
|
|
static void enumeration(IO &IO,
|
|
|
|
FormatStyle::SpaceBeforeParensOptions &Value) {
|
|
|
|
IO.enumCase(Value, "Never", FormatStyle::SBPO_Never);
|
2013-12-10 18:18:34 +08:00
|
|
|
IO.enumCase(Value, "ControlStatements",
|
2013-12-10 18:30:34 +08:00
|
|
|
FormatStyle::SBPO_ControlStatements);
|
|
|
|
IO.enumCase(Value, "Always", FormatStyle::SBPO_Always);
|
2013-12-10 18:18:34 +08:00
|
|
|
|
|
|
|
// For backward compatibility.
|
2013-12-10 18:30:34 +08:00
|
|
|
IO.enumCase(Value, "false", FormatStyle::SBPO_Never);
|
|
|
|
IO.enumCase(Value, "true", FormatStyle::SBPO_ControlStatements);
|
2013-12-10 18:18:34 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-12-10 18:30:34 +08:00
|
|
|
template <> struct MappingTraits<FormatStyle> {
|
2013-12-10 19:28:13 +08:00
|
|
|
static void mapping(IO &IO, FormatStyle &Style) {
|
|
|
|
// When reading, read the language first, we need it for getPredefinedStyle.
|
|
|
|
IO.mapOptional("Language", Style.Language);
|
|
|
|
|
2013-05-10 19:56:10 +08:00
|
|
|
if (IO.outputting()) {
|
2015-02-19 07:48:37 +08:00
|
|
|
StringRef StylesArray[] = {"LLVM", "Google", "Chromium",
|
|
|
|
"Mozilla", "WebKit", "GNU"};
|
2013-05-10 19:56:10 +08:00
|
|
|
ArrayRef<StringRef> Styles(StylesArray);
|
|
|
|
for (size_t i = 0, e = Styles.size(); i < e; ++i) {
|
|
|
|
StringRef StyleName(Styles[i]);
|
2013-12-10 18:30:34 +08:00
|
|
|
FormatStyle PredefinedStyle;
|
2013-12-10 19:28:13 +08:00
|
|
|
if (getPredefinedStyle(StyleName, Style.Language, &PredefinedStyle) &&
|
2013-05-19 08:53:30 +08:00
|
|
|
Style == PredefinedStyle) {
|
2013-05-10 19:56:10 +08:00
|
|
|
IO.mapOptional("# BasedOnStyle", StyleName);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2013-05-07 23:32:14 +08:00
|
|
|
StringRef BasedOnStyle;
|
|
|
|
IO.mapOptional("BasedOnStyle", BasedOnStyle);
|
2013-11-29 23:19:43 +08:00
|
|
|
if (!BasedOnStyle.empty()) {
|
2013-12-10 19:28:13 +08:00
|
|
|
FormatStyle::LanguageKind OldLanguage = Style.Language;
|
|
|
|
FormatStyle::LanguageKind Language =
|
|
|
|
((FormatStyle *)IO.getContext())->Language;
|
|
|
|
if (!getPredefinedStyle(BasedOnStyle, Language, &Style)) {
|
2013-05-19 08:53:30 +08:00
|
|
|
IO.setError(Twine("Unknown value for BasedOnStyle: ", BasedOnStyle));
|
|
|
|
return;
|
|
|
|
}
|
2013-12-10 19:28:13 +08:00
|
|
|
Style.Language = OldLanguage;
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
|
2015-06-28 22:52:34 +08:00
|
|
|
// For backward compatibility.
|
|
|
|
if (!IO.outputting()) {
|
2017-05-08 23:08:00 +08:00
|
|
|
IO.mapOptional("AlignEscapedNewlinesLeft", Style.AlignEscapedNewlines);
|
2015-06-28 22:52:34 +08:00
|
|
|
IO.mapOptional("DerivePointerBinding", Style.DerivePointerAlignment);
|
|
|
|
IO.mapOptional("IndentFunctionDeclarationAfterType",
|
|
|
|
Style.IndentWrappedFunctionNames);
|
|
|
|
IO.mapOptional("PointerBindsToType", Style.PointerAlignment);
|
|
|
|
IO.mapOptional("SpaceAfterControlStatementKeyword",
|
|
|
|
Style.SpaceBeforeParens);
|
|
|
|
}
|
|
|
|
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("AccessModifierOffset", Style.AccessModifierOffset);
|
2014-11-19 07:55:27 +08:00
|
|
|
IO.mapOptional("AlignAfterOpenBracket", Style.AlignAfterOpenBracket);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("AlignConsecutiveAssignments",
|
|
|
|
Style.AlignConsecutiveAssignments);
|
2015-10-01 18:06:54 +08:00
|
|
|
IO.mapOptional("AlignConsecutiveDeclarations",
|
|
|
|
Style.AlignConsecutiveDeclarations);
|
2017-05-08 23:08:00 +08:00
|
|
|
IO.mapOptional("AlignEscapedNewlines", Style.AlignEscapedNewlines);
|
2014-12-02 21:24:51 +08:00
|
|
|
IO.mapOptional("AlignOperands", Style.AlignOperands);
|
2013-08-01 07:55:15 +08:00
|
|
|
IO.mapOptional("AlignTrailingComments", Style.AlignTrailingComments);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("AllowAllParametersOfDeclarationOnNextLine",
|
|
|
|
Style.AllowAllParametersOfDeclarationOnNextLine);
|
2014-05-14 17:33:35 +08:00
|
|
|
IO.mapOptional("AllowShortBlocksOnASingleLine",
|
|
|
|
Style.AllowShortBlocksOnASingleLine);
|
2014-09-10 21:11:45 +08:00
|
|
|
IO.mapOptional("AllowShortCaseLabelsOnASingleLine",
|
|
|
|
Style.AllowShortCaseLabelsOnASingleLine);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("AllowShortFunctionsOnASingleLine",
|
|
|
|
Style.AllowShortFunctionsOnASingleLine);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("AllowShortIfStatementsOnASingleLine",
|
|
|
|
Style.AllowShortIfStatementsOnASingleLine);
|
2013-05-16 20:12:21 +08:00
|
|
|
IO.mapOptional("AllowShortLoopsOnASingleLine",
|
|
|
|
Style.AllowShortLoopsOnASingleLine);
|
2014-08-05 20:16:31 +08:00
|
|
|
IO.mapOptional("AlwaysBreakAfterDefinitionReturnType",
|
|
|
|
Style.AlwaysBreakAfterDefinitionReturnType);
|
2015-12-19 06:20:15 +08:00
|
|
|
IO.mapOptional("AlwaysBreakAfterReturnType",
|
|
|
|
Style.AlwaysBreakAfterReturnType);
|
|
|
|
// If AlwaysBreakAfterDefinitionReturnType was specified but
|
|
|
|
// AlwaysBreakAfterReturnType was not, initialize the latter from the
|
|
|
|
// former for backwards compatibility.
|
|
|
|
if (Style.AlwaysBreakAfterDefinitionReturnType != FormatStyle::DRTBS_None &&
|
|
|
|
Style.AlwaysBreakAfterReturnType == FormatStyle::RTBS_None) {
|
|
|
|
if (Style.AlwaysBreakAfterDefinitionReturnType == FormatStyle::DRTBS_All)
|
|
|
|
Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
|
|
|
|
else if (Style.AlwaysBreakAfterDefinitionReturnType ==
|
|
|
|
FormatStyle::DRTBS_TopLevel)
|
|
|
|
Style.AlwaysBreakAfterReturnType =
|
|
|
|
FormatStyle::RTBS_TopLevelDefinitions;
|
|
|
|
}
|
|
|
|
|
2013-07-04 20:02:44 +08:00
|
|
|
IO.mapOptional("AlwaysBreakBeforeMultilineStrings",
|
|
|
|
Style.AlwaysBreakBeforeMultilineStrings);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("AlwaysBreakTemplateDeclarations",
|
|
|
|
Style.AlwaysBreakTemplateDeclarations);
|
|
|
|
IO.mapOptional("BinPackArguments", Style.BinPackArguments);
|
|
|
|
IO.mapOptional("BinPackParameters", Style.BinPackParameters);
|
2015-09-29 22:57:55 +08:00
|
|
|
IO.mapOptional("BraceWrapping", Style.BraceWrapping);
|
2013-07-27 00:56:36 +08:00
|
|
|
IO.mapOptional("BreakBeforeBinaryOperators",
|
|
|
|
Style.BreakBeforeBinaryOperators);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
|
2018-06-11 22:41:26 +08:00
|
|
|
|
|
|
|
bool BreakBeforeInheritanceComma = false;
|
2019-03-01 17:09:54 +08:00
|
|
|
IO.mapOptional("BreakBeforeInheritanceComma", BreakBeforeInheritanceComma);
|
|
|
|
IO.mapOptional("BreakInheritanceList", Style.BreakInheritanceList);
|
2018-06-11 22:41:26 +08:00
|
|
|
// If BreakBeforeInheritanceComma was specified but
|
|
|
|
// BreakInheritance was not, initialize the latter from the
|
|
|
|
// former for backwards compatibility.
|
|
|
|
if (BreakBeforeInheritanceComma &&
|
|
|
|
Style.BreakInheritanceList == FormatStyle::BILS_BeforeColon)
|
|
|
|
Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
|
|
|
|
|
2013-11-08 08:57:11 +08:00
|
|
|
IO.mapOptional("BreakBeforeTernaryOperators",
|
|
|
|
Style.BreakBeforeTernaryOperators);
|
2017-05-24 19:36:58 +08:00
|
|
|
|
|
|
|
bool BreakConstructorInitializersBeforeComma = false;
|
2013-07-27 00:56:36 +08:00
|
|
|
IO.mapOptional("BreakConstructorInitializersBeforeComma",
|
2017-05-24 19:36:58 +08:00
|
|
|
BreakConstructorInitializersBeforeComma);
|
|
|
|
IO.mapOptional("BreakConstructorInitializers",
|
|
|
|
Style.BreakConstructorInitializers);
|
|
|
|
// If BreakConstructorInitializersBeforeComma was specified but
|
|
|
|
// BreakConstructorInitializers was not, initialize the latter from the
|
|
|
|
// former for backwards compatibility.
|
|
|
|
if (BreakConstructorInitializersBeforeComma &&
|
|
|
|
Style.BreakConstructorInitializers == FormatStyle::BCIS_BeforeColon)
|
|
|
|
Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
|
|
|
|
|
2016-02-01 19:21:02 +08:00
|
|
|
IO.mapOptional("BreakAfterJavaFieldAnnotations",
|
|
|
|
Style.BreakAfterJavaFieldAnnotations);
|
|
|
|
IO.mapOptional("BreakStringLiterals", Style.BreakStringLiterals);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("ColumnLimit", Style.ColumnLimit);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("CommentPragmas", Style.CommentPragmas);
|
2017-06-14 20:29:47 +08:00
|
|
|
IO.mapOptional("CompactNamespaces", Style.CompactNamespaces);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("ConstructorInitializerAllOnOneLineOrOnePerLine",
|
|
|
|
Style.ConstructorInitializerAllOnOneLineOrOnePerLine);
|
2014-10-29 00:53:38 +08:00
|
|
|
IO.mapOptional("ConstructorInitializerIndentWidth",
|
|
|
|
Style.ConstructorInitializerIndentWidth);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("ContinuationIndentWidth", Style.ContinuationIndentWidth);
|
|
|
|
IO.mapOptional("Cpp11BracedListStyle", Style.Cpp11BracedListStyle);
|
2014-06-17 20:40:34 +08:00
|
|
|
IO.mapOptional("DerivePointerAlignment", Style.DerivePointerAlignment);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("DisableFormat", Style.DisableFormat);
|
2013-07-10 22:02:49 +08:00
|
|
|
IO.mapOptional("ExperimentalAutoDetectBinPacking",
|
|
|
|
Style.ExperimentalAutoDetectBinPacking);
|
2017-03-01 23:35:39 +08:00
|
|
|
IO.mapOptional("FixNamespaceComments", Style.FixNamespaceComments);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("ForEachMacros", Style.ForEachMacros);
|
2018-05-15 03:51:33 +08:00
|
|
|
IO.mapOptional("IncludeBlocks", Style.IncludeStyle.IncludeBlocks);
|
|
|
|
IO.mapOptional("IncludeCategories", Style.IncludeStyle.IncludeCategories);
|
|
|
|
IO.mapOptional("IncludeIsMainRegex", Style.IncludeStyle.IncludeIsMainRegex);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
|
clang-format: Add preprocessor directive indentation
Summary:
This is an implementation for [bug 17362](https://bugs.llvm.org/attachment.cgi?bugid=17362) which adds support for indenting preprocessor statements inside if/ifdef/endif. This takes previous work from fmauch (https://github.com/fmauch/clang/tree/preprocessor_indent) and makes it into a full feature.
The context of this patch is that I'm a VMware intern, and I implemented this because VMware needs the feature. As such, some decisions were made based on what VMware wants, and I would appreciate suggestions on expanding this if necessary to use-cases other people may want.
This adds a new enum config option, `IndentPPDirectives`. Values are:
* `PPDIS_None` (in config: `None`):
```
#if FOO
#if BAR
#include <foo>
#endif
#endif
```
* `PPDIS_AfterHash` (in config: `AfterHash`):
```
#if FOO
# if BAR
# include <foo>
# endif
#endif
```
This is meant to work whether spaces or tabs are used for indentation. Preprocessor indentation is independent of indentation for non-preprocessor lines.
Preprocessor indentation also attempts to ignore include guards with the checks:
1. Include guards cover the entire file
2. Include guards don't have `#else`
3. Include guards begin with
```
#ifndef <var>
#define <var>
```
This patch allows `UnwrappedLineParser::PPBranchLevel` to be decremented to -1 (the initial value is -1) so the variable can be used for indent tracking.
Defects:
* This patch does not handle the case where there's code between the `#ifndef` and `#define` but all other conditions hold. This is because when the #define line is parsed, `UnwrappedLineParser::Lines` doesn't hold the previous code line yet, so we can't detect it. This is out of the scope of this patch.
* This patch does not handle cases where legitimate lines may be outside an include guard. Examples are `#pragma once` and `#pragma GCC diagnostic`, or anything else that does not change the meaning of the file if it's included multiple times.
* This does not detect when there is a single non-preprocessor line in front of an include-guard-like structure where other conditions hold because `ScopedLineState` hides the line.
* Preprocessor indentation throws off `TokenAnnotator::setCommentLineLevels` so the indentation of comments immediately before indented preprocessor lines is toggled on each run. Fixing this issue appears to be a major change and too much complexity for this patch.
Contributed by @euhlmann!
Reviewers: djasper, klimek, krasimir
Reviewed By: djasper, krasimir
Subscribers: krasimir, mzeren-vmw, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D35955
llvm-svn: 312125
2017-08-30 22:34:57 +08:00
|
|
|
IO.mapOptional("IndentPPDirectives", Style.IndentPPDirectives);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("IndentWidth", Style.IndentWidth);
|
|
|
|
IO.mapOptional("IndentWrappedFunctionNames",
|
|
|
|
Style.IndentWrappedFunctionNames);
|
2018-10-06 01:19:26 +08:00
|
|
|
IO.mapOptional("JavaImportGroups", Style.JavaImportGroups);
|
2016-06-14 00:39:50 +08:00
|
|
|
IO.mapOptional("JavaScriptQuotes", Style.JavaScriptQuotes);
|
|
|
|
IO.mapOptional("JavaScriptWrapImports", Style.JavaScriptWrapImports);
|
2014-03-21 21:43:14 +08:00
|
|
|
IO.mapOptional("KeepEmptyLinesAtTheStartOfBlocks",
|
|
|
|
Style.KeepEmptyLinesAtTheStartOfBlocks);
|
2015-07-04 01:25:16 +08:00
|
|
|
IO.mapOptional("MacroBlockBegin", Style.MacroBlockBegin);
|
|
|
|
IO.mapOptional("MacroBlockEnd", Style.MacroBlockEnd);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("MaxEmptyLinesToKeep", Style.MaxEmptyLinesToKeep);
|
2013-08-01 07:16:02 +08:00
|
|
|
IO.mapOptional("NamespaceIndentation", Style.NamespaceIndentation);
|
2018-02-03 04:15:14 +08:00
|
|
|
IO.mapOptional("ObjCBinPackProtocolList", Style.ObjCBinPackProtocolList);
|
2014-10-29 00:53:38 +08:00
|
|
|
IO.mapOptional("ObjCBlockIndentWidth", Style.ObjCBlockIndentWidth);
|
2014-01-28 23:20:33 +08:00
|
|
|
IO.mapOptional("ObjCSpaceAfterProperty", Style.ObjCSpaceAfterProperty);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("ObjCSpaceBeforeProtocolList",
|
|
|
|
Style.ObjCSpaceBeforeProtocolList);
|
2017-09-20 17:51:03 +08:00
|
|
|
IO.mapOptional("PenaltyBreakAssignment", Style.PenaltyBreakAssignment);
|
2013-10-25 22:29:37 +08:00
|
|
|
IO.mapOptional("PenaltyBreakBeforeFirstCallParameter",
|
|
|
|
Style.PenaltyBreakBeforeFirstCallParameter);
|
2013-06-08 00:02:52 +08:00
|
|
|
IO.mapOptional("PenaltyBreakComment", Style.PenaltyBreakComment);
|
2013-07-12 04:41:21 +08:00
|
|
|
IO.mapOptional("PenaltyBreakFirstLessLess",
|
|
|
|
Style.PenaltyBreakFirstLessLess);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("PenaltyBreakString", Style.PenaltyBreakString);
|
2018-05-16 16:25:03 +08:00
|
|
|
IO.mapOptional("PenaltyBreakTemplateDeclaration",
|
|
|
|
Style.PenaltyBreakTemplateDeclaration);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("PenaltyExcessCharacter", Style.PenaltyExcessCharacter);
|
|
|
|
IO.mapOptional("PenaltyReturnTypeOnItsOwnLine",
|
|
|
|
Style.PenaltyReturnTypeOnItsOwnLine);
|
2014-06-17 20:40:34 +08:00
|
|
|
IO.mapOptional("PointerAlignment", Style.PointerAlignment);
|
2017-10-30 22:01:50 +08:00
|
|
|
IO.mapOptional("RawStringFormats", Style.RawStringFormats);
|
2015-12-01 21:28:53 +08:00
|
|
|
IO.mapOptional("ReflowComments", Style.ReflowComments);
|
|
|
|
IO.mapOptional("SortIncludes", Style.SortIncludes);
|
2017-06-23 19:46:03 +08:00
|
|
|
IO.mapOptional("SortUsingDeclarations", Style.SortUsingDeclarations);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("SpaceAfterCStyleCast", Style.SpaceAfterCStyleCast);
|
2017-09-20 17:51:03 +08:00
|
|
|
IO.mapOptional("SpaceAfterTemplateKeyword",
|
|
|
|
Style.SpaceAfterTemplateKeyword);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("SpaceBeforeAssignmentOperators",
|
|
|
|
Style.SpaceBeforeAssignmentOperators);
|
2018-06-14 16:01:09 +08:00
|
|
|
IO.mapOptional("SpaceBeforeCpp11BracedList",
|
|
|
|
Style.SpaceBeforeCpp11BracedList);
|
[clang-format] Add SpaceBeforeColon option
Summary:
When disabled, this option allows removing the space before colon,
making it act more like the semi-colon. When enabled (default), the
current behavior is not affected.
This mostly affects C++11 loop, initializer list, inheritance list and
container literals:
class Foo: Bar {}
Foo::Foo(): a(a) {}
for (auto i: myList) {}
f({a: 1, b: 2, c: 3});
Reviewers: krasimir, djasper
Reviewed By: djasper
Subscribers: xvallspl, teemperor, karies, cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D32525
llvm-svn: 326426
2018-03-01 18:09:13 +08:00
|
|
|
IO.mapOptional("SpaceBeforeCtorInitializerColon",
|
|
|
|
Style.SpaceBeforeCtorInitializerColon);
|
|
|
|
IO.mapOptional("SpaceBeforeInheritanceColon",
|
|
|
|
Style.SpaceBeforeInheritanceColon);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("SpaceBeforeParens", Style.SpaceBeforeParens);
|
[clang-format] Add SpaceBeforeColon option
Summary:
When disabled, this option allows removing the space before colon,
making it act more like the semi-colon. When enabled (default), the
current behavior is not affected.
This mostly affects C++11 loop, initializer list, inheritance list and
container literals:
class Foo: Bar {}
Foo::Foo(): a(a) {}
for (auto i: myList) {}
f({a: 1, b: 2, c: 3});
Reviewers: krasimir, djasper
Reviewed By: djasper
Subscribers: xvallspl, teemperor, karies, cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D32525
llvm-svn: 326426
2018-03-01 18:09:13 +08:00
|
|
|
IO.mapOptional("SpaceBeforeRangeBasedForLoopColon",
|
|
|
|
Style.SpaceBeforeRangeBasedForLoopColon);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("SpaceInEmptyParentheses", Style.SpaceInEmptyParentheses);
|
2013-05-07 23:32:14 +08:00
|
|
|
IO.mapOptional("SpacesBeforeTrailingComments",
|
|
|
|
Style.SpacesBeforeTrailingComments);
|
2013-10-29 22:52:02 +08:00
|
|
|
IO.mapOptional("SpacesInAngles", Style.SpacesInAngles);
|
2014-01-15 23:09:08 +08:00
|
|
|
IO.mapOptional("SpacesInContainerLiterals",
|
|
|
|
Style.SpacesInContainerLiterals);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("SpacesInCStyleCastParentheses",
|
|
|
|
Style.SpacesInCStyleCastParentheses);
|
|
|
|
IO.mapOptional("SpacesInParentheses", Style.SpacesInParentheses);
|
|
|
|
IO.mapOptional("SpacesInSquareBrackets", Style.SpacesInSquareBrackets);
|
|
|
|
IO.mapOptional("Standard", Style.Standard);
|
clang-format: better handle statement macros
Summary:
Some macros are used in the body of function, and actually contain the trailing semicolon: they should thus be automatically followed by a new line, and not get merged with the next line. This is for example the case with Qt's Q_UNUSED macro:
void foo(int a, int b) {
Q_UNUSED(a)
return b;
}
This patch deals with these cases by introducing a new option to specify list of statement macros. This re-uses the system already in place for foreach macros, to ensure there is no impact on performance.
Reviewers: krasimir, djasper, klimek
Reviewed By: krasimir
Subscribers: acoomans, mgrang, alexfh, klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D33440
llvm-svn: 343602
2018-10-03 00:37:51 +08:00
|
|
|
IO.mapOptional("StatementMacros", Style.StatementMacros);
|
2015-06-28 22:51:17 +08:00
|
|
|
IO.mapOptional("TabWidth", Style.TabWidth);
|
|
|
|
IO.mapOptional("UseTab", Style.UseTab);
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
};
|
2013-11-29 23:19:43 +08:00
|
|
|
|
2015-09-29 22:57:55 +08:00
|
|
|
template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {
|
|
|
|
static void mapping(IO &IO, FormatStyle::BraceWrappingFlags &Wrapping) {
|
|
|
|
IO.mapOptional("AfterClass", Wrapping.AfterClass);
|
|
|
|
IO.mapOptional("AfterControlStatement", Wrapping.AfterControlStatement);
|
|
|
|
IO.mapOptional("AfterEnum", Wrapping.AfterEnum);
|
|
|
|
IO.mapOptional("AfterFunction", Wrapping.AfterFunction);
|
|
|
|
IO.mapOptional("AfterNamespace", Wrapping.AfterNamespace);
|
|
|
|
IO.mapOptional("AfterObjCDeclaration", Wrapping.AfterObjCDeclaration);
|
|
|
|
IO.mapOptional("AfterStruct", Wrapping.AfterStruct);
|
|
|
|
IO.mapOptional("AfterUnion", Wrapping.AfterUnion);
|
2017-09-15 19:23:50 +08:00
|
|
|
IO.mapOptional("AfterExternBlock", Wrapping.AfterExternBlock);
|
2015-09-29 22:57:55 +08:00
|
|
|
IO.mapOptional("BeforeCatch", Wrapping.BeforeCatch);
|
|
|
|
IO.mapOptional("BeforeElse", Wrapping.BeforeElse);
|
|
|
|
IO.mapOptional("IndentBraces", Wrapping.IndentBraces);
|
clang-format: add options to merge empty record body
Summary:
This patch introduces a few extra BraceWrapping options, similar to
`SplitEmptyFunction`, to allow merging empty 'record' bodies (e.g.
class, struct, union and namespace):
* SplitEmptyClass
* SplitEmptyStruct
* SplitEmptyUnion
* SplitEmptyNamespace
The `SplitEmptyFunction` option name has also been simplified/
shortened (from `SplitEmptyFunctionBody`).
These options are helpful when the correspond AfterXXX option is
enabled, to allow merging the empty record:
class Foo
{};
In addition, this fixes an unexpected merging of short records, when
the AfterXXXX options are used, which caused to be formatted like
this:
class Foo
{ void Foo(); };
This is now properly formatted as:
class Foo
{
void Foo();
};
Reviewers: djasper, krasimir
Reviewed By: djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D34395
llvm-svn: 306874
2017-07-01 04:25:55 +08:00
|
|
|
IO.mapOptional("SplitEmptyFunction", Wrapping.SplitEmptyFunction);
|
|
|
|
IO.mapOptional("SplitEmptyRecord", Wrapping.SplitEmptyRecord);
|
|
|
|
IO.mapOptional("SplitEmptyNamespace", Wrapping.SplitEmptyNamespace);
|
2015-09-29 22:57:55 +08:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2017-10-30 22:01:50 +08:00
|
|
|
template <> struct MappingTraits<FormatStyle::RawStringFormat> {
|
|
|
|
static void mapping(IO &IO, FormatStyle::RawStringFormat &Format) {
|
|
|
|
IO.mapOptional("Language", Format.Language);
|
2018-01-17 20:24:59 +08:00
|
|
|
IO.mapOptional("Delimiters", Format.Delimiters);
|
2018-01-18 00:17:26 +08:00
|
|
|
IO.mapOptional("EnclosingFunctions", Format.EnclosingFunctions);
|
2018-01-20 00:18:47 +08:00
|
|
|
IO.mapOptional("CanonicalDelimiter", Format.CanonicalDelimiter);
|
2017-10-30 22:01:50 +08:00
|
|
|
IO.mapOptional("BasedOnStyle", Format.BasedOnStyle);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2013-11-29 23:19:43 +08:00
|
|
|
// Allows to read vector<FormatStyle> while keeping default values.
|
2013-12-10 19:28:13 +08:00
|
|
|
// IO.getContext() should contain a pointer to the FormatStyle structure, that
|
|
|
|
// will be used to get default values for missing keys.
|
|
|
|
// If the first element has no Language specified, it will be treated as the
|
|
|
|
// default one for the following elements.
|
2015-02-19 07:48:37 +08:00
|
|
|
template <> struct DocumentListTraits<std::vector<FormatStyle>> {
|
2013-12-10 19:28:13 +08:00
|
|
|
static size_t size(IO &IO, std::vector<FormatStyle> &Seq) {
|
|
|
|
return Seq.size();
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
2013-12-10 19:28:13 +08:00
|
|
|
static FormatStyle &element(IO &IO, std::vector<FormatStyle> &Seq,
|
2013-12-10 18:30:34 +08:00
|
|
|
size_t Index) {
|
2013-12-10 19:28:13 +08:00
|
|
|
if (Index >= Seq.size()) {
|
|
|
|
assert(Index == Seq.size());
|
2013-12-10 18:30:34 +08:00
|
|
|
FormatStyle Template;
|
2017-11-09 23:12:17 +08:00
|
|
|
if (!Seq.empty() && Seq[0].Language == FormatStyle::LK_None) {
|
2013-11-29 23:19:43 +08:00
|
|
|
Template = Seq[0];
|
2013-12-10 19:28:13 +08:00
|
|
|
} else {
|
2014-05-09 21:11:16 +08:00
|
|
|
Template = *((const FormatStyle *)IO.getContext());
|
2013-12-10 18:30:34 +08:00
|
|
|
Template.Language = FormatStyle::LK_None;
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
2013-12-10 19:28:13 +08:00
|
|
|
Seq.resize(Index + 1, Template);
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
2013-12-10 19:28:13 +08:00
|
|
|
return Seq[Index];
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
|
|
|
};
|
2015-09-23 16:30:47 +08:00
|
|
|
} // namespace yaml
|
|
|
|
} // namespace llvm
|
2013-05-07 23:32:14 +08:00
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
namespace clang {
|
|
|
|
namespace format {
|
|
|
|
|
2014-06-12 11:31:26 +08:00
|
|
|
const std::error_category &getParseCategory() {
|
2018-03-21 05:52:19 +08:00
|
|
|
static const ParseErrorCategory C{};
|
2014-06-12 10:50:04 +08:00
|
|
|
return C;
|
|
|
|
}
|
|
|
|
std::error_code make_error_code(ParseError e) {
|
2014-06-12 11:31:26 +08:00
|
|
|
return std::error_code(static_cast<int>(e), getParseCategory());
|
2014-06-12 10:50:04 +08:00
|
|
|
}
|
|
|
|
|
2017-01-17 08:12:27 +08:00
|
|
|
inline llvm::Error make_string_error(const llvm::Twine &Message) {
|
|
|
|
return llvm::make_error<llvm::StringError>(Message,
|
|
|
|
llvm::inconvertibleErrorCode());
|
|
|
|
}
|
|
|
|
|
2016-10-20 07:39:55 +08:00
|
|
|
const char *ParseErrorCategory::name() const noexcept {
|
2014-06-12 10:50:04 +08:00
|
|
|
return "clang-format.parse_error";
|
|
|
|
}
|
|
|
|
|
|
|
|
std::string ParseErrorCategory::message(int EV) const {
|
|
|
|
switch (static_cast<ParseError>(EV)) {
|
|
|
|
case ParseError::Success:
|
|
|
|
return "Success";
|
|
|
|
case ParseError::Error:
|
|
|
|
return "Invalid argument";
|
|
|
|
case ParseError::Unsuitable:
|
|
|
|
return "Unsuitable";
|
|
|
|
}
|
2014-06-13 03:33:26 +08:00
|
|
|
llvm_unreachable("unexpected parse error");
|
2014-06-12 10:50:04 +08:00
|
|
|
}
|
|
|
|
|
2015-09-29 22:57:55 +08:00
|
|
|
static FormatStyle expandPresets(const FormatStyle &Style) {
|
2015-10-07 12:06:10 +08:00
|
|
|
if (Style.BreakBeforeBraces == FormatStyle::BS_Custom)
|
|
|
|
return Style;
|
2015-09-29 22:57:55 +08:00
|
|
|
FormatStyle Expanded = Style;
|
2017-09-20 17:51:03 +08:00
|
|
|
Expanded.BraceWrapping = {false, false, false, false, false,
|
|
|
|
false, false, false, false, false,
|
|
|
|
false, false, true, true, true};
|
2015-09-29 22:57:55 +08:00
|
|
|
switch (Style.BreakBeforeBraces) {
|
|
|
|
case FormatStyle::BS_Linux:
|
|
|
|
Expanded.BraceWrapping.AfterClass = true;
|
|
|
|
Expanded.BraceWrapping.AfterFunction = true;
|
|
|
|
Expanded.BraceWrapping.AfterNamespace = true;
|
|
|
|
break;
|
|
|
|
case FormatStyle::BS_Mozilla:
|
|
|
|
Expanded.BraceWrapping.AfterClass = true;
|
|
|
|
Expanded.BraceWrapping.AfterEnum = true;
|
|
|
|
Expanded.BraceWrapping.AfterFunction = true;
|
|
|
|
Expanded.BraceWrapping.AfterStruct = true;
|
|
|
|
Expanded.BraceWrapping.AfterUnion = true;
|
2017-09-15 19:23:50 +08:00
|
|
|
Expanded.BraceWrapping.AfterExternBlock = true;
|
2017-09-14 04:03:29 +08:00
|
|
|
Expanded.BraceWrapping.SplitEmptyFunction = true;
|
clang-format: add options to merge empty record body
Summary:
This patch introduces a few extra BraceWrapping options, similar to
`SplitEmptyFunction`, to allow merging empty 'record' bodies (e.g.
class, struct, union and namespace):
* SplitEmptyClass
* SplitEmptyStruct
* SplitEmptyUnion
* SplitEmptyNamespace
The `SplitEmptyFunction` option name has also been simplified/
shortened (from `SplitEmptyFunctionBody`).
These options are helpful when the correspond AfterXXX option is
enabled, to allow merging the empty record:
class Foo
{};
In addition, this fixes an unexpected merging of short records, when
the AfterXXXX options are used, which caused to be formatted like
this:
class Foo
{ void Foo(); };
This is now properly formatted as:
class Foo
{
void Foo();
};
Reviewers: djasper, krasimir
Reviewed By: djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D34395
llvm-svn: 306874
2017-07-01 04:25:55 +08:00
|
|
|
Expanded.BraceWrapping.SplitEmptyRecord = false;
|
2015-09-29 22:57:55 +08:00
|
|
|
break;
|
|
|
|
case FormatStyle::BS_Stroustrup:
|
|
|
|
Expanded.BraceWrapping.AfterFunction = true;
|
|
|
|
Expanded.BraceWrapping.BeforeCatch = true;
|
|
|
|
Expanded.BraceWrapping.BeforeElse = true;
|
|
|
|
break;
|
|
|
|
case FormatStyle::BS_Allman:
|
|
|
|
Expanded.BraceWrapping.AfterClass = true;
|
|
|
|
Expanded.BraceWrapping.AfterControlStatement = true;
|
|
|
|
Expanded.BraceWrapping.AfterEnum = true;
|
|
|
|
Expanded.BraceWrapping.AfterFunction = true;
|
|
|
|
Expanded.BraceWrapping.AfterNamespace = true;
|
|
|
|
Expanded.BraceWrapping.AfterObjCDeclaration = true;
|
|
|
|
Expanded.BraceWrapping.AfterStruct = true;
|
2017-09-15 19:23:50 +08:00
|
|
|
Expanded.BraceWrapping.AfterExternBlock = true;
|
2015-09-29 22:57:55 +08:00
|
|
|
Expanded.BraceWrapping.BeforeCatch = true;
|
|
|
|
Expanded.BraceWrapping.BeforeElse = true;
|
|
|
|
break;
|
|
|
|
case FormatStyle::BS_GNU:
|
2017-09-20 17:51:03 +08:00
|
|
|
Expanded.BraceWrapping = {true, true, true, true, true, true, true, true,
|
|
|
|
true, true, true, true, true, true, true};
|
2015-09-29 22:57:55 +08:00
|
|
|
break;
|
|
|
|
case FormatStyle::BS_WebKit:
|
|
|
|
Expanded.BraceWrapping.AfterFunction = true;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
return Expanded;
|
|
|
|
}
|
|
|
|
|
2019-03-01 03:16:45 +08:00
|
|
|
FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) {
|
2012-12-04 02:12:45 +08:00
|
|
|
FormatStyle LLVMStyle;
|
2019-03-01 03:16:45 +08:00
|
|
|
LLVMStyle.Language = Language;
|
2012-12-04 02:12:45 +08:00
|
|
|
LLVMStyle.AccessModifierOffset = -2;
|
2017-05-08 23:08:00 +08:00
|
|
|
LLVMStyle.AlignEscapedNewlines = FormatStyle::ENAS_Right;
|
2015-10-27 20:38:37 +08:00
|
|
|
LLVMStyle.AlignAfterOpenBracket = FormatStyle::BAS_Align;
|
2014-12-02 21:24:51 +08:00
|
|
|
LLVMStyle.AlignOperands = true;
|
2013-08-01 07:55:15 +08:00
|
|
|
LLVMStyle.AlignTrailingComments = true;
|
2015-04-29 21:06:49 +08:00
|
|
|
LLVMStyle.AlignConsecutiveAssignments = false;
|
2015-10-01 18:06:54 +08:00
|
|
|
LLVMStyle.AlignConsecutiveDeclarations = false;
|
2013-01-30 00:03:49 +08:00
|
|
|
LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
|
2014-04-08 20:46:38 +08:00
|
|
|
LLVMStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
|
2014-05-14 17:33:35 +08:00
|
|
|
LLVMStyle.AllowShortBlocksOnASingleLine = false;
|
2014-09-10 21:11:45 +08:00
|
|
|
LLVMStyle.AllowShortCaseLabelsOnASingleLine = false;
|
2019-03-13 16:26:39 +08:00
|
|
|
LLVMStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
|
2013-05-16 20:12:21 +08:00
|
|
|
LLVMStyle.AllowShortLoopsOnASingleLine = false;
|
2015-12-19 06:20:15 +08:00
|
|
|
LLVMStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
|
2015-06-29 23:30:42 +08:00
|
|
|
LLVMStyle.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_None;
|
2013-07-04 20:02:44 +08:00
|
|
|
LLVMStyle.AlwaysBreakBeforeMultilineStrings = false;
|
2018-05-16 16:25:03 +08:00
|
|
|
LLVMStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_MultiLine;
|
2014-10-09 17:52:05 +08:00
|
|
|
LLVMStyle.BinPackArguments = true;
|
2017-06-14 20:29:47 +08:00
|
|
|
LLVMStyle.BinPackParameters = true;
|
2014-09-15 19:11:00 +08:00
|
|
|
LLVMStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
|
2013-11-08 08:57:11 +08:00
|
|
|
LLVMStyle.BreakBeforeTernaryOperators = true;
|
2013-07-27 00:56:36 +08:00
|
|
|
LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
|
2017-09-20 17:51:03 +08:00
|
|
|
LLVMStyle.BraceWrapping = {false, false, false, false, false,
|
|
|
|
false, false, false, false, false,
|
|
|
|
false, false, true, true, true};
|
2015-10-16 00:03:01 +08:00
|
|
|
LLVMStyle.BreakAfterJavaFieldAnnotations = false;
|
2017-05-24 19:36:58 +08:00
|
|
|
LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
|
2018-06-11 22:41:26 +08:00
|
|
|
LLVMStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
|
2016-02-01 19:21:02 +08:00
|
|
|
LLVMStyle.BreakStringLiterals = true;
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.ColumnLimit = 80;
|
2014-04-01 20:55:11 +08:00
|
|
|
LLVMStyle.CommentPragmas = "^ IWYU pragma:";
|
2017-06-14 20:29:47 +08:00
|
|
|
LLVMStyle.CompactNamespaces = false;
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
|
2013-08-13 18:58:30 +08:00
|
|
|
LLVMStyle.ConstructorInitializerIndentWidth = 4;
|
2014-04-01 20:55:11 +08:00
|
|
|
LLVMStyle.ContinuationIndentWidth = 4;
|
2014-03-02 20:37:31 +08:00
|
|
|
LLVMStyle.Cpp11BracedListStyle = true;
|
2014-06-17 20:40:34 +08:00
|
|
|
LLVMStyle.DerivePointerAlignment = false;
|
2013-07-10 22:02:49 +08:00
|
|
|
LLVMStyle.ExperimentalAutoDetectBinPacking = false;
|
2017-03-01 23:35:39 +08:00
|
|
|
LLVMStyle.FixNamespaceComments = true;
|
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");
|
2018-05-15 03:51:33 +08:00
|
|
|
LLVMStyle.IncludeStyle.IncludeCategories = {
|
|
|
|
{"^\"(llvm|llvm-c|clang|clang-c)/", 2},
|
|
|
|
{"^(<|\"(gtest|gmock|isl|json)/)", 3},
|
|
|
|
{".*", 1}};
|
|
|
|
LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
|
|
|
|
LLVMStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve;
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.IndentCaseLabels = false;
|
clang-format: Add preprocessor directive indentation
Summary:
This is an implementation for [bug 17362](https://bugs.llvm.org/attachment.cgi?bugid=17362) which adds support for indenting preprocessor statements inside if/ifdef/endif. This takes previous work from fmauch (https://github.com/fmauch/clang/tree/preprocessor_indent) and makes it into a full feature.
The context of this patch is that I'm a VMware intern, and I implemented this because VMware needs the feature. As such, some decisions were made based on what VMware wants, and I would appreciate suggestions on expanding this if necessary to use-cases other people may want.
This adds a new enum config option, `IndentPPDirectives`. Values are:
* `PPDIS_None` (in config: `None`):
```
#if FOO
#if BAR
#include <foo>
#endif
#endif
```
* `PPDIS_AfterHash` (in config: `AfterHash`):
```
#if FOO
# if BAR
# include <foo>
# endif
#endif
```
This is meant to work whether spaces or tabs are used for indentation. Preprocessor indentation is independent of indentation for non-preprocessor lines.
Preprocessor indentation also attempts to ignore include guards with the checks:
1. Include guards cover the entire file
2. Include guards don't have `#else`
3. Include guards begin with
```
#ifndef <var>
#define <var>
```
This patch allows `UnwrappedLineParser::PPBranchLevel` to be decremented to -1 (the initial value is -1) so the variable can be used for indent tracking.
Defects:
* This patch does not handle the case where there's code between the `#ifndef` and `#define` but all other conditions hold. This is because when the #define line is parsed, `UnwrappedLineParser::Lines` doesn't hold the previous code line yet, so we can't detect it. This is out of the scope of this patch.
* This patch does not handle cases where legitimate lines may be outside an include guard. Examples are `#pragma once` and `#pragma GCC diagnostic`, or anything else that does not change the meaning of the file if it's included multiple times.
* This does not detect when there is a single non-preprocessor line in front of an include-guard-like structure where other conditions hold because `ScopedLineState` hides the line.
* Preprocessor indentation throws off `TokenAnnotator::setCommentLineLevels` so the indentation of comments immediately before indented preprocessor lines is toggled on each run. Fixing this issue appears to be a major change and too much complexity for this patch.
Contributed by @euhlmann!
Reviewers: djasper, klimek, krasimir
Reviewed By: djasper, krasimir
Subscribers: krasimir, mzeren-vmw, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D35955
llvm-svn: 312125
2017-08-30 22:34:57 +08:00
|
|
|
LLVMStyle.IndentPPDirectives = FormatStyle::PPDIS_None;
|
2014-07-09 16:42:42 +08:00
|
|
|
LLVMStyle.IndentWrappedFunctionNames = false;
|
2013-07-27 00:56:36 +08:00
|
|
|
LLVMStyle.IndentWidth = 2;
|
2016-06-14 01:50:10 +08:00
|
|
|
LLVMStyle.JavaScriptQuotes = FormatStyle::JSQS_Leave;
|
|
|
|
LLVMStyle.JavaScriptWrapImports = true;
|
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;
|
2018-02-03 04:15:14 +08:00
|
|
|
LLVMStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
|
2014-10-29 00:53:38 +08:00
|
|
|
LLVMStyle.ObjCBlockIndentWidth = 2;
|
2014-01-28 23:20:33 +08:00
|
|
|
LLVMStyle.ObjCSpaceAfterProperty = false;
|
2013-01-11 04:12:55 +08:00
|
|
|
LLVMStyle.ObjCSpaceBeforeProtocolList = true;
|
2014-06-17 20:40:34 +08:00
|
|
|
LLVMStyle.PointerAlignment = FormatStyle::PAS_Right;
|
2013-05-06 22:11:27 +08:00
|
|
|
LLVMStyle.SpacesBeforeTrailingComments = 1;
|
2014-03-02 20:37:31 +08:00
|
|
|
LLVMStyle.Standard = FormatStyle::LS_Cpp11;
|
2013-09-28 00:14:22 +08:00
|
|
|
LLVMStyle.UseTab = FormatStyle::UT_Never;
|
2015-12-01 21:28:53 +08:00
|
|
|
LLVMStyle.ReflowComments = true;
|
2013-08-20 20:36:34 +08:00
|
|
|
LLVMStyle.SpacesInParentheses = false;
|
2014-08-26 19:41:14 +08:00
|
|
|
LLVMStyle.SpacesInSquareBrackets = false;
|
2013-08-20 20:36:34 +08:00
|
|
|
LLVMStyle.SpaceInEmptyParentheses = false;
|
2014-01-15 23:09:08 +08:00
|
|
|
LLVMStyle.SpacesInContainerLiterals = true;
|
2013-08-20 20:36:34 +08:00
|
|
|
LLVMStyle.SpacesInCStyleCastParentheses = false;
|
2014-09-03 15:37:29 +08:00
|
|
|
LLVMStyle.SpaceAfterCStyleCast = false;
|
2016-08-09 22:24:40 +08:00
|
|
|
LLVMStyle.SpaceAfterTemplateKeyword = true;
|
[clang-format] Add SpaceBeforeColon option
Summary:
When disabled, this option allows removing the space before colon,
making it act more like the semi-colon. When enabled (default), the
current behavior is not affected.
This mostly affects C++11 loop, initializer list, inheritance list and
container literals:
class Foo: Bar {}
Foo::Foo(): a(a) {}
for (auto i: myList) {}
f({a: 1, b: 2, c: 3});
Reviewers: krasimir, djasper
Reviewed By: djasper
Subscribers: xvallspl, teemperor, karies, cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D32525
llvm-svn: 326426
2018-03-01 18:09:13 +08:00
|
|
|
LLVMStyle.SpaceBeforeCtorInitializerColon = true;
|
|
|
|
LLVMStyle.SpaceBeforeInheritanceColon = true;
|
2013-12-10 18:18:34 +08:00
|
|
|
LLVMStyle.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
|
[clang-format] Add SpaceBeforeColon option
Summary:
When disabled, this option allows removing the space before colon,
making it act more like the semi-colon. When enabled (default), the
current behavior is not affected.
This mostly affects C++11 loop, initializer list, inheritance list and
container literals:
class Foo: Bar {}
Foo::Foo(): a(a) {}
for (auto i: myList) {}
f({a: 1, b: 2, c: 3});
Reviewers: krasimir, djasper
Reviewed By: djasper
Subscribers: xvallspl, teemperor, karies, cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D32525
llvm-svn: 326426
2018-03-01 18:09:13 +08:00
|
|
|
LLVMStyle.SpaceBeforeRangeBasedForLoopColon = true;
|
2013-09-25 23:15:02 +08:00
|
|
|
LLVMStyle.SpaceBeforeAssignmentOperators = true;
|
2018-06-14 16:01:09 +08:00
|
|
|
LLVMStyle.SpaceBeforeCpp11BracedList = false;
|
2013-10-29 22:52:02 +08:00
|
|
|
LLVMStyle.SpacesInAngles = false;
|
2013-07-12 04:41:21 +08:00
|
|
|
|
2017-05-22 16:28:17 +08:00
|
|
|
LLVMStyle.PenaltyBreakAssignment = prec::Assignment;
|
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;
|
2018-05-16 16:25:03 +08:00
|
|
|
LLVMStyle.PenaltyBreakTemplateDeclaration = prec::Relational;
|
2013-07-12 04:41:21 +08:00
|
|
|
|
2014-05-22 23:12:22 +08:00
|
|
|
LLVMStyle.DisableFormat = false;
|
2015-11-16 20:38:56 +08:00
|
|
|
LLVMStyle.SortIncludes = true;
|
2017-06-23 19:46:03 +08:00
|
|
|
LLVMStyle.SortUsingDeclarations = true;
|
clang-format: better handle statement macros
Summary:
Some macros are used in the body of function, and actually contain the trailing semicolon: they should thus be automatically followed by a new line, and not get merged with the next line. This is for example the case with Qt's Q_UNUSED macro:
void foo(int a, int b) {
Q_UNUSED(a)
return b;
}
This patch deals with these cases by introducing a new option to specify list of statement macros. This re-uses the system already in place for foreach macros, to ensure there is no impact on performance.
Reviewers: krasimir, djasper, klimek
Reviewed By: krasimir
Subscribers: acoomans, mgrang, alexfh, klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D33440
llvm-svn: 343602
2018-10-03 00:37:51 +08:00
|
|
|
LLVMStyle.StatementMacros.push_back("Q_UNUSED");
|
|
|
|
LLVMStyle.StatementMacros.push_back("QT_REQUIRE_VERSION");
|
2014-05-22 23:12:22 +08:00
|
|
|
|
[clang-format][TableGen] Don't add spaces around items in square braces.
Summary:
clang-formatting wants to add spaces around items in square braces, e.g. [1, 2] -> [ 1, 2 ]. Based on a quick check [1], it seems like most cases are using the [1, 2] format, so make that the consistent one.
[1] in llvm `.td` files, the regex `\[[^ ]` (bracket followed by not-a-space) shows up ~400 times, but `\[\s[^ ]` (bracket followed by one space and one not-a-space) shows up ~40 times => ~90% uses this format.
Reviewers: djasper, krasimir, MyDeveloperDay
Reviewed By: MyDeveloperDay
Subscribers: MyDeveloperDay, arphaman, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D55964
llvm-svn: 355158
2019-03-01 08:12:18 +08:00
|
|
|
// Defaults that differ when not C++.
|
|
|
|
if (Language == FormatStyle::LK_TableGen) {
|
|
|
|
LLVMStyle.SpacesInContainerLiterals = false;
|
|
|
|
}
|
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
return LLVMStyle;
|
|
|
|
}
|
|
|
|
|
2014-02-03 04:50:45 +08:00
|
|
|
FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
|
2017-07-03 23:05:14 +08:00
|
|
|
if (Language == FormatStyle::LK_TextProto) {
|
|
|
|
FormatStyle GoogleStyle = getGoogleStyle(FormatStyle::LK_Proto);
|
|
|
|
GoogleStyle.Language = FormatStyle::LK_TextProto;
|
2018-01-24 19:18:39 +08:00
|
|
|
|
2017-07-03 23:05:14 +08:00
|
|
|
return GoogleStyle;
|
|
|
|
}
|
|
|
|
|
2019-03-01 03:16:45 +08:00
|
|
|
FormatStyle GoogleStyle = getLLVMStyle(Language);
|
2014-02-03 04:50:45 +08:00
|
|
|
|
2012-12-04 02:12:45 +08:00
|
|
|
GoogleStyle.AccessModifierOffset = -1;
|
2017-05-08 23:08:00 +08:00
|
|
|
GoogleStyle.AlignEscapedNewlines = FormatStyle::ENAS_Left;
|
2019-03-13 16:26:39 +08:00
|
|
|
GoogleStyle.AllowShortIfStatementsOnASingleLine =
|
|
|
|
FormatStyle::SIS_WithoutElse;
|
2013-05-24 02:05:18 +08:00
|
|
|
GoogleStyle.AllowShortLoopsOnASingleLine = true;
|
2013-07-04 20:02:44 +08:00
|
|
|
GoogleStyle.AlwaysBreakBeforeMultilineStrings = true;
|
2018-05-16 16:25:03 +08:00
|
|
|
GoogleStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
|
2013-05-06 22:11:27 +08:00
|
|
|
GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
|
2014-06-17 20:40:34 +08:00
|
|
|
GoogleStyle.DerivePointerAlignment = true;
|
2018-05-15 03:51:33 +08:00
|
|
|
GoogleStyle.IncludeStyle.IncludeCategories = {
|
2017-09-26 22:58:29 +08:00
|
|
|
{"^<ext/.*\\.h>", 2}, {"^<.*\\.h>", 1}, {"^<.*", 2}, {".*", 3}};
|
2018-05-15 03:51:33 +08:00
|
|
|
GoogleStyle.IncludeStyle.IncludeIsMainRegex = "([-_](test|unittest))?$";
|
2013-05-06 22:11:27 +08:00
|
|
|
GoogleStyle.IndentCaseLabels = true;
|
2014-03-21 21:43:14 +08:00
|
|
|
GoogleStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
|
2018-02-08 09:49:10 +08:00
|
|
|
GoogleStyle.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
|
2014-01-28 23:20:33 +08:00
|
|
|
GoogleStyle.ObjCSpaceAfterProperty = false;
|
2018-01-19 02:37:16 +08:00
|
|
|
GoogleStyle.ObjCSpaceBeforeProtocolList = true;
|
2014-06-17 20:40:34 +08:00
|
|
|
GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
|
2018-04-25 22:56:19 +08:00
|
|
|
GoogleStyle.RawStringFormats = {
|
2018-01-17 20:24:59 +08:00
|
|
|
{
|
2018-04-25 22:56:19 +08:00
|
|
|
FormatStyle::LK_Cpp,
|
|
|
|
/*Delimiters=*/
|
|
|
|
{
|
|
|
|
"cc",
|
|
|
|
"CC",
|
|
|
|
"cpp",
|
|
|
|
"Cpp",
|
|
|
|
"CPP",
|
|
|
|
"c++",
|
|
|
|
"C++",
|
|
|
|
},
|
|
|
|
/*EnclosingFunctionNames=*/
|
|
|
|
{},
|
|
|
|
/*CanonicalDelimiter=*/"",
|
|
|
|
/*BasedOnStyle=*/"google",
|
2018-01-17 20:24:59 +08:00
|
|
|
},
|
2018-04-25 22:56:19 +08:00
|
|
|
{
|
|
|
|
FormatStyle::LK_TextProto,
|
|
|
|
/*Delimiters=*/
|
|
|
|
{
|
|
|
|
"pb",
|
|
|
|
"PB",
|
|
|
|
"proto",
|
|
|
|
"PROTO",
|
|
|
|
},
|
|
|
|
/*EnclosingFunctionNames=*/
|
2018-06-26 20:00:14 +08:00
|
|
|
{
|
|
|
|
"EqualsProto",
|
2018-06-29 22:25:25 +08:00
|
|
|
"EquivToProto",
|
2018-08-01 20:35:23 +08:00
|
|
|
"PARSE_PARTIAL_TEXT_PROTO",
|
2018-06-29 22:25:25 +08:00
|
|
|
"PARSE_TEST_PROTO",
|
|
|
|
"PARSE_TEXT_PROTO",
|
|
|
|
"ParseTextOrDie",
|
2018-08-01 20:35:23 +08:00
|
|
|
"ParseTextProtoOrDie",
|
2018-06-26 20:00:14 +08:00
|
|
|
},
|
2018-04-25 22:56:19 +08:00
|
|
|
/*CanonicalDelimiter=*/"",
|
|
|
|
/*BasedOnStyle=*/"google",
|
|
|
|
},
|
|
|
|
};
|
2013-05-06 22:11:27 +08:00
|
|
|
GoogleStyle.SpacesBeforeTrailingComments = 2;
|
|
|
|
GoogleStyle.Standard = FormatStyle::LS_Auto;
|
2013-07-12 04:41:21 +08:00
|
|
|
|
|
|
|
GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
|
2013-10-25 22:29:37 +08:00
|
|
|
GoogleStyle.PenaltyBreakBeforeFirstCallParameter = 1;
|
2013-07-12 04:41:21 +08:00
|
|
|
|
2014-09-15 19:21:46 +08:00
|
|
|
if (Language == FormatStyle::LK_Java) {
|
2015-10-27 20:38:37 +08:00
|
|
|
GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
|
2014-12-02 21:24:51 +08:00
|
|
|
GoogleStyle.AlignOperands = false;
|
2015-01-05 04:40:45 +08:00
|
|
|
GoogleStyle.AlignTrailingComments = false;
|
2014-11-26 18:43:58 +08:00
|
|
|
GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
|
2019-03-13 16:26:39 +08:00
|
|
|
GoogleStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
|
2015-01-14 20:24:59 +08:00
|
|
|
GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
|
2014-09-15 19:21:46 +08:00
|
|
|
GoogleStyle.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
|
|
|
|
GoogleStyle.ColumnLimit = 100;
|
|
|
|
GoogleStyle.SpaceAfterCStyleCast = true;
|
2014-11-14 16:22:46 +08:00
|
|
|
GoogleStyle.SpacesBeforeTrailingComments = 1;
|
2014-09-15 19:21:46 +08:00
|
|
|
} else if (Language == FormatStyle::LK_JavaScript) {
|
2015-10-27 20:38:37 +08:00
|
|
|
GoogleStyle.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
|
2015-12-21 21:52:19 +08:00
|
|
|
GoogleStyle.AlignOperands = false;
|
2016-09-08 07:01:13 +08:00
|
|
|
GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
|
2015-10-27 20:38:37 +08:00
|
|
|
GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
|
2014-11-06 01:22:31 +08:00
|
|
|
GoogleStyle.BreakBeforeTernaryOperators = false;
|
2018-07-30 16:45:45 +08:00
|
|
|
// taze:, triple slash directives (`/// <...`), @see, which is commonly
|
|
|
|
// followed by overlong URLs.
|
|
|
|
GoogleStyle.CommentPragmas = "(taze:|^/[ \t]*<|@see)";
|
2014-05-09 18:28:58 +08:00
|
|
|
GoogleStyle.MaxEmptyLinesToKeep = 3;
|
2016-06-14 00:41:28 +08:00
|
|
|
GoogleStyle.NamespaceIndentation = FormatStyle::NI_All;
|
2014-02-03 04:50:45 +08:00
|
|
|
GoogleStyle.SpacesInContainerLiterals = false;
|
2016-03-03 06:44:03 +08:00
|
|
|
GoogleStyle.JavaScriptQuotes = FormatStyle::JSQS_Single;
|
2016-06-14 00:39:50 +08:00
|
|
|
GoogleStyle.JavaScriptWrapImports = false;
|
2014-02-03 04:50:45 +08:00
|
|
|
} else if (Language == FormatStyle::LK_Proto) {
|
2018-08-16 03:07:55 +08:00
|
|
|
GoogleStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
|
2018-03-12 18:32:18 +08:00
|
|
|
GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
|
2014-04-15 17:54:30 +08:00
|
|
|
GoogleStyle.SpacesInContainerLiterals = false;
|
2018-01-31 18:14:10 +08:00
|
|
|
GoogleStyle.Cpp11BracedListStyle = false;
|
2018-02-08 18:47:12 +08:00
|
|
|
// This affects protocol buffer options specifications and text protos.
|
|
|
|
// Text protos are currently mostly formatted inside C++ raw string literals
|
|
|
|
// and often the current breaking behavior of string literals is not
|
|
|
|
// beneficial there. Investigate turning this on once proper string reflow
|
|
|
|
// has been implemented.
|
|
|
|
GoogleStyle.BreakStringLiterals = false;
|
2016-12-12 20:42:29 +08:00
|
|
|
} else if (Language == FormatStyle::LK_ObjC) {
|
2018-06-15 01:30:10 +08:00
|
|
|
GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
|
2016-12-12 20:42:29 +08:00
|
|
|
GoogleStyle.ColumnLimit = 100;
|
2014-02-03 04:50:45 +08:00
|
|
|
}
|
2013-12-10 19:28:13 +08:00
|
|
|
|
2014-02-03 04:50:45 +08:00
|
|
|
return GoogleStyle;
|
2014-01-19 17:04:08 +08:00
|
|
|
}
|
|
|
|
|
2014-02-03 04:50:45 +08:00
|
|
|
FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {
|
|
|
|
FormatStyle ChromiumStyle = getGoogleStyle(Language);
|
2014-11-27 00:43:18 +08:00
|
|
|
if (Language == FormatStyle::LK_Java) {
|
2019-03-13 16:26:39 +08:00
|
|
|
ChromiumStyle.AllowShortIfStatementsOnASingleLine =
|
|
|
|
FormatStyle::SIS_WithoutElse;
|
2015-10-16 00:03:01 +08:00
|
|
|
ChromiumStyle.BreakAfterJavaFieldAnnotations = true;
|
2014-11-27 00:43:18 +08:00
|
|
|
ChromiumStyle.ContinuationIndentWidth = 8;
|
2015-10-16 00:03:01 +08:00
|
|
|
ChromiumStyle.IndentWidth = 4;
|
2018-10-06 01:19:26 +08:00
|
|
|
// See styleguide for import groups:
|
|
|
|
// https://chromium.googlesource.com/chromium/src/+/master/styleguide/java/java.md#Import-Order
|
|
|
|
ChromiumStyle.JavaImportGroups = {
|
2019-03-01 17:09:54 +08:00
|
|
|
"android", "com", "dalvik",
|
|
|
|
"junit", "org", "com.google.android.apps.chrome",
|
|
|
|
"org.chromium", "java", "javax",
|
2018-10-06 01:19:26 +08:00
|
|
|
};
|
|
|
|
ChromiumStyle.SortIncludes = true;
|
2017-01-04 10:33:36 +08:00
|
|
|
} else if (Language == FormatStyle::LK_JavaScript) {
|
2019-03-13 16:26:39 +08:00
|
|
|
ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
|
2017-01-04 10:33:36 +08:00
|
|
|
ChromiumStyle.AllowShortLoopsOnASingleLine = false;
|
2014-11-27 00:43:18 +08:00
|
|
|
} else {
|
|
|
|
ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
|
|
|
|
ChromiumStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
|
2019-03-13 16:26:39 +08:00
|
|
|
ChromiumStyle.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Never;
|
2014-11-27 00:43:18 +08:00
|
|
|
ChromiumStyle.AllowShortLoopsOnASingleLine = false;
|
|
|
|
ChromiumStyle.BinPackParameters = false;
|
|
|
|
ChromiumStyle.DerivePointerAlignment = false;
|
2017-02-01 02:42:05 +08:00
|
|
|
if (Language == FormatStyle::LK_ObjC)
|
|
|
|
ChromiumStyle.ColumnLimit = 80;
|
2014-11-27 00:43:18 +08:00
|
|
|
}
|
2013-01-15 00:24:39 +08:00
|
|
|
return ChromiumStyle;
|
|
|
|
}
|
|
|
|
|
2013-05-06 22:11:27 +08:00
|
|
|
FormatStyle getMozillaStyle() {
|
|
|
|
FormatStyle MozillaStyle = getLLVMStyle();
|
|
|
|
MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
|
2015-06-29 23:18:58 +08:00
|
|
|
MozillaStyle.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
|
2017-09-20 17:51:03 +08:00
|
|
|
MozillaStyle.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
|
2015-06-29 23:30:42 +08:00
|
|
|
MozillaStyle.AlwaysBreakAfterDefinitionReturnType =
|
|
|
|
FormatStyle::DRTBS_TopLevel;
|
2018-05-16 16:25:03 +08:00
|
|
|
MozillaStyle.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
|
2016-12-15 00:09:29 +08:00
|
|
|
MozillaStyle.BinPackParameters = false;
|
|
|
|
MozillaStyle.BinPackArguments = false;
|
2015-07-12 11:13:54 +08:00
|
|
|
MozillaStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
|
2017-05-24 19:36:58 +08:00
|
|
|
MozillaStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
|
2018-06-11 22:41:26 +08:00
|
|
|
MozillaStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
|
2015-06-29 23:18:58 +08:00
|
|
|
MozillaStyle.ConstructorInitializerIndentWidth = 2;
|
|
|
|
MozillaStyle.ContinuationIndentWidth = 2;
|
2014-03-02 20:37:31 +08:00
|
|
|
MozillaStyle.Cpp11BracedListStyle = false;
|
2017-03-01 23:35:39 +08:00
|
|
|
MozillaStyle.FixNamespaceComments = false;
|
2013-05-06 22:11:27 +08:00
|
|
|
MozillaStyle.IndentCaseLabels = true;
|
2014-01-28 23:20:33 +08:00
|
|
|
MozillaStyle.ObjCSpaceAfterProperty = true;
|
2013-05-06 22:11:27 +08:00
|
|
|
MozillaStyle.ObjCSpaceBeforeProtocolList = false;
|
|
|
|
MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
|
2014-06-17 20:40:34 +08:00
|
|
|
MozillaStyle.PointerAlignment = FormatStyle::PAS_Left;
|
2016-08-09 22:24:40 +08:00
|
|
|
MozillaStyle.SpaceAfterTemplateKeyword = false;
|
2013-05-06 22:11:27 +08:00
|
|
|
return MozillaStyle;
|
|
|
|
}
|
|
|
|
|
2013-07-24 21:10:59 +08:00
|
|
|
FormatStyle getWebKitStyle() {
|
|
|
|
FormatStyle Style = getLLVMStyle();
|
2013-08-01 07:16:02 +08:00
|
|
|
Style.AccessModifierOffset = -4;
|
2015-10-27 20:38:37 +08:00
|
|
|
Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
|
2014-12-02 21:24:51 +08:00
|
|
|
Style.AlignOperands = false;
|
2013-08-01 07:55:15 +08:00
|
|
|
Style.AlignTrailingComments = false;
|
2014-09-15 19:11:00 +08:00
|
|
|
Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
|
2015-08-10 21:43:19 +08:00
|
|
|
Style.BreakBeforeBraces = FormatStyle::BS_WebKit;
|
2017-05-24 19:36:58 +08:00
|
|
|
Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
|
2014-03-02 20:37:31 +08:00
|
|
|
Style.Cpp11BracedListStyle = false;
|
2013-08-01 07:16:02 +08:00
|
|
|
Style.ColumnLimit = 0;
|
2017-03-01 23:35:39 +08:00
|
|
|
Style.FixNamespaceComments = false;
|
2013-07-27 00:56:36 +08:00
|
|
|
Style.IndentWidth = 4;
|
2013-08-01 07:16:02 +08:00
|
|
|
Style.NamespaceIndentation = FormatStyle::NI_Inner;
|
2014-10-29 00:53:38 +08:00
|
|
|
Style.ObjCBlockIndentWidth = 4;
|
2014-01-28 23:20:33 +08:00
|
|
|
Style.ObjCSpaceAfterProperty = true;
|
2014-06-17 20:40:34 +08:00
|
|
|
Style.PointerAlignment = FormatStyle::PAS_Left;
|
2018-06-14 16:01:09 +08:00
|
|
|
Style.SpaceBeforeCpp11BracedList = true;
|
2013-07-24 21:10:59 +08:00
|
|
|
return Style;
|
|
|
|
}
|
|
|
|
|
2013-12-10 23:42:15 +08:00
|
|
|
FormatStyle getGNUStyle() {
|
|
|
|
FormatStyle Style = getLLVMStyle();
|
2015-06-29 23:30:42 +08:00
|
|
|
Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
|
2015-12-19 06:20:15 +08:00
|
|
|
Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
|
2014-09-15 19:11:00 +08:00
|
|
|
Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
|
2013-12-12 17:49:52 +08:00
|
|
|
Style.BreakBeforeBraces = FormatStyle::BS_GNU;
|
2013-12-10 23:42:15 +08:00
|
|
|
Style.BreakBeforeTernaryOperators = true;
|
2014-03-02 20:37:31 +08:00
|
|
|
Style.Cpp11BracedListStyle = false;
|
2013-12-10 23:42:15 +08:00
|
|
|
Style.ColumnLimit = 79;
|
2017-03-01 23:35:39 +08:00
|
|
|
Style.FixNamespaceComments = false;
|
2013-12-10 23:42:15 +08:00
|
|
|
Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
|
2014-03-02 20:37:31 +08:00
|
|
|
Style.Standard = FormatStyle::LS_Cpp03;
|
2013-12-10 23:42:15 +08:00
|
|
|
return Style;
|
|
|
|
}
|
|
|
|
|
2014-05-22 23:12:22 +08:00
|
|
|
FormatStyle getNoStyle() {
|
|
|
|
FormatStyle NoStyle = getLLVMStyle();
|
|
|
|
NoStyle.DisableFormat = true;
|
2015-11-16 20:38:56 +08:00
|
|
|
NoStyle.SortIncludes = false;
|
2017-06-23 19:46:03 +08:00
|
|
|
NoStyle.SortUsingDeclarations = false;
|
2014-05-22 23:12:22 +08:00
|
|
|
return NoStyle;
|
|
|
|
}
|
|
|
|
|
2013-12-10 19:28:13 +08:00
|
|
|
bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
|
|
|
|
FormatStyle *Style) {
|
|
|
|
if (Name.equals_lower("llvm")) {
|
2019-03-14 05:13:01 +08:00
|
|
|
*Style = getLLVMStyle(Language);
|
2013-12-10 19:28:13 +08:00
|
|
|
} else if (Name.equals_lower("chromium")) {
|
2014-02-03 04:50:45 +08:00
|
|
|
*Style = getChromiumStyle(Language);
|
2013-12-10 19:28:13 +08:00
|
|
|
} else if (Name.equals_lower("mozilla")) {
|
2013-05-19 08:53:30 +08:00
|
|
|
*Style = getMozillaStyle();
|
2013-12-10 19:28:13 +08:00
|
|
|
} else if (Name.equals_lower("google")) {
|
2014-02-03 04:50:45 +08:00
|
|
|
*Style = getGoogleStyle(Language);
|
2013-12-10 19:28:13 +08:00
|
|
|
} else if (Name.equals_lower("webkit")) {
|
2013-07-24 21:10:59 +08:00
|
|
|
*Style = getWebKitStyle();
|
2013-12-10 23:42:15 +08:00
|
|
|
} else if (Name.equals_lower("gnu")) {
|
|
|
|
*Style = getGNUStyle();
|
2014-05-22 23:12:22 +08:00
|
|
|
} else if (Name.equals_lower("none")) {
|
|
|
|
*Style = getNoStyle();
|
2013-12-10 19:28:13 +08:00
|
|
|
} else {
|
2013-05-19 08:53:30 +08:00
|
|
|
return false;
|
2013-12-10 19:28:13 +08:00
|
|
|
}
|
2013-05-07 23:32:14 +08:00
|
|
|
|
2013-12-10 19:28:13 +08:00
|
|
|
Style->Language = Language;
|
2013-05-19 08:53:30 +08:00
|
|
|
return true;
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
|
2014-06-12 22:02:15 +08:00
|
|
|
std::error_code parseConfiguration(StringRef Text, FormatStyle *Style) {
|
2013-11-29 23:19:43 +08:00
|
|
|
assert(Style);
|
2013-12-10 19:28:13 +08:00
|
|
|
FormatStyle::LanguageKind Language = Style->Language;
|
|
|
|
assert(Language != FormatStyle::LK_None);
|
2013-05-20 23:18:01 +08:00
|
|
|
if (Text.trim().empty())
|
2014-06-12 10:50:04 +08:00
|
|
|
return make_error_code(ParseError::Error);
|
2018-01-15 20:06:16 +08:00
|
|
|
Style->StyleSet.Clear();
|
2013-11-29 23:19:43 +08:00
|
|
|
std::vector<FormatStyle> Styles;
|
2013-05-07 23:32:14 +08:00
|
|
|
llvm::yaml::Input Input(Text);
|
2013-12-10 19:28:13 +08:00
|
|
|
// DocumentListTraits<vector<FormatStyle>> uses the context to get default
|
|
|
|
// values for the fields, keys for which are missing from the configuration.
|
|
|
|
// Mapping also uses the context to get the language to find the correct
|
|
|
|
// base style.
|
|
|
|
Input.setContext(Style);
|
2013-11-29 23:19:43 +08:00
|
|
|
Input >> Styles;
|
|
|
|
if (Input.error())
|
|
|
|
return Input.error();
|
|
|
|
|
2013-12-10 19:28:13 +08:00
|
|
|
for (unsigned i = 0; i < Styles.size(); ++i) {
|
2013-11-29 23:19:43 +08:00
|
|
|
// Ensures that only the first configuration can skip the Language option.
|
2013-12-10 19:28:13 +08:00
|
|
|
if (Styles[i].Language == FormatStyle::LK_None && i != 0)
|
2014-06-12 10:50:04 +08:00
|
|
|
return make_error_code(ParseError::Error);
|
2013-11-29 23:19:43 +08:00
|
|
|
// Ensure that each language is configured at most once.
|
2013-12-10 19:28:13 +08:00
|
|
|
for (unsigned j = 0; j < i; ++j) {
|
|
|
|
if (Styles[i].Language == Styles[j].Language) {
|
2018-05-15 21:30:56 +08:00
|
|
|
LLVM_DEBUG(llvm::dbgs()
|
|
|
|
<< "Duplicate languages in the config file on positions "
|
|
|
|
<< j << " and " << i << "\n");
|
2014-06-12 10:50:04 +08:00
|
|
|
return make_error_code(ParseError::Error);
|
2013-12-10 19:28:13 +08:00
|
|
|
}
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
// Look for a suitable configuration starting from the end, so we can
|
|
|
|
// find the configuration for the specific language first, and the default
|
2013-12-10 19:28:13 +08:00
|
|
|
// configuration (which can only be at slot 0) after it.
|
2018-01-15 20:06:16 +08:00
|
|
|
FormatStyle::FormatStyleSet StyleSet;
|
|
|
|
bool LanguageFound = false;
|
2013-12-10 19:28:13 +08:00
|
|
|
for (int i = Styles.size() - 1; i >= 0; --i) {
|
2018-01-15 20:06:16 +08:00
|
|
|
if (Styles[i].Language != FormatStyle::LK_None)
|
|
|
|
StyleSet.Add(Styles[i]);
|
|
|
|
if (Styles[i].Language == Language)
|
|
|
|
LanguageFound = true;
|
|
|
|
}
|
|
|
|
if (!LanguageFound) {
|
|
|
|
if (Styles.empty() || Styles[0].Language != FormatStyle::LK_None)
|
|
|
|
return make_error_code(ParseError::Unsuitable);
|
|
|
|
FormatStyle DefaultStyle = Styles[0];
|
|
|
|
DefaultStyle.Language = Language;
|
|
|
|
StyleSet.Add(std::move(DefaultStyle));
|
|
|
|
}
|
|
|
|
*Style = *StyleSet.Get(Language);
|
|
|
|
return make_error_code(ParseError::Success);
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
std::string configurationAsText(const FormatStyle &Style) {
|
|
|
|
std::string Text;
|
|
|
|
llvm::raw_string_ostream Stream(Text);
|
|
|
|
llvm::yaml::Output Output(Stream);
|
|
|
|
// We use the same mapping method for input and output, so we need a non-const
|
|
|
|
// reference here.
|
2015-09-29 22:57:55 +08:00
|
|
|
FormatStyle NonConstStyle = expandPresets(Style);
|
2013-05-07 23:32:14 +08:00
|
|
|
Output << NonConstStyle;
|
2013-05-13 20:56:35 +08:00
|
|
|
return Stream.str();
|
2013-05-07 23:32:14 +08:00
|
|
|
}
|
|
|
|
|
2018-01-15 20:06:16 +08:00
|
|
|
llvm::Optional<FormatStyle>
|
|
|
|
FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const {
|
|
|
|
if (!Styles)
|
|
|
|
return None;
|
|
|
|
auto It = Styles->find(Language);
|
|
|
|
if (It == Styles->end())
|
|
|
|
return None;
|
|
|
|
FormatStyle Style = It->second;
|
|
|
|
Style.StyleSet = *this;
|
|
|
|
return Style;
|
|
|
|
}
|
|
|
|
|
|
|
|
void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {
|
|
|
|
assert(Style.Language != LK_None &&
|
|
|
|
"Cannot add a style for LK_None to a StyleSet");
|
|
|
|
assert(
|
|
|
|
!Style.StyleSet.Styles &&
|
|
|
|
"Cannot add a style associated with an existing StyleSet to a StyleSet");
|
|
|
|
if (!Styles)
|
|
|
|
Styles = std::make_shared<MapType>();
|
|
|
|
(*Styles)[Style.Language] = std::move(Style);
|
|
|
|
}
|
|
|
|
|
2019-03-01 17:09:54 +08:00
|
|
|
void FormatStyle::FormatStyleSet::Clear() { Styles.reset(); }
|
2018-01-15 20:06:16 +08:00
|
|
|
|
|
|
|
llvm::Optional<FormatStyle>
|
|
|
|
FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const {
|
|
|
|
return StyleSet.Get(Language);
|
|
|
|
}
|
|
|
|
|
2013-07-01 06:29:28 +08:00
|
|
|
namespace {
|
|
|
|
|
2016-09-08 06:48:53 +08:00
|
|
|
class JavaScriptRequoter : public TokenAnalyzer {
|
2016-04-25 23:09:22 +08:00
|
|
|
public:
|
2016-09-08 06:48:53 +08:00
|
|
|
JavaScriptRequoter(const Environment &Env, const FormatStyle &Style)
|
|
|
|
: TokenAnalyzer(Env, Style) {}
|
2016-04-25 23:09:22 +08:00
|
|
|
|
2017-10-30 22:01:50 +08:00
|
|
|
std::pair<tooling::Replacements, unsigned>
|
2016-04-25 23:09:22 +08:00
|
|
|
analyze(TokenAnnotator &Annotator,
|
|
|
|
SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
|
2016-09-02 22:29:48 +08:00
|
|
|
FormatTokenLexer &Tokens) override {
|
2018-04-23 17:34:26 +08:00
|
|
|
AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
|
2016-09-08 06:48:53 +08:00
|
|
|
tooling::Replacements Result;
|
|
|
|
requoteJSStringLiteral(AnnotatedLines, Result);
|
2017-10-30 22:01:50 +08:00
|
|
|
return {Result, 0};
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2016-09-08 06:48:53 +08:00
|
|
|
// Replaces double/single-quoted string literal as appropriate, re-escaping
|
|
|
|
// the contents in the process.
|
2016-03-17 21:03:41 +08:00
|
|
|
void requoteJSStringLiteral(SmallVectorImpl<AnnotatedLine *> &Lines,
|
2016-04-25 23:09:22 +08:00
|
|
|
tooling::Replacements &Result) {
|
2016-03-17 21:03:41 +08:00
|
|
|
for (AnnotatedLine *Line : Lines) {
|
|
|
|
requoteJSStringLiteral(Line->Children, Result);
|
|
|
|
if (!Line->Affected)
|
|
|
|
continue;
|
|
|
|
for (FormatToken *FormatTok = Line->First; FormatTok;
|
|
|
|
FormatTok = FormatTok->Next) {
|
|
|
|
StringRef Input = FormatTok->TokenText;
|
2016-05-12 19:20:32 +08:00
|
|
|
if (FormatTok->Finalized || !FormatTok->isStringLiteral() ||
|
2016-03-17 21:03:41 +08:00
|
|
|
// NB: testing for not starting with a double quote to avoid
|
2016-09-08 06:48:53 +08:00
|
|
|
// breaking `template strings`.
|
2016-04-28 15:52:03 +08:00
|
|
|
(Style.JavaScriptQuotes == FormatStyle::JSQS_Single &&
|
2016-03-17 21:03:41 +08:00
|
|
|
!Input.startswith("\"")) ||
|
2016-04-28 15:52:03 +08:00
|
|
|
(Style.JavaScriptQuotes == FormatStyle::JSQS_Double &&
|
2016-03-17 21:03:41 +08:00
|
|
|
!Input.startswith("\'")))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// Change start and end quote.
|
2016-04-28 15:52:03 +08:00
|
|
|
bool IsSingle = Style.JavaScriptQuotes == FormatStyle::JSQS_Single;
|
2016-03-17 21:03:41 +08:00
|
|
|
SourceLocation Start = FormatTok->Tok.getLocation();
|
|
|
|
auto Replace = [&](SourceLocation Start, unsigned Length,
|
|
|
|
StringRef ReplacementText) {
|
2016-08-01 18:16:37 +08:00
|
|
|
auto Err = Result.add(tooling::Replacement(
|
|
|
|
Env.getSourceManager(), Start, Length, ReplacementText));
|
|
|
|
// FIXME: handle error. For now, print error message and skip the
|
|
|
|
// replacement for release version.
|
2016-12-23 19:40:44 +08:00
|
|
|
if (Err) {
|
2016-08-01 18:16:37 +08:00
|
|
|
llvm::errs() << llvm::toString(std::move(Err)) << "\n";
|
2016-12-23 19:40:44 +08:00
|
|
|
assert(false);
|
|
|
|
}
|
2016-03-17 21:03:41 +08:00
|
|
|
};
|
|
|
|
Replace(Start, 1, IsSingle ? "'" : "\"");
|
|
|
|
Replace(FormatTok->Tok.getEndLoc().getLocWithOffset(-1), 1,
|
|
|
|
IsSingle ? "'" : "\"");
|
|
|
|
|
|
|
|
// Escape internal quotes.
|
|
|
|
bool Escaped = false;
|
|
|
|
for (size_t i = 1; i < Input.size() - 1; i++) {
|
|
|
|
switch (Input[i]) {
|
2016-04-25 23:09:22 +08:00
|
|
|
case '\\':
|
|
|
|
if (!Escaped && i + 1 < Input.size() &&
|
|
|
|
((IsSingle && Input[i + 1] == '"') ||
|
|
|
|
(!IsSingle && Input[i + 1] == '\''))) {
|
|
|
|
// Remove this \, it's escaping a " or ' that no longer needs
|
|
|
|
// escaping
|
|
|
|
Replace(Start.getLocWithOffset(i), 1, "");
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
Escaped = !Escaped;
|
|
|
|
break;
|
|
|
|
case '\"':
|
|
|
|
case '\'':
|
|
|
|
if (!Escaped && IsSingle == (Input[i] == '\'')) {
|
|
|
|
// Escape the quote.
|
|
|
|
Replace(Start.getLocWithOffset(i), 0, "\\");
|
|
|
|
}
|
|
|
|
Escaped = false;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
Escaped = false;
|
|
|
|
break;
|
2016-03-17 21:03:41 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2016-09-08 06:48:53 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
class Formatter : public TokenAnalyzer {
|
|
|
|
public:
|
|
|
|
Formatter(const Environment &Env, const FormatStyle &Style,
|
2017-04-21 22:35:20 +08:00
|
|
|
FormattingAttemptStatus *Status)
|
|
|
|
: TokenAnalyzer(Env, Style), Status(Status) {}
|
2016-09-08 06:48:53 +08:00
|
|
|
|
2017-10-30 22:01:50 +08:00
|
|
|
std::pair<tooling::Replacements, unsigned>
|
2016-09-08 06:48:53 +08:00
|
|
|
analyze(TokenAnnotator &Annotator,
|
|
|
|
SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
|
|
|
|
FormatTokenLexer &Tokens) override {
|
|
|
|
tooling::Replacements Result;
|
|
|
|
deriveLocalStyle(AnnotatedLines);
|
2018-04-23 17:34:26 +08:00
|
|
|
AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
|
2016-09-08 06:48:53 +08:00
|
|
|
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
|
|
|
|
Annotator.calculateFormattingInformation(*AnnotatedLines[i]);
|
|
|
|
}
|
|
|
|
Annotator.setCommentLineLevels(AnnotatedLines);
|
|
|
|
|
|
|
|
WhitespaceManager Whitespaces(
|
|
|
|
Env.getSourceManager(), Style,
|
|
|
|
inputUsesCRLF(Env.getSourceManager().getBufferData(Env.getFileID())));
|
|
|
|
ContinuationIndenter Indenter(Style, Tokens.getKeywords(),
|
|
|
|
Env.getSourceManager(), Whitespaces, Encoding,
|
|
|
|
BinPackInconclusiveFunctions);
|
2017-10-30 22:01:50 +08:00
|
|
|
unsigned Penalty =
|
|
|
|
UnwrappedLineFormatter(&Indenter, &Whitespaces, Style,
|
|
|
|
Tokens.getKeywords(), Env.getSourceManager(),
|
|
|
|
Status)
|
|
|
|
.format(AnnotatedLines, /*DryRun=*/false,
|
|
|
|
/*AdditionalIndent=*/0,
|
|
|
|
/*FixBadIndentation=*/false,
|
|
|
|
/*FirstStartColumn=*/Env.getFirstStartColumn(),
|
|
|
|
/*NextStartColumn=*/Env.getNextStartColumn(),
|
|
|
|
/*LastStartColumn=*/Env.getLastStartColumn());
|
2016-09-08 06:48:53 +08:00
|
|
|
for (const auto &R : Whitespaces.generateReplacements())
|
|
|
|
if (Result.add(R))
|
2017-10-30 22:30:14 +08:00
|
|
|
return std::make_pair(Result, 0);
|
|
|
|
return std::make_pair(Result, Penalty);
|
2016-09-08 06:48:53 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
2013-09-11 20:25:57 +08:00
|
|
|
static bool inputUsesCRLF(StringRef Text) {
|
|
|
|
return Text.count('\r') * 2 > Text.count('\n');
|
|
|
|
}
|
|
|
|
|
2015-07-19 00:35:30 +08:00
|
|
|
bool
|
|
|
|
hasCpp03IncompatibleFormat(const SmallVectorImpl<AnnotatedLine *> &Lines) {
|
2016-04-25 23:09:22 +08:00
|
|
|
for (const AnnotatedLine *Line : Lines) {
|
2015-07-19 00:35:30 +08:00
|
|
|
if (hasCpp03IncompatibleFormat(Line->Children))
|
|
|
|
return true;
|
|
|
|
for (FormatToken *Tok = Line->First->Next; Tok; Tok = Tok->Next) {
|
|
|
|
if (Tok->WhitespaceRange.getBegin() == Tok->WhitespaceRange.getEnd()) {
|
|
|
|
if (Tok->is(tok::coloncolon) && Tok->Previous->is(TT_TemplateOpener))
|
|
|
|
return true;
|
|
|
|
if (Tok->is(TT_TemplateCloser) &&
|
|
|
|
Tok->Previous->is(TT_TemplateCloser))
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
int countVariableAlignments(const SmallVectorImpl<AnnotatedLine *> &Lines) {
|
|
|
|
int AlignmentDiff = 0;
|
2016-04-25 23:09:22 +08:00
|
|
|
for (const AnnotatedLine *Line : Lines) {
|
2015-07-19 00:35:30 +08:00
|
|
|
AlignmentDiff += countVariableAlignments(Line->Children);
|
|
|
|
for (FormatToken *Tok = Line->First; Tok && Tok->Next; Tok = Tok->Next) {
|
|
|
|
if (!Tok->is(TT_PointerOrReference))
|
|
|
|
continue;
|
|
|
|
bool SpaceBefore =
|
|
|
|
Tok->WhitespaceRange.getBegin() != Tok->WhitespaceRange.getEnd();
|
|
|
|
bool SpaceAfter = Tok->Next->WhitespaceRange.getBegin() !=
|
|
|
|
Tok->Next->WhitespaceRange.getEnd();
|
|
|
|
if (SpaceBefore && !SpaceAfter)
|
|
|
|
++AlignmentDiff;
|
|
|
|
if (!SpaceBefore && SpaceAfter)
|
|
|
|
--AlignmentDiff;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return AlignmentDiff;
|
|
|
|
}
|
|
|
|
|
2013-10-12 05:25:45 +08:00
|
|
|
void
|
|
|
|
deriveLocalStyle(const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
|
2013-07-10 22:02:49 +08:00
|
|
|
bool HasBinPackedFunction = false;
|
|
|
|
bool HasOnePerLineFunction = false;
|
2013-03-13 22:41:29 +08:00
|
|
|
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
|
2013-09-05 17:29:45 +08:00
|
|
|
if (!AnnotatedLines[i]->First->Next)
|
2013-03-13 22:41:29 +08:00
|
|
|
continue;
|
2013-09-05 17:29:45 +08:00
|
|
|
FormatToken *Tok = AnnotatedLines[i]->First->Next;
|
2013-05-29 22:47:47 +08:00
|
|
|
while (Tok->Next) {
|
2013-07-10 22:02:49 +08:00
|
|
|
if (Tok->PackingKind == PPK_BinPacked)
|
|
|
|
HasBinPackedFunction = true;
|
|
|
|
if (Tok->PackingKind == PPK_OnePerLine)
|
|
|
|
HasOnePerLineFunction = true;
|
|
|
|
|
2013-05-29 22:47:47 +08:00
|
|
|
Tok = Tok->Next;
|
2013-03-13 22:41:29 +08:00
|
|
|
}
|
|
|
|
}
|
2016-04-28 15:52:03 +08:00
|
|
|
if (Style.DerivePointerAlignment)
|
|
|
|
Style.PointerAlignment = countVariableAlignments(AnnotatedLines) <= 0
|
|
|
|
? FormatStyle::PAS_Left
|
|
|
|
: FormatStyle::PAS_Right;
|
|
|
|
if (Style.Standard == FormatStyle::LS_Auto)
|
|
|
|
Style.Standard = hasCpp03IncompatibleFormat(AnnotatedLines)
|
|
|
|
? FormatStyle::LS_Cpp11
|
|
|
|
: FormatStyle::LS_Cpp03;
|
2013-07-10 22:02:49 +08:00
|
|
|
BinPackInconclusiveFunctions =
|
|
|
|
HasBinPackedFunction || !HasOnePerLineFunction;
|
2013-03-13 22:41:29 +08:00
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
bool BinPackInconclusiveFunctions;
|
2017-04-21 22:35:20 +08:00
|
|
|
FormattingAttemptStatus *Status;
|
2016-04-25 23:09:22 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
// This class clean up the erroneous/redundant code around the given ranges in
|
|
|
|
// file.
|
|
|
|
class Cleaner : public TokenAnalyzer {
|
|
|
|
public:
|
2016-04-28 15:52:03 +08:00
|
|
|
Cleaner(const Environment &Env, const FormatStyle &Style)
|
|
|
|
: TokenAnalyzer(Env, Style),
|
2016-04-25 23:09:22 +08:00
|
|
|
DeletedTokens(FormatTokenLess(Env.getSourceManager())) {}
|
|
|
|
|
|
|
|
// FIXME: eliminate unused parameters.
|
2017-10-30 22:01:50 +08:00
|
|
|
std::pair<tooling::Replacements, unsigned>
|
2016-04-25 23:09:22 +08:00
|
|
|
analyze(TokenAnnotator &Annotator,
|
|
|
|
SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
|
2016-09-02 22:29:48 +08:00
|
|
|
FormatTokenLexer &Tokens) override {
|
2016-04-25 23:09:22 +08:00
|
|
|
// FIXME: in the current implementation the granularity of affected range
|
|
|
|
// is an annotated line. However, this is not sufficient. Furthermore,
|
|
|
|
// redundant code introduced by replacements does not necessarily
|
|
|
|
// intercept with ranges of replacements that result in the redundancy.
|
|
|
|
// To determine if some redundant code is actually introduced by
|
|
|
|
// replacements(e.g. deletions), we need to come up with a more
|
|
|
|
// sophisticated way of computing affected ranges.
|
2018-04-23 17:34:26 +08:00
|
|
|
AffectedRangeMgr.computeAffectedLines(AnnotatedLines);
|
2016-04-25 23:09:22 +08:00
|
|
|
|
|
|
|
checkEmptyNamespace(AnnotatedLines);
|
|
|
|
|
2016-05-18 16:02:56 +08:00
|
|
|
for (auto &Line : AnnotatedLines) {
|
|
|
|
if (Line->Affected) {
|
|
|
|
cleanupRight(Line->First, tok::comma, tok::comma);
|
|
|
|
cleanupRight(Line->First, TT_CtorInitializerColon, tok::comma);
|
2016-09-13 23:02:43 +08:00
|
|
|
cleanupRight(Line->First, tok::l_paren, tok::comma);
|
|
|
|
cleanupLeft(Line->First, tok::comma, tok::r_paren);
|
2016-05-18 16:02:56 +08:00
|
|
|
cleanupLeft(Line->First, TT_CtorInitializerComma, tok::l_brace);
|
|
|
|
cleanupLeft(Line->First, TT_CtorInitializerColon, tok::l_brace);
|
2016-10-20 22:58:45 +08:00
|
|
|
cleanupLeft(Line->First, TT_CtorInitializerColon, tok::equal);
|
2016-05-18 16:02:56 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-30 22:01:50 +08:00
|
|
|
return {generateFixes(), 0};
|
2013-10-12 05:25:45 +08:00
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
private:
|
|
|
|
bool containsOnlyComments(const AnnotatedLine &Line) {
|
|
|
|
for (FormatToken *Tok = Line.First; Tok != nullptr; Tok = Tok->Next) {
|
|
|
|
if (Tok->isNot(tok::comment))
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
2012-12-04 02:12:45 +08:00
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
// Iterate through all lines and remove any empty (nested) namespaces.
|
|
|
|
void checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines) {
|
2016-10-05 23:49:01 +08:00
|
|
|
std::set<unsigned> DeletedLines;
|
2016-04-25 23:09:22 +08:00
|
|
|
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
|
|
|
|
auto &Line = *AnnotatedLines[i];
|
2018-09-05 15:44:02 +08:00
|
|
|
if (Line.startsWithNamespace()) {
|
2016-10-05 23:49:01 +08:00
|
|
|
checkEmptyNamespace(AnnotatedLines, i, i, DeletedLines);
|
2016-04-25 23:09:22 +08:00
|
|
|
}
|
|
|
|
}
|
2013-06-05 22:09:10 +08:00
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
for (auto Line : DeletedLines) {
|
|
|
|
FormatToken *Tok = AnnotatedLines[Line]->First;
|
|
|
|
while (Tok) {
|
|
|
|
deleteToken(Tok);
|
|
|
|
Tok = Tok->Next;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// The function checks if the namespace, which starts from \p CurrentLine, and
|
|
|
|
// its nested namespaces are empty and delete them if they are empty. It also
|
|
|
|
// sets \p NewLine to the last line checked.
|
|
|
|
// Returns true if the current namespace is empty.
|
|
|
|
bool checkEmptyNamespace(SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
|
2016-10-05 23:49:01 +08:00
|
|
|
unsigned CurrentLine, unsigned &NewLine,
|
|
|
|
std::set<unsigned> &DeletedLines) {
|
2016-04-25 23:09:22 +08:00
|
|
|
unsigned InitLine = CurrentLine, End = AnnotatedLines.size();
|
2016-04-28 15:52:03 +08:00
|
|
|
if (Style.BraceWrapping.AfterNamespace) {
|
2016-04-25 23:09:22 +08:00
|
|
|
// If the left brace is in a new line, we should consume it first so that
|
|
|
|
// it does not make the namespace non-empty.
|
|
|
|
// FIXME: error handling if there is no left brace.
|
|
|
|
if (!AnnotatedLines[++CurrentLine]->startsWith(tok::l_brace)) {
|
|
|
|
NewLine = CurrentLine;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
} else if (!AnnotatedLines[CurrentLine]->endsWith(tok::l_brace)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
while (++CurrentLine < End) {
|
|
|
|
if (AnnotatedLines[CurrentLine]->startsWith(tok::r_brace))
|
|
|
|
break;
|
|
|
|
|
2018-09-05 15:44:02 +08:00
|
|
|
if (AnnotatedLines[CurrentLine]->startsWithNamespace()) {
|
2016-10-05 23:49:01 +08:00
|
|
|
if (!checkEmptyNamespace(AnnotatedLines, CurrentLine, NewLine,
|
|
|
|
DeletedLines))
|
2016-04-25 23:09:22 +08:00
|
|
|
return false;
|
|
|
|
CurrentLine = NewLine;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (containsOnlyComments(*AnnotatedLines[CurrentLine]))
|
|
|
|
continue;
|
|
|
|
|
|
|
|
// If there is anything other than comments or nested namespaces in the
|
|
|
|
// current namespace, the namespace cannot be empty.
|
|
|
|
NewLine = CurrentLine;
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
NewLine = CurrentLine;
|
|
|
|
if (CurrentLine >= End)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Check if the empty namespace is actually affected by changed ranges.
|
|
|
|
if (!AffectedRangeMgr.affectsCharSourceRange(CharSourceRange::getCharRange(
|
|
|
|
AnnotatedLines[InitLine]->First->Tok.getLocation(),
|
|
|
|
AnnotatedLines[CurrentLine]->Last->Tok.getEndLoc())))
|
|
|
|
return false;
|
|
|
|
|
|
|
|
for (unsigned i = InitLine; i <= CurrentLine; ++i) {
|
|
|
|
DeletedLines.insert(i);
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2016-05-18 16:02:56 +08:00
|
|
|
// Checks pairs {start, start->next},..., {end->previous, end} and deletes one
|
|
|
|
// of the token in the pair if the left token has \p LK token kind and the
|
|
|
|
// right token has \p RK token kind. If \p DeleteLeft is true, the left token
|
|
|
|
// is deleted on match; otherwise, the right token is deleted.
|
|
|
|
template <typename LeftKind, typename RightKind>
|
|
|
|
void cleanupPair(FormatToken *Start, LeftKind LK, RightKind RK,
|
|
|
|
bool DeleteLeft) {
|
|
|
|
auto NextNotDeleted = [this](const FormatToken &Tok) -> FormatToken * {
|
|
|
|
for (auto *Res = Tok.Next; Res; Res = Res->Next)
|
|
|
|
if (!Res->is(tok::comment) &&
|
|
|
|
DeletedTokens.find(Res) == DeletedTokens.end())
|
|
|
|
return Res;
|
|
|
|
return nullptr;
|
|
|
|
};
|
|
|
|
for (auto *Left = Start; Left;) {
|
|
|
|
auto *Right = NextNotDeleted(*Left);
|
|
|
|
if (!Right)
|
|
|
|
break;
|
|
|
|
if (Left->is(LK) && Right->is(RK)) {
|
|
|
|
deleteToken(DeleteLeft ? Left : Right);
|
2016-09-10 01:50:49 +08:00
|
|
|
for (auto *Tok = Left->Next; Tok && Tok != Right; Tok = Tok->Next)
|
|
|
|
deleteToken(Tok);
|
2016-05-18 16:02:56 +08:00
|
|
|
// If the right token is deleted, we should keep the left token
|
|
|
|
// unchanged and pair it with the new right token.
|
|
|
|
if (!DeleteLeft)
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
Left = Right;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
template <typename LeftKind, typename RightKind>
|
|
|
|
void cleanupLeft(FormatToken *Start, LeftKind LK, RightKind RK) {
|
|
|
|
cleanupPair(Start, LK, RK, /*DeleteLeft=*/true);
|
|
|
|
}
|
|
|
|
|
|
|
|
template <typename LeftKind, typename RightKind>
|
|
|
|
void cleanupRight(FormatToken *Start, LeftKind LK, RightKind RK) {
|
|
|
|
cleanupPair(Start, LK, RK, /*DeleteLeft=*/false);
|
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
// Delete the given token.
|
|
|
|
inline void deleteToken(FormatToken *Tok) {
|
|
|
|
if (Tok)
|
|
|
|
DeletedTokens.insert(Tok);
|
|
|
|
}
|
|
|
|
|
|
|
|
tooling::Replacements generateFixes() {
|
|
|
|
tooling::Replacements Fixes;
|
|
|
|
std::vector<FormatToken *> Tokens;
|
|
|
|
std::copy(DeletedTokens.begin(), DeletedTokens.end(),
|
|
|
|
std::back_inserter(Tokens));
|
|
|
|
|
|
|
|
// Merge multiple continuous token deletions into one big deletion so that
|
|
|
|
// the number of replacements can be reduced. This makes computing affected
|
|
|
|
// ranges more efficient when we run reformat on the changed code.
|
|
|
|
unsigned Idx = 0;
|
|
|
|
while (Idx < Tokens.size()) {
|
|
|
|
unsigned St = Idx, End = Idx;
|
|
|
|
while ((End + 1) < Tokens.size() &&
|
|
|
|
Tokens[End]->Next == Tokens[End + 1]) {
|
|
|
|
End++;
|
|
|
|
}
|
|
|
|
auto SR = CharSourceRange::getCharRange(Tokens[St]->Tok.getLocation(),
|
|
|
|
Tokens[End]->Tok.getEndLoc());
|
2016-08-01 18:16:37 +08:00
|
|
|
auto Err =
|
|
|
|
Fixes.add(tooling::Replacement(Env.getSourceManager(), SR, ""));
|
|
|
|
// FIXME: better error handling. for now just print error message and skip
|
|
|
|
// for the release version.
|
2016-12-23 19:40:44 +08:00
|
|
|
if (Err) {
|
2016-08-01 18:16:37 +08:00
|
|
|
llvm::errs() << llvm::toString(std::move(Err)) << "\n";
|
2016-12-23 19:40:44 +08:00
|
|
|
assert(false && "Fixes must not conflict!");
|
|
|
|
}
|
2016-04-25 23:09:22 +08:00
|
|
|
Idx = End + 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Fixes;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Class for less-than inequality comparason for the set `RedundantTokens`.
|
|
|
|
// We store tokens in the order they appear in the translation unit so that
|
|
|
|
// we do not need to sort them in `generateFixes()`.
|
|
|
|
struct FormatTokenLess {
|
2016-04-28 15:52:03 +08:00
|
|
|
FormatTokenLess(const SourceManager &SM) : SM(SM) {}
|
2016-04-25 23:09:22 +08:00
|
|
|
|
2016-05-18 16:14:49 +08:00
|
|
|
bool operator()(const FormatToken *LHS, const FormatToken *RHS) const {
|
2016-04-25 23:09:22 +08:00
|
|
|
return SM.isBeforeInTranslationUnit(LHS->Tok.getLocation(),
|
|
|
|
RHS->Tok.getLocation());
|
|
|
|
}
|
2016-04-28 15:52:03 +08:00
|
|
|
const SourceManager &SM;
|
2016-04-25 23:09:22 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
// Tokens to be deleted.
|
|
|
|
std::set<FormatToken *, FormatTokenLess> DeletedTokens;
|
2012-12-04 02:12:45 +08:00
|
|
|
};
|
|
|
|
|
2018-01-18 01:33:08 +08:00
|
|
|
class ObjCHeaderStyleGuesser : public TokenAnalyzer {
|
|
|
|
public:
|
|
|
|
ObjCHeaderStyleGuesser(const Environment &Env, const FormatStyle &Style)
|
|
|
|
: TokenAnalyzer(Env, Style), IsObjC(false) {}
|
|
|
|
|
|
|
|
std::pair<tooling::Replacements, unsigned>
|
|
|
|
analyze(TokenAnnotator &Annotator,
|
|
|
|
SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
|
|
|
|
FormatTokenLexer &Tokens) override {
|
|
|
|
assert(Style.Language == FormatStyle::LK_Cpp);
|
2018-11-06 00:59:33 +08:00
|
|
|
IsObjC = guessIsObjC(Env.getSourceManager(), AnnotatedLines,
|
|
|
|
Tokens.getKeywords());
|
2018-01-18 01:33:08 +08:00
|
|
|
tooling::Replacements Result;
|
|
|
|
return {Result, 0};
|
|
|
|
}
|
|
|
|
|
|
|
|
bool isObjC() { return IsObjC; }
|
|
|
|
|
|
|
|
private:
|
2018-11-06 00:59:33 +08:00
|
|
|
static bool
|
|
|
|
guessIsObjC(const SourceManager &SourceManager,
|
|
|
|
const SmallVectorImpl<AnnotatedLine *> &AnnotatedLines,
|
|
|
|
const AdditionalKeywords &Keywords) {
|
2018-01-18 04:01:02 +08:00
|
|
|
// Keep this array sorted, since we are binary searching over it.
|
|
|
|
static constexpr llvm::StringLiteral FoundationIdentifiers[] = {
|
2018-01-18 01:33:08 +08:00
|
|
|
"CGFloat",
|
2018-03-22 11:25:22 +08:00
|
|
|
"CGPoint",
|
|
|
|
"CGPointMake",
|
|
|
|
"CGPointZero",
|
|
|
|
"CGRect",
|
|
|
|
"CGRectEdge",
|
|
|
|
"CGRectInfinite",
|
|
|
|
"CGRectMake",
|
|
|
|
"CGRectNull",
|
|
|
|
"CGRectZero",
|
|
|
|
"CGSize",
|
|
|
|
"CGSizeMake",
|
|
|
|
"CGVector",
|
|
|
|
"CGVectorMake",
|
2018-01-18 01:33:08 +08:00
|
|
|
"NSAffineTransform",
|
|
|
|
"NSArray",
|
|
|
|
"NSAttributedString",
|
2018-04-12 23:11:53 +08:00
|
|
|
"NSBlockOperation",
|
2018-02-15 16:47:56 +08:00
|
|
|
"NSBundle",
|
2018-01-18 01:33:08 +08:00
|
|
|
"NSCache",
|
2018-02-15 16:47:56 +08:00
|
|
|
"NSCalendar",
|
2018-01-18 01:33:08 +08:00
|
|
|
"NSCharacterSet",
|
|
|
|
"NSCountedSet",
|
|
|
|
"NSData",
|
|
|
|
"NSDataDetector",
|
|
|
|
"NSDecimal",
|
|
|
|
"NSDecimalNumber",
|
|
|
|
"NSDictionary",
|
|
|
|
"NSEdgeInsets",
|
|
|
|
"NSHashTable",
|
|
|
|
"NSIndexPath",
|
|
|
|
"NSIndexSet",
|
|
|
|
"NSInteger",
|
2018-04-12 23:11:53 +08:00
|
|
|
"NSInvocationOperation",
|
2018-01-18 01:33:08 +08:00
|
|
|
"NSLocale",
|
|
|
|
"NSMapTable",
|
|
|
|
"NSMutableArray",
|
|
|
|
"NSMutableAttributedString",
|
|
|
|
"NSMutableCharacterSet",
|
|
|
|
"NSMutableData",
|
|
|
|
"NSMutableDictionary",
|
|
|
|
"NSMutableIndexSet",
|
|
|
|
"NSMutableOrderedSet",
|
|
|
|
"NSMutableSet",
|
|
|
|
"NSMutableString",
|
|
|
|
"NSNumber",
|
|
|
|
"NSNumberFormatter",
|
2018-02-15 16:47:56 +08:00
|
|
|
"NSObject",
|
2018-04-12 23:11:53 +08:00
|
|
|
"NSOperation",
|
|
|
|
"NSOperationQueue",
|
|
|
|
"NSOperationQueuePriority",
|
2018-01-18 01:33:08 +08:00
|
|
|
"NSOrderedSet",
|
|
|
|
"NSPoint",
|
|
|
|
"NSPointerArray",
|
2018-04-12 23:11:53 +08:00
|
|
|
"NSQualityOfService",
|
2018-01-18 01:33:08 +08:00
|
|
|
"NSRange",
|
|
|
|
"NSRect",
|
|
|
|
"NSRegularExpression",
|
|
|
|
"NSSet",
|
|
|
|
"NSSize",
|
|
|
|
"NSString",
|
2018-02-15 16:47:56 +08:00
|
|
|
"NSTimeZone",
|
2018-01-18 01:33:08 +08:00
|
|
|
"NSUInteger",
|
|
|
|
"NSURL",
|
|
|
|
"NSURLComponents",
|
|
|
|
"NSURLQueryItem",
|
|
|
|
"NSUUID",
|
2018-02-15 16:47:56 +08:00
|
|
|
"NSValue",
|
2018-03-22 11:25:22 +08:00
|
|
|
"UIImage",
|
|
|
|
"UIView",
|
2018-01-18 01:33:08 +08:00
|
|
|
};
|
|
|
|
|
2018-03-27 23:01:21 +08:00
|
|
|
for (auto Line : AnnotatedLines) {
|
|
|
|
for (const FormatToken *FormatTok = Line->First; FormatTok;
|
2018-01-18 01:33:08 +08:00
|
|
|
FormatTok = FormatTok->Next) {
|
2018-02-15 16:47:56 +08:00
|
|
|
if ((FormatTok->Previous && FormatTok->Previous->is(tok::at) &&
|
2018-04-12 23:11:53 +08:00
|
|
|
(FormatTok->Tok.getObjCKeywordID() != tok::objc_not_keyword ||
|
2018-01-18 01:33:08 +08:00
|
|
|
FormatTok->isOneOf(tok::numeric_constant, tok::l_square,
|
|
|
|
tok::l_brace))) ||
|
|
|
|
(FormatTok->Tok.isAnyIdentifier() &&
|
2018-01-18 04:01:02 +08:00
|
|
|
std::binary_search(std::begin(FoundationIdentifiers),
|
|
|
|
std::end(FoundationIdentifiers),
|
|
|
|
FormatTok->TokenText)) ||
|
2018-01-18 01:33:08 +08:00
|
|
|
FormatTok->is(TT_ObjCStringLiteral) ||
|
|
|
|
FormatTok->isOneOf(Keywords.kw_NS_ENUM, Keywords.kw_NS_OPTIONS,
|
|
|
|
TT_ObjCBlockLBrace, TT_ObjCBlockLParen,
|
|
|
|
TT_ObjCDecl, TT_ObjCForIn, TT_ObjCMethodExpr,
|
|
|
|
TT_ObjCMethodSpecifier, TT_ObjCProperty)) {
|
2018-11-06 00:59:33 +08:00
|
|
|
LLVM_DEBUG(llvm::dbgs()
|
|
|
|
<< "Detected ObjC at location "
|
|
|
|
<< FormatTok->Tok.getLocation().printToString(
|
|
|
|
SourceManager)
|
|
|
|
<< " token: " << FormatTok->TokenText << " token type: "
|
|
|
|
<< getTokenTypeName(FormatTok->Type) << "\n");
|
2018-01-18 01:33:08 +08:00
|
|
|
return true;
|
|
|
|
}
|
2018-11-06 00:59:33 +08:00
|
|
|
if (guessIsObjC(SourceManager, Line->Children, Keywords))
|
2018-03-23 01:37:19 +08:00
|
|
|
return true;
|
|
|
|
}
|
2018-01-18 01:33:08 +08:00
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool IsObjC;
|
|
|
|
};
|
|
|
|
|
2015-09-23 16:30:47 +08:00
|
|
|
struct IncludeDirective {
|
|
|
|
StringRef Filename;
|
|
|
|
StringRef Text;
|
|
|
|
unsigned Offset;
|
2015-12-16 18:10:16 +08:00
|
|
|
int Category;
|
2015-09-23 16:30:47 +08:00
|
|
|
};
|
|
|
|
|
2018-10-06 01:19:26 +08:00
|
|
|
struct JavaImportDirective {
|
|
|
|
StringRef Identifier;
|
|
|
|
StringRef Text;
|
|
|
|
unsigned Offset;
|
|
|
|
std::vector<StringRef> AssociatedCommentLines;
|
|
|
|
bool IsStatic;
|
|
|
|
};
|
|
|
|
|
2013-07-01 06:29:28 +08:00
|
|
|
} // end anonymous namespace
|
|
|
|
|
2015-09-23 16:30:47 +08:00
|
|
|
// Determines whether 'Ranges' intersects with ('Start', 'End').
|
|
|
|
static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
|
|
|
|
unsigned End) {
|
|
|
|
for (auto Range : Ranges) {
|
|
|
|
if (Range.getOffset() < End &&
|
|
|
|
Range.getOffset() + Range.getLength() > Start)
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2016-08-10 17:32:23 +08:00
|
|
|
// Returns a pair (Index, OffsetToEOL) describing the position of the cursor
|
|
|
|
// before sorting/deduplicating. Index is the index of the include under the
|
|
|
|
// cursor in the original set of includes. If this include has duplicates, it is
|
|
|
|
// the index of the first of the duplicates as the others are going to be
|
|
|
|
// removed. OffsetToEOL describes the cursor's position relative to the end of
|
|
|
|
// its current line.
|
|
|
|
// If `Cursor` is not on any #include, `Index` will be UINT_MAX.
|
|
|
|
static std::pair<unsigned, unsigned>
|
|
|
|
FindCursorIndex(const SmallVectorImpl<IncludeDirective> &Includes,
|
|
|
|
const SmallVectorImpl<unsigned> &Indices, unsigned Cursor) {
|
|
|
|
unsigned CursorIndex = UINT_MAX;
|
|
|
|
unsigned OffsetToEOL = 0;
|
|
|
|
for (int i = 0, e = Includes.size(); i != e; ++i) {
|
|
|
|
unsigned Start = Includes[Indices[i]].Offset;
|
|
|
|
unsigned End = Start + Includes[Indices[i]].Text.size();
|
|
|
|
if (!(Cursor >= Start && Cursor < End))
|
|
|
|
continue;
|
|
|
|
CursorIndex = Indices[i];
|
|
|
|
OffsetToEOL = End - Cursor;
|
|
|
|
// Put the cursor on the only remaining #include among the duplicate
|
|
|
|
// #includes.
|
|
|
|
while (--i >= 0 && Includes[CursorIndex].Text == Includes[Indices[i]].Text)
|
|
|
|
CursorIndex = i;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
return std::make_pair(CursorIndex, OffsetToEOL);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sorts and deduplicate a block of includes given by 'Includes' alphabetically
|
|
|
|
// adding the necessary replacement to 'Replaces'. 'Includes' must be in strict
|
|
|
|
// source order.
|
|
|
|
// #include directives with the same text will be deduplicated, and only the
|
|
|
|
// first #include in the duplicate #includes remains. If the `Cursor` is
|
|
|
|
// provided and put on a deleted #include, it will be moved to the remaining
|
|
|
|
// #include in the duplicate #includes.
|
2016-05-20 19:24:24 +08:00
|
|
|
static void sortCppIncludes(const FormatStyle &Style,
|
2016-08-10 17:32:23 +08:00
|
|
|
const SmallVectorImpl<IncludeDirective> &Includes,
|
|
|
|
ArrayRef<tooling::Range> Ranges, StringRef FileName,
|
|
|
|
tooling::Replacements &Replaces, unsigned *Cursor) {
|
|
|
|
unsigned IncludesBeginOffset = Includes.front().Offset;
|
2016-08-31 05:33:41 +08:00
|
|
|
unsigned IncludesEndOffset =
|
|
|
|
Includes.back().Offset + Includes.back().Text.size();
|
|
|
|
unsigned IncludesBlockSize = IncludesEndOffset - IncludesBeginOffset;
|
|
|
|
if (!affectsRange(Ranges, IncludesBeginOffset, IncludesEndOffset))
|
2015-09-23 16:30:47 +08:00
|
|
|
return;
|
|
|
|
SmallVector<unsigned, 16> Indices;
|
|
|
|
for (unsigned i = 0, e = Includes.size(); i != e; ++i)
|
|
|
|
Indices.push_back(i);
|
2016-03-04 01:34:14 +08:00
|
|
|
std::stable_sort(
|
|
|
|
Indices.begin(), Indices.end(), [&](unsigned LHSI, unsigned RHSI) {
|
|
|
|
return std::tie(Includes[LHSI].Category, Includes[LHSI].Filename) <
|
|
|
|
std::tie(Includes[RHSI].Category, Includes[RHSI].Filename);
|
|
|
|
});
|
2016-08-10 17:32:23 +08:00
|
|
|
// The index of the include on which the cursor will be put after
|
|
|
|
// sorting/deduplicating.
|
|
|
|
unsigned CursorIndex;
|
|
|
|
// The offset from cursor to the end of line.
|
|
|
|
unsigned CursorToEOLOffset;
|
|
|
|
if (Cursor)
|
|
|
|
std::tie(CursorIndex, CursorToEOLOffset) =
|
|
|
|
FindCursorIndex(Includes, Indices, *Cursor);
|
|
|
|
|
|
|
|
// Deduplicate #includes.
|
|
|
|
Indices.erase(std::unique(Indices.begin(), Indices.end(),
|
|
|
|
[&](unsigned LHSI, unsigned RHSI) {
|
|
|
|
return Includes[LHSI].Text == Includes[RHSI].Text;
|
|
|
|
}),
|
|
|
|
Indices.end());
|
2015-09-23 16:30:47 +08:00
|
|
|
|
2017-11-27 21:23:45 +08:00
|
|
|
int CurrentCategory = Includes.front().Category;
|
|
|
|
|
2015-09-23 16:30:47 +08:00
|
|
|
// If the #includes are out of order, we generate a single replacement fixing
|
|
|
|
// the entire block. Otherwise, no replacement is generated.
|
2016-08-10 17:32:23 +08:00
|
|
|
if (Indices.size() == Includes.size() &&
|
2017-11-27 21:23:45 +08:00
|
|
|
std::is_sorted(Indices.begin(), Indices.end()) &&
|
2018-05-15 03:51:33 +08:00
|
|
|
Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve)
|
2015-09-23 16:30:47 +08:00
|
|
|
return;
|
|
|
|
|
2015-11-23 16:36:35 +08:00
|
|
|
std::string result;
|
|
|
|
for (unsigned Index : Indices) {
|
2017-11-27 21:23:45 +08:00
|
|
|
if (!result.empty()) {
|
2015-11-23 16:36:35 +08:00
|
|
|
result += "\n";
|
2018-05-15 03:51:33 +08:00
|
|
|
if (Style.IncludeStyle.IncludeBlocks ==
|
|
|
|
tooling::IncludeStyle::IBS_Regroup &&
|
2017-11-27 21:23:45 +08:00
|
|
|
CurrentCategory != Includes[Index].Category)
|
|
|
|
result += "\n";
|
|
|
|
}
|
2015-11-23 16:36:35 +08:00
|
|
|
result += Includes[Index].Text;
|
2016-08-10 17:32:23 +08:00
|
|
|
if (Cursor && CursorIndex == Index)
|
|
|
|
*Cursor = IncludesBeginOffset + result.size() - CursorToEOLOffset;
|
2017-11-27 21:23:45 +08:00
|
|
|
CurrentCategory = Includes[Index].Category;
|
2015-09-23 16:30:47 +08:00
|
|
|
}
|
|
|
|
|
2016-08-01 18:16:37 +08:00
|
|
|
auto Err = Replaces.add(tooling::Replacement(
|
2016-08-10 17:32:23 +08:00
|
|
|
FileName, Includes.front().Offset, IncludesBlockSize, result));
|
2016-08-01 18:16:37 +08:00
|
|
|
// FIXME: better error handling. For now, just skip the replacement for the
|
|
|
|
// release version.
|
2016-12-23 19:40:44 +08:00
|
|
|
if (Err) {
|
2016-08-01 18:16:37 +08:00
|
|
|
llvm::errs() << llvm::toString(std::move(Err)) << "\n";
|
2016-12-23 19:40:44 +08:00
|
|
|
assert(false);
|
|
|
|
}
|
2015-09-23 16:30:47 +08:00
|
|
|
}
|
|
|
|
|
2016-05-31 21:34:20 +08:00
|
|
|
namespace {
|
|
|
|
|
2018-10-06 01:19:26 +08:00
|
|
|
const char CppIncludeRegexPattern[] =
|
2016-05-31 21:34:20 +08:00
|
|
|
R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
|
|
|
|
|
|
|
|
} // anonymous namespace
|
|
|
|
|
2016-05-20 19:24:24 +08:00
|
|
|
tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
|
|
|
|
ArrayRef<tooling::Range> Ranges,
|
|
|
|
StringRef FileName,
|
|
|
|
tooling::Replacements &Replaces,
|
|
|
|
unsigned *Cursor) {
|
2015-09-23 16:30:47 +08:00
|
|
|
unsigned Prev = 0;
|
|
|
|
unsigned SearchFrom = 0;
|
2018-10-06 01:19:26 +08:00
|
|
|
llvm::Regex IncludeRegex(CppIncludeRegexPattern);
|
2015-09-23 16:30:47 +08:00
|
|
|
SmallVector<StringRef, 4> Matches;
|
|
|
|
SmallVector<IncludeDirective, 16> IncludesInBlock;
|
2015-09-29 15:53:08 +08:00
|
|
|
|
|
|
|
// In compiled files, consider the first #include to be the main #include of
|
|
|
|
// the file if it is not a system #include. This ensures that the header
|
|
|
|
// doesn't have hidden dependencies
|
|
|
|
// (http://llvm.org/docs/CodingStandards.html#include-style).
|
|
|
|
//
|
|
|
|
// FIXME: Do some sanity checking, e.g. edit distance of the base name, to fix
|
|
|
|
// cases where the first #include is unlikely to be the main header.
|
2018-05-15 04:17:53 +08:00
|
|
|
tooling::IncludeCategoryManager Categories(Style.IncludeStyle, FileName);
|
2015-12-21 21:40:49 +08:00
|
|
|
bool FirstIncludeBlock = true;
|
2015-12-22 01:28:24 +08:00
|
|
|
bool MainIncludeFound = false;
|
2015-11-21 17:17:08 +08:00
|
|
|
bool FormattingOff = false;
|
|
|
|
|
2015-09-23 16:30:47 +08:00
|
|
|
for (;;) {
|
|
|
|
auto Pos = Code.find('\n', SearchFrom);
|
|
|
|
StringRef Line =
|
|
|
|
Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
|
2015-11-21 17:17:08 +08:00
|
|
|
|
|
|
|
StringRef Trimmed = Line.trim();
|
2019-03-02 17:08:51 +08:00
|
|
|
if (Trimmed == "// clang-format off" || Trimmed == "/* clang-format off */")
|
2015-11-21 17:17:08 +08:00
|
|
|
FormattingOff = true;
|
2019-03-02 17:08:51 +08:00
|
|
|
else if (Trimmed == "// clang-format on" ||
|
|
|
|
Trimmed == "/* clang-format on */")
|
2015-11-21 17:17:08 +08:00
|
|
|
FormattingOff = false;
|
|
|
|
|
2017-11-27 21:23:45 +08:00
|
|
|
const bool EmptyLineSkipped =
|
2018-05-15 03:51:33 +08:00
|
|
|
Trimmed.empty() &&
|
|
|
|
(Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Merge ||
|
|
|
|
Style.IncludeStyle.IncludeBlocks ==
|
|
|
|
tooling::IncludeStyle::IBS_Regroup);
|
2017-11-27 21:23:45 +08:00
|
|
|
|
2015-11-21 17:17:08 +08:00
|
|
|
if (!FormattingOff && !Line.endswith("\\")) {
|
2015-09-23 16:30:47 +08:00
|
|
|
if (IncludeRegex.match(Line, &Matches)) {
|
2015-10-22 01:13:45 +08:00
|
|
|
StringRef IncludeName = Matches[2];
|
2016-05-31 21:34:20 +08:00
|
|
|
int Category = Categories.getIncludePriority(
|
|
|
|
IncludeName,
|
|
|
|
/*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
|
|
|
|
if (Category == 0)
|
|
|
|
MainIncludeFound = true;
|
2015-10-22 01:13:45 +08:00
|
|
|
IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
|
2017-11-27 21:23:45 +08:00
|
|
|
} else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
|
2016-05-20 19:24:24 +08:00
|
|
|
sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
|
|
|
|
Cursor);
|
2015-09-23 16:30:47 +08:00
|
|
|
IncludesInBlock.clear();
|
2015-12-21 21:40:49 +08:00
|
|
|
FirstIncludeBlock = false;
|
2015-09-23 16:30:47 +08:00
|
|
|
}
|
|
|
|
Prev = Pos + 1;
|
|
|
|
}
|
|
|
|
if (Pos == StringRef::npos || Pos + 1 == Code.size())
|
|
|
|
break;
|
|
|
|
SearchFrom = Pos + 1;
|
|
|
|
}
|
|
|
|
if (!IncludesInBlock.empty())
|
2016-05-20 19:24:24 +08:00
|
|
|
sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, Cursor);
|
|
|
|
return Replaces;
|
|
|
|
}
|
|
|
|
|
2018-10-06 01:19:26 +08:00
|
|
|
// Returns group number to use as a first order sort on imports. Gives UINT_MAX
|
|
|
|
// if the import does not match any given groups.
|
|
|
|
static unsigned findJavaImportGroup(const FormatStyle &Style,
|
|
|
|
StringRef ImportIdentifier) {
|
|
|
|
unsigned LongestMatchIndex = UINT_MAX;
|
|
|
|
unsigned LongestMatchLength = 0;
|
|
|
|
for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
|
|
|
|
std::string GroupPrefix = Style.JavaImportGroups[I];
|
|
|
|
if (ImportIdentifier.startswith(GroupPrefix) &&
|
|
|
|
GroupPrefix.length() > LongestMatchLength) {
|
|
|
|
LongestMatchIndex = I;
|
|
|
|
LongestMatchLength = GroupPrefix.length();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return LongestMatchIndex;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Sorts and deduplicates a block of includes given by 'Imports' based on
|
|
|
|
// JavaImportGroups, then adding the necessary replacement to 'Replaces'.
|
|
|
|
// Import declarations with the same text will be deduplicated. Between each
|
|
|
|
// import group, a newline is inserted, and within each import group, a
|
|
|
|
// lexicographic sort based on ASCII value is performed.
|
|
|
|
static void sortJavaImports(const FormatStyle &Style,
|
|
|
|
const SmallVectorImpl<JavaImportDirective> &Imports,
|
|
|
|
ArrayRef<tooling::Range> Ranges, StringRef FileName,
|
2019-03-01 17:09:54 +08:00
|
|
|
StringRef Code, tooling::Replacements &Replaces) {
|
2018-10-06 01:19:26 +08:00
|
|
|
unsigned ImportsBeginOffset = Imports.front().Offset;
|
|
|
|
unsigned ImportsEndOffset =
|
|
|
|
Imports.back().Offset + Imports.back().Text.size();
|
|
|
|
unsigned ImportsBlockSize = ImportsEndOffset - ImportsBeginOffset;
|
|
|
|
if (!affectsRange(Ranges, ImportsBeginOffset, ImportsEndOffset))
|
|
|
|
return;
|
|
|
|
SmallVector<unsigned, 16> Indices;
|
|
|
|
SmallVector<unsigned, 16> JavaImportGroups;
|
|
|
|
for (unsigned i = 0, e = Imports.size(); i != e; ++i) {
|
|
|
|
Indices.push_back(i);
|
|
|
|
JavaImportGroups.push_back(
|
|
|
|
findJavaImportGroup(Style, Imports[i].Identifier));
|
|
|
|
}
|
2019-01-19 02:45:26 +08:00
|
|
|
llvm::sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
|
2019-02-20 19:44:21 +08:00
|
|
|
// Negating IsStatic to push static imports above non-static imports.
|
|
|
|
return std::make_tuple(!Imports[LHSI].IsStatic, JavaImportGroups[LHSI],
|
|
|
|
Imports[LHSI].Identifier) <
|
|
|
|
std::make_tuple(!Imports[RHSI].IsStatic, JavaImportGroups[RHSI],
|
|
|
|
Imports[RHSI].Identifier);
|
|
|
|
});
|
2018-10-06 01:19:26 +08:00
|
|
|
|
|
|
|
// Deduplicate imports.
|
|
|
|
Indices.erase(std::unique(Indices.begin(), Indices.end(),
|
|
|
|
[&](unsigned LHSI, unsigned RHSI) {
|
|
|
|
return Imports[LHSI].Text == Imports[RHSI].Text;
|
|
|
|
}),
|
|
|
|
Indices.end());
|
|
|
|
|
|
|
|
bool CurrentIsStatic = Imports[Indices.front()].IsStatic;
|
|
|
|
unsigned CurrentImportGroup = JavaImportGroups[Indices.front()];
|
|
|
|
|
|
|
|
std::string result;
|
|
|
|
for (unsigned Index : Indices) {
|
|
|
|
if (!result.empty()) {
|
|
|
|
result += "\n";
|
|
|
|
if (CurrentIsStatic != Imports[Index].IsStatic ||
|
|
|
|
CurrentImportGroup != JavaImportGroups[Index])
|
|
|
|
result += "\n";
|
|
|
|
}
|
|
|
|
for (StringRef CommentLine : Imports[Index].AssociatedCommentLines) {
|
|
|
|
result += CommentLine;
|
|
|
|
result += "\n";
|
|
|
|
}
|
|
|
|
result += Imports[Index].Text;
|
|
|
|
CurrentIsStatic = Imports[Index].IsStatic;
|
|
|
|
CurrentImportGroup = JavaImportGroups[Index];
|
|
|
|
}
|
|
|
|
|
2019-02-20 19:44:21 +08:00
|
|
|
// If the imports are out of order, we generate a single replacement fixing
|
|
|
|
// the entire block. Otherwise, no replacement is generated.
|
|
|
|
if (result == Code.substr(Imports.front().Offset, ImportsBlockSize))
|
|
|
|
return;
|
|
|
|
|
2018-10-06 01:19:26 +08:00
|
|
|
auto Err = Replaces.add(tooling::Replacement(FileName, Imports.front().Offset,
|
|
|
|
ImportsBlockSize, result));
|
|
|
|
// FIXME: better error handling. For now, just skip the replacement for the
|
|
|
|
// release version.
|
|
|
|
if (Err) {
|
|
|
|
llvm::errs() << llvm::toString(std::move(Err)) << "\n";
|
|
|
|
assert(false);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
|
|
|
|
const char JavaImportRegexPattern[] =
|
|
|
|
"^[\t ]*import[\t ]*(static[\t ]*)?([^\t ]*)[\t ]*;";
|
|
|
|
|
|
|
|
} // anonymous namespace
|
|
|
|
|
|
|
|
tooling::Replacements sortJavaImports(const FormatStyle &Style, StringRef Code,
|
|
|
|
ArrayRef<tooling::Range> Ranges,
|
|
|
|
StringRef FileName,
|
|
|
|
tooling::Replacements &Replaces) {
|
|
|
|
unsigned Prev = 0;
|
|
|
|
unsigned SearchFrom = 0;
|
|
|
|
llvm::Regex ImportRegex(JavaImportRegexPattern);
|
|
|
|
SmallVector<StringRef, 4> Matches;
|
|
|
|
SmallVector<JavaImportDirective, 16> ImportsInBlock;
|
|
|
|
std::vector<StringRef> AssociatedCommentLines;
|
|
|
|
|
|
|
|
bool FormattingOff = false;
|
|
|
|
|
|
|
|
for (;;) {
|
|
|
|
auto Pos = Code.find('\n', SearchFrom);
|
|
|
|
StringRef Line =
|
|
|
|
Code.substr(Prev, (Pos != StringRef::npos ? Pos : Code.size()) - Prev);
|
|
|
|
|
|
|
|
StringRef Trimmed = Line.trim();
|
|
|
|
if (Trimmed == "// clang-format off")
|
|
|
|
FormattingOff = true;
|
|
|
|
else if (Trimmed == "// clang-format on")
|
|
|
|
FormattingOff = false;
|
|
|
|
|
|
|
|
if (ImportRegex.match(Line, &Matches)) {
|
|
|
|
if (FormattingOff) {
|
|
|
|
// If at least one import line has formatting turned off, turn off
|
|
|
|
// formatting entirely.
|
|
|
|
return Replaces;
|
|
|
|
}
|
|
|
|
StringRef Static = Matches[1];
|
|
|
|
StringRef Identifier = Matches[2];
|
|
|
|
bool IsStatic = false;
|
|
|
|
if (Static.contains("static")) {
|
|
|
|
IsStatic = true;
|
|
|
|
}
|
2019-03-01 17:09:54 +08:00
|
|
|
ImportsInBlock.push_back(
|
|
|
|
{Identifier, Line, Prev, AssociatedCommentLines, IsStatic});
|
2018-10-06 01:19:26 +08:00
|
|
|
AssociatedCommentLines.clear();
|
|
|
|
} else if (Trimmed.size() > 0 && !ImportsInBlock.empty()) {
|
|
|
|
// Associating comments within the imports with the nearest import below
|
|
|
|
AssociatedCommentLines.push_back(Line);
|
|
|
|
}
|
|
|
|
Prev = Pos + 1;
|
|
|
|
if (Pos == StringRef::npos || Pos + 1 == Code.size())
|
|
|
|
break;
|
|
|
|
SearchFrom = Pos + 1;
|
|
|
|
}
|
|
|
|
if (!ImportsInBlock.empty())
|
2019-02-20 19:44:21 +08:00
|
|
|
sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
|
2018-10-06 01:19:26 +08:00
|
|
|
return Replaces;
|
|
|
|
}
|
|
|
|
|
2017-01-27 17:09:11 +08:00
|
|
|
bool isMpegTS(StringRef Code) {
|
|
|
|
// MPEG transport streams use the ".ts" file extension. clang-format should
|
|
|
|
// not attempt to format those. MPEG TS' frame format starts with 0x47 every
|
|
|
|
// 189 bytes - detect that and return.
|
|
|
|
return Code.size() > 188 && Code[0] == 0x47 && Code[188] == 0x47;
|
|
|
|
}
|
|
|
|
|
2017-09-20 17:51:03 +08:00
|
|
|
bool isLikelyXml(StringRef Code) { return Code.ltrim().startswith("<"); }
|
2017-08-29 21:51:38 +08:00
|
|
|
|
2016-05-20 19:24:24 +08:00
|
|
|
tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
|
|
|
|
ArrayRef<tooling::Range> Ranges,
|
|
|
|
StringRef FileName, unsigned *Cursor) {
|
|
|
|
tooling::Replacements Replaces;
|
|
|
|
if (!Style.SortIncludes)
|
|
|
|
return Replaces;
|
2017-08-29 21:57:31 +08:00
|
|
|
if (isLikelyXml(Code))
|
|
|
|
return Replaces;
|
|
|
|
if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript &&
|
|
|
|
isMpegTS(Code))
|
2017-01-27 17:09:11 +08:00
|
|
|
return Replaces;
|
2016-05-20 19:24:24 +08:00
|
|
|
if (Style.Language == FormatStyle::LanguageKind::LK_JavaScript)
|
|
|
|
return sortJavaScriptImports(Style, Code, Ranges, FileName);
|
2018-10-06 01:19:26 +08:00
|
|
|
if (Style.Language == FormatStyle::LanguageKind::LK_Java)
|
|
|
|
return sortJavaImports(Style, Code, Ranges, FileName, Replaces);
|
2016-05-20 19:24:24 +08:00
|
|
|
sortCppIncludes(Style, Code, Ranges, FileName, Replaces, Cursor);
|
2015-09-23 16:30:47 +08:00
|
|
|
return Replaces;
|
|
|
|
}
|
|
|
|
|
2016-04-25 23:09:22 +08:00
|
|
|
template <typename T>
|
2016-07-11 21:53:12 +08:00
|
|
|
static llvm::Expected<tooling::Replacements>
|
2016-04-25 23:09:22 +08:00
|
|
|
processReplacements(T ProcessFunc, StringRef Code,
|
|
|
|
const tooling::Replacements &Replaces,
|
|
|
|
const FormatStyle &Style) {
|
2016-03-01 20:37:30 +08:00
|
|
|
if (Replaces.empty())
|
|
|
|
return tooling::Replacements();
|
|
|
|
|
2016-07-11 21:53:12 +08:00
|
|
|
auto NewCode = applyAllReplacements(Code, Replaces);
|
|
|
|
if (!NewCode)
|
|
|
|
return NewCode.takeError();
|
2016-08-01 18:16:37 +08:00
|
|
|
std::vector<tooling::Range> ChangedRanges = Replaces.getAffectedRanges();
|
2016-03-01 20:37:30 +08:00
|
|
|
StringRef FileName = Replaces.begin()->getFilePath();
|
2016-04-25 23:09:22 +08:00
|
|
|
|
2016-03-01 20:37:30 +08:00
|
|
|
tooling::Replacements FormatReplaces =
|
2016-07-11 21:53:12 +08:00
|
|
|
ProcessFunc(Style, *NewCode, ChangedRanges, FileName);
|
2016-03-01 20:37:30 +08:00
|
|
|
|
2016-08-01 18:16:37 +08:00
|
|
|
return Replaces.merge(FormatReplaces);
|
2016-04-25 23:09:22 +08:00
|
|
|
}
|
2016-03-24 18:21:00 +08:00
|
|
|
|
2016-07-11 21:53:12 +08:00
|
|
|
llvm::Expected<tooling::Replacements>
|
|
|
|
formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
|
|
|
|
const FormatStyle &Style) {
|
2016-04-25 23:09:22 +08:00
|
|
|
// We need to use lambda function here since there are two versions of
|
2016-05-18 21:43:48 +08:00
|
|
|
// `sortIncludes`.
|
|
|
|
auto SortIncludes = [](const FormatStyle &Style, StringRef Code,
|
|
|
|
std::vector<tooling::Range> Ranges,
|
|
|
|
StringRef FileName) -> tooling::Replacements {
|
|
|
|
return sortIncludes(Style, Code, Ranges, FileName);
|
|
|
|
};
|
2016-07-11 21:53:12 +08:00
|
|
|
auto SortedReplaces =
|
2016-05-18 21:43:48 +08:00
|
|
|
processReplacements(SortIncludes, Code, Replaces, Style);
|
2016-07-11 21:53:12 +08:00
|
|
|
if (!SortedReplaces)
|
|
|
|
return SortedReplaces.takeError();
|
2016-05-18 21:43:48 +08:00
|
|
|
|
|
|
|
// We need to use lambda function here since there are two versions of
|
2016-04-25 23:09:22 +08:00
|
|
|
// `reformat`.
|
|
|
|
auto Reformat = [](const FormatStyle &Style, StringRef Code,
|
|
|
|
std::vector<tooling::Range> Ranges,
|
|
|
|
StringRef FileName) -> tooling::Replacements {
|
|
|
|
return reformat(Style, Code, Ranges, FileName);
|
|
|
|
};
|
2016-07-11 21:53:12 +08:00
|
|
|
return processReplacements(Reformat, Code, *SortedReplaces, Style);
|
2016-03-01 20:37:30 +08:00
|
|
|
}
|
|
|
|
|
2016-05-31 21:34:20 +08:00
|
|
|
namespace {
|
|
|
|
|
|
|
|
inline bool isHeaderInsertion(const tooling::Replacement &Replace) {
|
2016-09-23 23:10:56 +08:00
|
|
|
return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 &&
|
2018-10-06 01:19:26 +08:00
|
|
|
llvm::Regex(CppIncludeRegexPattern)
|
|
|
|
.match(Replace.getReplacementText());
|
2016-05-31 21:34:20 +08:00
|
|
|
}
|
|
|
|
|
2016-09-23 23:10:56 +08:00
|
|
|
inline bool isHeaderDeletion(const tooling::Replacement &Replace) {
|
|
|
|
return Replace.getOffset() == UINT_MAX && Replace.getLength() == 1;
|
|
|
|
}
|
|
|
|
|
2016-05-31 21:34:20 +08:00
|
|
|
// FIXME: insert empty lines between newly created blocks.
|
|
|
|
tooling::Replacements
|
|
|
|
fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
|
|
|
|
const FormatStyle &Style) {
|
2017-03-31 21:30:24 +08:00
|
|
|
if (!Style.isCpp())
|
2016-05-31 21:34:20 +08:00
|
|
|
return Replaces;
|
|
|
|
|
|
|
|
tooling::Replacements HeaderInsertions;
|
2016-09-23 23:10:56 +08:00
|
|
|
std::set<llvm::StringRef> HeadersToDelete;
|
2016-08-01 18:16:37 +08:00
|
|
|
tooling::Replacements Result;
|
2016-05-31 21:34:20 +08:00
|
|
|
for (const auto &R : Replaces) {
|
2016-08-01 18:16:37 +08:00
|
|
|
if (isHeaderInsertion(R)) {
|
|
|
|
// Replacements from \p Replaces must be conflict-free already, so we can
|
|
|
|
// simply consume the error.
|
|
|
|
llvm::consumeError(HeaderInsertions.add(R));
|
2016-09-23 23:10:56 +08:00
|
|
|
} else if (isHeaderDeletion(R)) {
|
|
|
|
HeadersToDelete.insert(R.getReplacementText());
|
2016-08-01 18:16:37 +08:00
|
|
|
} else if (R.getOffset() == UINT_MAX) {
|
2016-05-31 21:34:20 +08:00
|
|
|
llvm::errs() << "Insertions other than header #include insertion are "
|
|
|
|
"not supported! "
|
|
|
|
<< R.getReplacementText() << "\n";
|
2016-08-01 18:16:37 +08:00
|
|
|
} else {
|
|
|
|
llvm::consumeError(Result.add(R));
|
|
|
|
}
|
2016-05-31 21:34:20 +08:00
|
|
|
}
|
2016-09-23 23:10:56 +08:00
|
|
|
if (HeaderInsertions.empty() && HeadersToDelete.empty())
|
2016-05-31 21:34:20 +08:00
|
|
|
return Replaces;
|
|
|
|
|
|
|
|
StringRef FileName = Replaces.begin()->getFilePath();
|
2018-05-15 04:17:53 +08:00
|
|
|
tooling::HeaderIncludes Includes(FileName, Code, Style.IncludeStyle);
|
2016-05-31 21:34:20 +08:00
|
|
|
|
2018-05-05 01:55:13 +08:00
|
|
|
for (const auto &Header : HeadersToDelete) {
|
|
|
|
tooling::Replacements Replaces =
|
2018-05-15 04:17:53 +08:00
|
|
|
Includes.remove(Header.trim("\"<>"), Header.startswith("<"));
|
2018-05-05 01:55:13 +08:00
|
|
|
for (const auto &R : Replaces) {
|
|
|
|
auto Err = Result.add(R);
|
|
|
|
if (Err) {
|
|
|
|
// Ignore the deletion on conflict.
|
|
|
|
llvm::errs() << "Failed to add header deletion replacement for "
|
|
|
|
<< Header << ": " << llvm::toString(std::move(Err))
|
|
|
|
<< "\n";
|
2016-09-23 23:10:56 +08:00
|
|
|
}
|
2016-05-31 21:34:20 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-10-06 01:19:26 +08:00
|
|
|
llvm::Regex IncludeRegex = llvm::Regex(CppIncludeRegexPattern);
|
2018-05-05 01:55:13 +08:00
|
|
|
llvm::SmallVector<StringRef, 4> Matches;
|
2016-05-31 21:34:20 +08:00
|
|
|
for (const auto &R : HeaderInsertions) {
|
|
|
|
auto IncludeDirective = R.getReplacementText();
|
|
|
|
bool Matched = IncludeRegex.match(IncludeDirective, &Matches);
|
|
|
|
assert(Matched && "Header insertion replacement must have replacement text "
|
|
|
|
"'#include ...'");
|
2016-05-31 22:14:42 +08:00
|
|
|
(void)Matched;
|
2016-05-31 21:34:20 +08:00
|
|
|
auto IncludeName = Matches[2];
|
2018-05-05 01:55:13 +08:00
|
|
|
auto Replace =
|
2018-05-15 04:17:53 +08:00
|
|
|
Includes.insert(IncludeName.trim("\"<>"), IncludeName.startswith("<"));
|
2018-05-05 01:55:13 +08:00
|
|
|
if (Replace) {
|
|
|
|
auto Err = Result.add(*Replace);
|
|
|
|
if (Err) {
|
|
|
|
llvm::consumeError(std::move(Err));
|
2019-03-01 17:09:54 +08:00
|
|
|
unsigned NewOffset =
|
|
|
|
Result.getShiftedCodePosition(Replace->getOffset());
|
2018-05-05 01:55:13 +08:00
|
|
|
auto Shifted = tooling::Replacement(FileName, NewOffset, 0,
|
|
|
|
Replace->getReplacementText());
|
|
|
|
Result = Result.merge(tooling::Replacements(Shifted));
|
|
|
|
}
|
2016-08-01 18:16:37 +08:00
|
|
|
}
|
2016-05-31 21:34:20 +08:00
|
|
|
}
|
|
|
|
return Result;
|
|
|
|
}
|
|
|
|
|
|
|
|
} // anonymous namespace
|
|
|
|
|
2016-07-11 21:53:12 +08:00
|
|
|
llvm::Expected<tooling::Replacements>
|
2016-04-25 23:09:22 +08:00
|
|
|
cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
|
|
|
|
const FormatStyle &Style) {
|
|
|
|
// We need to use lambda function here since there are two versions of
|
|
|
|
// `cleanup`.
|
|
|
|
auto Cleanup = [](const FormatStyle &Style, StringRef Code,
|
|
|
|
std::vector<tooling::Range> Ranges,
|
|
|
|
StringRef FileName) -> tooling::Replacements {
|
|
|
|
return cleanup(Style, Code, Ranges, FileName);
|
|
|
|
};
|
2016-05-31 21:34:20 +08:00
|
|
|
// Make header insertion replacements insert new headers into correct blocks.
|
|
|
|
tooling::Replacements NewReplaces =
|
|
|
|
fixCppIncludeInsertions(Code, Replaces, Style);
|
|
|
|
return processReplacements(Cleanup, Code, NewReplaces, Style);
|
2016-04-25 23:09:22 +08:00
|
|
|
}
|
|
|
|
|
2017-10-30 22:01:50 +08:00
|
|
|
namespace internal {
|
|
|
|
std::pair<tooling::Replacements, unsigned>
|
|
|
|
reformat(const FormatStyle &Style, StringRef Code,
|
|
|
|
ArrayRef<tooling::Range> Ranges, unsigned FirstStartColumn,
|
|
|
|
unsigned NextStartColumn, unsigned LastStartColumn, StringRef FileName,
|
|
|
|
FormattingAttemptStatus *Status) {
|
2016-04-25 23:09:22 +08:00
|
|
|
FormatStyle Expanded = expandPresets(Style);
|
|
|
|
if (Expanded.DisableFormat)
|
2017-10-30 22:01:50 +08:00
|
|
|
return {tooling::Replacements(), 0};
|
2017-08-29 21:57:31 +08:00
|
|
|
if (isLikelyXml(Code))
|
2017-10-30 22:01:50 +08:00
|
|
|
return {tooling::Replacements(), 0};
|
2017-08-29 21:57:31 +08:00
|
|
|
if (Expanded.Language == FormatStyle::LK_JavaScript && isMpegTS(Code))
|
2017-10-30 22:01:50 +08:00
|
|
|
return {tooling::Replacements(), 0};
|
2017-03-01 23:35:39 +08:00
|
|
|
|
2017-10-30 22:01:50 +08:00
|
|
|
typedef std::function<std::pair<tooling::Replacements, unsigned>(
|
|
|
|
const Environment &)>
|
2017-06-23 19:46:03 +08:00
|
|
|
AnalyzerPass;
|
|
|
|
SmallVector<AnalyzerPass, 4> Passes;
|
|
|
|
|
|
|
|
if (Style.Language == FormatStyle::LK_Cpp) {
|
|
|
|
if (Style.FixNamespaceComments)
|
|
|
|
Passes.emplace_back([&](const Environment &Env) {
|
|
|
|
return NamespaceEndCommentsFixer(Env, Expanded).process();
|
|
|
|
});
|
|
|
|
|
|
|
|
if (Style.SortUsingDeclarations)
|
|
|
|
Passes.emplace_back([&](const Environment &Env) {
|
|
|
|
return UsingDeclarationsSorter(Env, Expanded).process();
|
|
|
|
});
|
2017-03-01 23:35:39 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if (Style.Language == FormatStyle::LK_JavaScript &&
|
2017-06-23 19:46:03 +08:00
|
|
|
Style.JavaScriptQuotes != FormatStyle::JSQS_Leave)
|
|
|
|
Passes.emplace_back([&](const Environment &Env) {
|
|
|
|
return JavaScriptRequoter(Env, Expanded).process();
|
|
|
|
});
|
|
|
|
|
|
|
|
Passes.emplace_back([&](const Environment &Env) {
|
|
|
|
return Formatter(Env, Expanded, Status).process();
|
|
|
|
});
|
|
|
|
|
2018-05-10 05:35:52 +08:00
|
|
|
auto Env =
|
|
|
|
llvm::make_unique<Environment>(Code, FileName, Ranges, FirstStartColumn,
|
|
|
|
NextStartColumn, LastStartColumn);
|
2017-06-23 19:46:03 +08:00
|
|
|
llvm::Optional<std::string> CurrentCode = None;
|
|
|
|
tooling::Replacements Fixes;
|
2017-10-30 22:01:50 +08:00
|
|
|
unsigned Penalty = 0;
|
2017-06-23 19:46:03 +08:00
|
|
|
for (size_t I = 0, E = Passes.size(); I < E; ++I) {
|
2017-10-30 22:01:50 +08:00
|
|
|
std::pair<tooling::Replacements, unsigned> PassFixes = Passes[I](*Env);
|
2017-06-23 19:46:03 +08:00
|
|
|
auto NewCode = applyAllReplacements(
|
2017-10-30 22:01:50 +08:00
|
|
|
CurrentCode ? StringRef(*CurrentCode) : Code, PassFixes.first);
|
2017-06-23 19:46:03 +08:00
|
|
|
if (NewCode) {
|
2017-10-30 22:01:50 +08:00
|
|
|
Fixes = Fixes.merge(PassFixes.first);
|
|
|
|
Penalty += PassFixes.second;
|
2017-06-23 19:46:03 +08:00
|
|
|
if (I + 1 < E) {
|
|
|
|
CurrentCode = std::move(*NewCode);
|
2018-05-10 05:35:52 +08:00
|
|
|
Env = llvm::make_unique<Environment>(
|
2017-06-23 19:46:03 +08:00
|
|
|
*CurrentCode, FileName,
|
2017-10-30 22:01:50 +08:00
|
|
|
tooling::calculateRangesAfterReplacements(Fixes, Ranges),
|
|
|
|
FirstStartColumn, NextStartColumn, LastStartColumn);
|
2017-06-23 19:46:03 +08:00
|
|
|
}
|
|
|
|
}
|
2016-09-08 06:48:53 +08:00
|
|
|
}
|
|
|
|
|
2017-10-30 22:01:50 +08:00
|
|
|
return {Fixes, Penalty};
|
|
|
|
}
|
|
|
|
} // namespace internal
|
|
|
|
|
|
|
|
tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
|
|
|
|
ArrayRef<tooling::Range> Ranges,
|
|
|
|
StringRef FileName,
|
|
|
|
FormattingAttemptStatus *Status) {
|
|
|
|
return internal::reformat(Style, Code, Ranges,
|
|
|
|
/*FirstStartColumn=*/0,
|
|
|
|
/*NextStartColumn=*/0,
|
|
|
|
/*LastStartColumn=*/0, FileName, Status)
|
|
|
|
.first;
|
2016-04-25 23:09:22 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
|
|
|
|
ArrayRef<tooling::Range> Ranges,
|
|
|
|
StringRef FileName) {
|
2017-05-29 16:41:11 +08:00
|
|
|
// cleanups only apply to C++ (they mostly concern ctor commas etc.)
|
|
|
|
if (Style.Language != FormatStyle::LK_Cpp)
|
|
|
|
return tooling::Replacements();
|
2018-05-10 05:35:52 +08:00
|
|
|
return Cleaner(Environment(Code, FileName, Ranges), Style).process().first;
|
2013-05-16 18:40:07 +08:00
|
|
|
}
|
|
|
|
|
2017-04-21 22:35:20 +08:00
|
|
|
tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
|
|
|
|
ArrayRef<tooling::Range> Ranges,
|
|
|
|
StringRef FileName, bool *IncompleteFormat) {
|
|
|
|
FormattingAttemptStatus Status;
|
|
|
|
auto Result = reformat(Style, Code, Ranges, FileName, &Status);
|
|
|
|
if (!Status.FormatComplete)
|
|
|
|
*IncompleteFormat = true;
|
|
|
|
return Result;
|
|
|
|
}
|
|
|
|
|
2017-02-27 21:28:36 +08:00
|
|
|
tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
|
|
|
|
StringRef Code,
|
|
|
|
ArrayRef<tooling::Range> Ranges,
|
|
|
|
StringRef FileName) {
|
2018-05-10 05:35:52 +08:00
|
|
|
return NamespaceEndCommentsFixer(Environment(Code, FileName, Ranges), Style)
|
|
|
|
.process()
|
|
|
|
.first;
|
2017-02-27 21:28:36 +08:00
|
|
|
}
|
|
|
|
|
2017-06-21 20:03:12 +08:00
|
|
|
tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
|
|
|
|
StringRef Code,
|
|
|
|
ArrayRef<tooling::Range> Ranges,
|
|
|
|
StringRef FileName) {
|
2018-05-10 05:35:52 +08:00
|
|
|
return UsingDeclarationsSorter(Environment(Code, FileName, Ranges), Style)
|
|
|
|
.process()
|
|
|
|
.first;
|
2017-06-21 20:03:12 +08:00
|
|
|
}
|
|
|
|
|
2014-09-05 02:23:42 +08:00
|
|
|
LangOptions getFormattingLangOpts(const FormatStyle &Style) {
|
2013-01-10 21:08:12 +08:00
|
|
|
LangOptions LangOpts;
|
|
|
|
LangOpts.CPlusPlus = 1;
|
2014-09-05 02:23:42 +08:00
|
|
|
LangOpts.CPlusPlus11 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
|
|
|
|
LangOpts.CPlusPlus14 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
|
2017-12-05 04:27:34 +08:00
|
|
|
LangOpts.CPlusPlus17 = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
|
2017-12-14 23:16:18 +08:00
|
|
|
LangOpts.CPlusPlus2a = Style.Standard == FormatStyle::LS_Cpp03 ? 0 : 1;
|
2013-03-22 18:01:29 +08:00
|
|
|
LangOpts.LineComment = 1;
|
2017-03-31 21:30:24 +08:00
|
|
|
bool AlternativeOperators = Style.isCpp();
|
2014-11-14 17:02:28 +08:00
|
|
|
LangOpts.CXXOperatorNames = AlternativeOperators ? 1 : 0;
|
2013-01-10 21:08:12 +08:00
|
|
|
LangOpts.Bool = 1;
|
2018-10-31 04:31:30 +08:00
|
|
|
LangOpts.ObjC = 1;
|
2016-04-25 23:09:22 +08:00
|
|
|
LangOpts.MicrosoftExt = 1; // To get kw___try, kw___finally.
|
2015-10-05 01:51:05 +08:00
|
|
|
LangOpts.DeclSpecKeyword = 1; // To get __declspec.
|
2013-01-10 21:08:12 +08:00
|
|
|
return LangOpts;
|
|
|
|
}
|
|
|
|
|
2013-09-30 21:31:48 +08:00
|
|
|
const char *StyleOptionHelpDescription =
|
|
|
|
"Coding style, currently supports:\n"
|
|
|
|
" LLVM, Google, Chromium, Mozilla, WebKit.\n"
|
|
|
|
"Use -style=file to load style configuration from\n"
|
|
|
|
".clang-format file located in one of the parent\n"
|
|
|
|
"directories of the source file (or current\n"
|
|
|
|
"directory for stdin).\n"
|
|
|
|
"Use -style=\"{key: value, ...}\" to set specific\n"
|
|
|
|
"parameters, e.g.:\n"
|
|
|
|
" -style=\"{BasedOnStyle: llvm, IndentWidth: 8}\"";
|
|
|
|
|
2013-12-10 19:28:13 +08:00
|
|
|
static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {
|
2015-12-25 16:53:31 +08:00
|
|
|
if (FileName.endswith(".java"))
|
2014-09-15 19:21:46 +08:00
|
|
|
return FormatStyle::LK_Java;
|
2015-12-25 16:53:31 +08:00
|
|
|
if (FileName.endswith_lower(".js") || FileName.endswith_lower(".ts"))
|
|
|
|
return FormatStyle::LK_JavaScript; // JavaScript or TypeScript.
|
2016-12-12 20:42:29 +08:00
|
|
|
if (FileName.endswith(".m") || FileName.endswith(".mm"))
|
|
|
|
return FormatStyle::LK_ObjC;
|
2015-12-25 16:53:31 +08:00
|
|
|
if (FileName.endswith_lower(".proto") ||
|
|
|
|
FileName.endswith_lower(".protodevel"))
|
2014-01-19 17:04:08 +08:00
|
|
|
return FormatStyle::LK_Proto;
|
2017-11-17 23:10:49 +08:00
|
|
|
if (FileName.endswith_lower(".textpb") ||
|
|
|
|
FileName.endswith_lower(".pb.txt") ||
|
|
|
|
FileName.endswith_lower(".textproto") ||
|
|
|
|
FileName.endswith_lower(".asciipb"))
|
|
|
|
return FormatStyle::LK_TextProto;
|
2015-12-25 16:53:31 +08:00
|
|
|
if (FileName.endswith_lower(".td"))
|
|
|
|
return FormatStyle::LK_TableGen;
|
2013-12-10 19:28:13 +08:00
|
|
|
return FormatStyle::LK_Cpp;
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
|
|
|
|
2018-02-21 23:54:31 +08:00
|
|
|
FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {
|
2018-02-27 23:56:40 +08:00
|
|
|
const auto GuessedLanguage = getLanguageByFileName(FileName);
|
|
|
|
if (GuessedLanguage == FormatStyle::LK_Cpp) {
|
2018-02-22 05:27:27 +08:00
|
|
|
auto Extension = llvm::sys::path::extension(FileName);
|
2018-02-21 23:54:31 +08:00
|
|
|
// If there's no file extension (or it's .h), we need to check the contents
|
|
|
|
// of the code to see if it contains Objective-C.
|
2018-02-22 05:27:27 +08:00
|
|
|
if (Extension.empty() || Extension == ".h") {
|
|
|
|
auto NonEmptyFileName = FileName.empty() ? "guess.h" : FileName;
|
2018-05-10 05:35:52 +08:00
|
|
|
Environment Env(Code, NonEmptyFileName, /*Ranges=*/{});
|
|
|
|
ObjCHeaderStyleGuesser Guesser(Env, getLLVMStyle());
|
2018-02-21 23:54:31 +08:00
|
|
|
Guesser.process();
|
2018-02-27 23:56:40 +08:00
|
|
|
if (Guesser.isObjC())
|
|
|
|
return FormatStyle::LK_ObjC;
|
2018-02-21 23:54:31 +08:00
|
|
|
}
|
|
|
|
}
|
2018-02-27 23:56:40 +08:00
|
|
|
return GuessedLanguage;
|
2018-02-21 23:54:31 +08:00
|
|
|
}
|
|
|
|
|
2018-06-26 00:29:19 +08:00
|
|
|
const char *DefaultFormatStyle = "file";
|
|
|
|
|
|
|
|
const char *DefaultFallbackStyle = "LLVM";
|
|
|
|
|
2017-01-17 08:12:27 +08:00
|
|
|
llvm::Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
|
2017-01-20 09:22:42 +08:00
|
|
|
StringRef FallbackStyleName,
|
2018-10-10 21:27:25 +08:00
|
|
|
StringRef Code,
|
|
|
|
llvm::vfs::FileSystem *FS) {
|
2016-03-24 21:22:42 +08:00
|
|
|
if (!FS) {
|
2018-10-10 21:27:25 +08:00
|
|
|
FS = llvm::vfs::getRealFileSystem().get();
|
2016-03-24 21:22:42 +08:00
|
|
|
}
|
2019-03-01 03:16:45 +08:00
|
|
|
FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
|
2016-12-12 20:42:29 +08:00
|
|
|
|
2017-01-20 09:22:42 +08:00
|
|
|
FormatStyle FallbackStyle = getNoStyle();
|
|
|
|
if (!getPredefinedStyle(FallbackStyleName, Style.Language, &FallbackStyle))
|
|
|
|
return make_string_error("Invalid fallback style \"" + FallbackStyleName);
|
2013-09-30 21:31:48 +08:00
|
|
|
|
|
|
|
if (StyleName.startswith("{")) {
|
|
|
|
// Parse YAML/JSON style from the command line.
|
2017-01-17 08:12:27 +08:00
|
|
|
if (std::error_code ec = parseConfiguration(StyleName, &Style))
|
|
|
|
return make_string_error("Error parsing -style: " + ec.message());
|
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))
|
2017-01-17 08:12:27 +08:00
|
|
|
return make_string_error("Invalid value for -style");
|
2013-09-30 21:31:48 +08:00
|
|
|
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);
|
2017-01-17 08:12:27 +08:00
|
|
|
if (std::error_code EC = FS->makeAbsolute(Path))
|
|
|
|
return make_string_error(EC.message());
|
2016-12-22 13:10:07 +08:00
|
|
|
|
2013-10-14 08:46:35 +08:00
|
|
|
for (StringRef Directory = Path; !Directory.empty();
|
2013-09-30 21:31:48 +08:00
|
|
|
Directory = llvm::sys::path::parent_path(Directory)) {
|
2016-03-24 21:22:42 +08:00
|
|
|
|
|
|
|
auto Status = FS->status(Directory);
|
|
|
|
if (!Status ||
|
|
|
|
Status->getType() != llvm::sys::fs::file_type::directory_file) {
|
2013-09-30 21:31:48 +08:00
|
|
|
continue;
|
2016-03-24 21:22:42 +08:00
|
|
|
}
|
|
|
|
|
2013-09-30 21:31:48 +08:00
|
|
|
SmallString<128> ConfigFile(Directory);
|
|
|
|
|
|
|
|
llvm::sys::path::append(ConfigFile, ".clang-format");
|
2018-05-15 21:30:56 +08:00
|
|
|
LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
|
2016-03-24 21:22:37 +08:00
|
|
|
|
2016-03-24 21:22:42 +08:00
|
|
|
Status = FS->status(ConfigFile.str());
|
2017-01-17 08:12:27 +08:00
|
|
|
bool FoundConfigFile =
|
2016-03-24 21:22:42 +08:00
|
|
|
Status && (Status->getType() == llvm::sys::fs::file_type::regular_file);
|
2017-01-17 08:12:27 +08:00
|
|
|
if (!FoundConfigFile) {
|
2013-09-30 21:31:48 +08:00
|
|
|
// Try _clang-format too, since dotfiles are not commonly used on Windows.
|
|
|
|
ConfigFile = Directory;
|
|
|
|
llvm::sys::path::append(ConfigFile, "_clang-format");
|
2018-05-15 21:30:56 +08:00
|
|
|
LLVM_DEBUG(llvm::dbgs() << "Trying " << ConfigFile << "...\n");
|
2016-03-24 21:22:42 +08:00
|
|
|
Status = FS->status(ConfigFile.str());
|
2017-01-17 08:12:27 +08:00
|
|
|
FoundConfigFile = Status && (Status->getType() ==
|
|
|
|
llvm::sys::fs::file_type::regular_file);
|
2013-09-30 21:31:48 +08:00
|
|
|
}
|
|
|
|
|
2017-01-17 08:12:27 +08:00
|
|
|
if (FoundConfigFile) {
|
2014-07-07 01:43:24 +08:00
|
|
|
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
|
2016-03-24 21:22:42 +08:00
|
|
|
FS->getBufferForFile(ConfigFile.str());
|
2017-01-17 08:12:27 +08:00
|
|
|
if (std::error_code EC = Text.getError())
|
|
|
|
return make_string_error(EC.message());
|
2014-07-07 01:43:24 +08:00
|
|
|
if (std::error_code ec =
|
|
|
|
parseConfiguration(Text.get()->getBuffer(), &Style)) {
|
2014-06-12 10:50:04 +08:00
|
|
|
if (ec == ParseError::Unsuitable) {
|
2013-11-29 23:19:43 +08:00
|
|
|
if (!UnsuitableConfigFiles.empty())
|
|
|
|
UnsuitableConfigFiles.append(", ");
|
|
|
|
UnsuitableConfigFiles.append(ConfigFile);
|
2013-12-02 23:21:38 +08:00
|
|
|
continue;
|
2013-11-29 23:19:43 +08:00
|
|
|
}
|
2017-01-17 08:12:27 +08:00
|
|
|
return make_string_error("Error reading " + ConfigFile + ": " +
|
|
|
|
ec.message());
|
2013-09-30 21:31:48 +08:00
|
|
|
}
|
2018-05-15 21:30:56 +08:00
|
|
|
LLVM_DEBUG(llvm::dbgs()
|
|
|
|
<< "Using configuration file " << ConfigFile << "\n");
|
2013-09-30 21:31:48 +08:00
|
|
|
return Style;
|
|
|
|
}
|
|
|
|
}
|
2017-01-17 08:12:27 +08:00
|
|
|
if (!UnsuitableConfigFiles.empty())
|
|
|
|
return make_string_error("Configuration file(s) do(es) not support " +
|
|
|
|
getLanguageName(Style.Language) + ": " +
|
|
|
|
UnsuitableConfigFiles);
|
2017-01-20 09:22:42 +08:00
|
|
|
return FallbackStyle;
|
2013-09-30 21:31:48 +08:00
|
|
|
}
|
|
|
|
|
2013-01-07 21:26:07 +08:00
|
|
|
} // namespace format
|
|
|
|
} // namespace clang
|