llvm/clang/lib/Format/Format.cpp

//===--- Format.cpp - Format C++ code -------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements functions declared in Format.h. This will be
/// split into separate files as we go.
///
//===----------------------------------------------------------------------===//

#include "clang/Format/Format.h"
#include "DefinitionBlockSeparator.h"
#include "IntegerLiteralSeparatorFixer.h"
#include "NamespaceEndCommentsFixer.h"
#include "ObjCPropertyAttributeOrderFixer.h"
#include "QualifierAlignmentFixer.h"
#include "SortJavaScriptImports.h"
#include "UnwrappedLineFormatter.h"
#include "UsingDeclarationsSorter.h"
#include "clang/Tooling/Inclusions/HeaderIncludes.h"
#include "llvm/ADT/Sequence.h"

#define DEBUG_TYPE

FormatStyle;

LLVM_YAML_IS_SEQUENCE_VECTOR(FormatStyle::RawStringFormat)

namespace llvm {
namespace yaml {
template <>
struct ScalarEnumerationTraits<FormatStyle::BreakBeforeNoexceptSpecifierStyle> {};

template <> struct MappingTraits<FormatStyle::AlignConsecutiveStyle> {};

template <>
struct MappingTraits<FormatStyle::ShortCaseStatementsAlignmentStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::AttributeBreakingStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::ArrayInitializerAlignmentStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::BinaryOperatorStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::BinPackParametersStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::BinPackStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::BitFieldColonSpacingStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::BraceBreakingStyle> {};

template <> struct MappingTraits<FormatStyle::BraceWrappingFlags> {};

template <> struct ScalarEnumerationTraits<FormatStyle::BracketAlignmentStyle> {};

template <>
struct ScalarEnumerationTraits<
    FormatStyle::BraceWrappingAfterControlStatementStyle> {};

template <>
struct ScalarEnumerationTraits<
    FormatStyle::BreakBeforeConceptDeclarationsStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::BreakBeforeInlineASMColonStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::BreakBinaryOperationsStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::BreakConstructorInitializersStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::BreakInheritanceListStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::BreakTemplateDeclarationsStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::DAGArgStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::DefinitionReturnTypeBreakingStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::EscapedNewlineAlignmentStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::EmptyLineAfterAccessModifierStyle> {};

template <>
struct ScalarEnumerationTraits<
    FormatStyle::EmptyLineBeforeAccessModifierStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::IndentExternBlockStyle> {};

template <> struct MappingTraits<FormatStyle::IntegerLiteralSeparatorStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::JavaScriptQuoteStyle> {};

template <> struct MappingTraits<FormatStyle::KeepEmptyLinesStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::LanguageKind> {};

template <> struct ScalarEnumerationTraits<FormatStyle::LanguageStandard> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::LambdaBodyIndentationKind> {};

template <> struct ScalarEnumerationTraits<FormatStyle::LineEndingStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::NamespaceIndentationKind> {};

template <> struct ScalarEnumerationTraits<FormatStyle::OperandAlignmentStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::PackConstructorInitializersStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::PointerAlignmentStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::PPDirectiveIndentStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::QualifierAlignmentStyle> {};

template <> struct MappingTraits<FormatStyle::RawStringFormat> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::ReferenceAlignmentStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::RemoveParenthesesStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::RequiresClausePositionStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::RequiresExpressionIndentationKind> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::ReturnTypeBreakingStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::SeparateDefinitionStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::ShortBlockStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::ShortFunctionStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::ShortIfStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::ShortLambdaStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::SortIncludesOptions> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::SortJavaStaticImportOptions> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::SortUsingDeclarationsOptions> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::SpaceAroundPointerQualifiersStyle> {};

template <> struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::SpaceBeforeParensStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInAnglesStyle> {};

template <> struct MappingTraits<FormatStyle::SpacesInLineComment> {};

template <> struct MappingTraits<FormatStyle::SpacesInParensCustom> {};

template <> struct ScalarEnumerationTraits<FormatStyle::SpacesInParensStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::TrailingCommaStyle> {};

template <>
struct ScalarEnumerationTraits<FormatStyle::TrailingCommentsAlignmentKinds> {};

template <> struct MappingTraits<FormatStyle::TrailingCommentsAlignmentStyle> {};

template <> struct ScalarEnumerationTraits<FormatStyle::UseTabStyle> {};

template <> struct MappingTraits<FormatStyle> {};

// Allows to read vector<FormatStyle> while keeping default values.
// 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.
template <> struct DocumentListTraits<std::vector<FormatStyle>> {};
} // namespace yaml
} // namespace llvm

namespace clang {
namespace format {

const std::error_category &getParseCategory() {}
std::error_code make_error_code(ParseError e) {}

inline llvm::Error make_string_error(const Twine &Message) {}

const char *ParseErrorCategory::name() const noexcept {}

std::string ParseErrorCategory::message(int EV) const {}

static void expandPresetsBraceWrapping(FormatStyle &Expanded) {}

static void expandPresetsSpaceBeforeParens(FormatStyle &Expanded) {}

static void expandPresetsSpacesInParens(FormatStyle &Expanded) {}

FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) {}

FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {}

FormatStyle getChromiumStyle(FormatStyle::LanguageKind Language) {}

FormatStyle getMozillaStyle() {}

FormatStyle getWebKitStyle() {}

FormatStyle getGNUStyle() {}

FormatStyle getMicrosoftStyle(FormatStyle::LanguageKind Language) {}

FormatStyle getClangFormatStyle() {}

FormatStyle getNoStyle() {}

bool getPredefinedStyle(StringRef Name, FormatStyle::LanguageKind Language,
                        FormatStyle *Style) {}

ParseError validateQualifierOrder(FormatStyle *Style) {}

std::error_code parseConfiguration(llvm::MemoryBufferRef Config,
                                   FormatStyle *Style, bool AllowUnknownOptions,
                                   llvm::SourceMgr::DiagHandlerTy DiagHandler,
                                   void *DiagHandlerCtxt) {}

std::string configurationAsText(const FormatStyle &Style) {}

std::optional<FormatStyle>
FormatStyle::FormatStyleSet::Get(FormatStyle::LanguageKind Language) const {}

void FormatStyle::FormatStyleSet::Add(FormatStyle Style) {}

void FormatStyle::FormatStyleSet::Clear() {}

std::optional<FormatStyle>
FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind Language) const {}

namespace {

class ParensRemover : public TokenAnalyzer {};

class BracesInserter : public TokenAnalyzer {};

class BracesRemover : public TokenAnalyzer {};

class SemiRemover : public TokenAnalyzer {};

class JavaScriptRequoter : public TokenAnalyzer {};

class Formatter : public TokenAnalyzer {};

/// TrailingCommaInserter inserts trailing commas into container literals.
/// E.g.:
///     const x = [
///       1,
///     ];
/// TrailingCommaInserter runs after formatting. To avoid causing a required
/// reformatting (and thus reflow), it never inserts a comma that'd exceed the
/// ColumnLimit.
///
/// Because trailing commas disable binpacking of arrays, TrailingCommaInserter
/// is conceptually incompatible with bin packing.
class TrailingCommaInserter : public TokenAnalyzer {};

// This class clean up the erroneous/redundant code around the given ranges in
// file.
class Cleaner : public TokenAnalyzer {};

class ObjCHeaderStyleGuesser : public TokenAnalyzer {};

struct IncludeDirective {};

struct JavaImportDirective {};

} // end anonymous namespace

// Determines whether 'Ranges' intersects with ('Start', 'End').
static bool affectsRange(ArrayRef<tooling::Range> Ranges, unsigned Start,
                         unsigned End) {}

// 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) {}

// Replace all "\r\n" with "\n".
std::string replaceCRLF(const std::string &Code) {}

// 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.
static void sortCppIncludes(const FormatStyle &Style,
                            const SmallVectorImpl<IncludeDirective> &Includes,
                            ArrayRef<tooling::Range> Ranges, StringRef FileName,
                            StringRef Code, tooling::Replacements &Replaces,
                            unsigned *Cursor) {}

tooling::Replacements sortCppIncludes(const FormatStyle &Style, StringRef Code,
                                      ArrayRef<tooling::Range> Ranges,
                                      StringRef FileName,
                                      tooling::Replacements &Replaces,
                                      unsigned *Cursor) {}

// 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) {}

// 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,
                            StringRef Code, tooling::Replacements &Replaces) {}

namespace {

const char JavaImportRegexPattern[] =;

} // anonymous namespace

tooling::Replacements sortJavaImports(const FormatStyle &Style, StringRef Code,
                                      ArrayRef<tooling::Range> Ranges,
                                      StringRef FileName,
                                      tooling::Replacements &Replaces) {}

bool isMpegTS(StringRef Code) {}

bool isLikelyXml(StringRef Code) {}

tooling::Replacements sortIncludes(const FormatStyle &Style, StringRef Code,
                                   ArrayRef<tooling::Range> Ranges,
                                   StringRef FileName, unsigned *Cursor) {}

template <typename T>
static Expected<tooling::Replacements>
processReplacements(T ProcessFunc, StringRef Code,
                    const tooling::Replacements &Replaces,
                    const FormatStyle &Style) {}

Expected<tooling::Replacements>
formatReplacements(StringRef Code, const tooling::Replacements &Replaces,
                   const FormatStyle &Style) {}

namespace {

inline bool isHeaderInsertion(const tooling::Replacement &Replace) {}

inline bool isHeaderDeletion(const tooling::Replacement &Replace) {}

// FIXME: insert empty lines between newly created blocks.
tooling::Replacements
fixCppIncludeInsertions(StringRef Code, const tooling::Replacements &Replaces,
                        const FormatStyle &Style) {}

} // anonymous namespace

Expected<tooling::Replacements>
cleanupAroundReplacements(StringRef Code, const tooling::Replacements &Replaces,
                          const FormatStyle &Style) {}

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) {}
} // namespace internal

tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
                               ArrayRef<tooling::Range> Ranges,
                               StringRef FileName,
                               FormattingAttemptStatus *Status) {}

tooling::Replacements cleanup(const FormatStyle &Style, StringRef Code,
                              ArrayRef<tooling::Range> Ranges,
                              StringRef FileName) {}

tooling::Replacements reformat(const FormatStyle &Style, StringRef Code,
                               ArrayRef<tooling::Range> Ranges,
                               StringRef FileName, bool *IncompleteFormat) {}

tooling::Replacements fixNamespaceEndComments(const FormatStyle &Style,
                                              StringRef Code,
                                              ArrayRef<tooling::Range> Ranges,
                                              StringRef FileName) {}

tooling::Replacements sortUsingDeclarations(const FormatStyle &Style,
                                            StringRef Code,
                                            ArrayRef<tooling::Range> Ranges,
                                            StringRef FileName) {}

LangOptions getFormattingLangOpts(const FormatStyle &Style) {}

const char *StyleOptionHelpDescription =;

static FormatStyle::LanguageKind getLanguageByFileName(StringRef FileName) {}

FormatStyle::LanguageKind guessLanguage(StringRef FileName, StringRef Code) {}

// Update StyleOptionHelpDescription above when changing this.
const char *DefaultFormatStyle =;

const char *DefaultFallbackStyle =;

llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
                       FormatStyle *Style, bool AllowUnknownOptions,
                       llvm::SourceMgr::DiagHandlerTy DiagHandler) {}

Expected<FormatStyle> getStyle(StringRef StyleName, StringRef FileName,
                               StringRef FallbackStyleName, StringRef Code,
                               llvm::vfs::FileSystem *FS,
                               bool AllowUnknownOptions,
                               llvm::SourceMgr::DiagHandlerTy DiagHandler) {}

static bool isClangFormatOnOff(StringRef Comment, bool On) {}

bool isClangFormatOn(StringRef Comment) {}

bool isClangFormatOff(StringRef Comment) {}

} // namespace format
} // namespace clang