llvm/clang-tools-extra/clangd/refactor/Tweak.h

//===--- Tweak.h -------------------------------------------------*- C++-*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Tweaks are small actions that run over the AST and produce edits, messages
// etc as a result. They are local, i.e. they should take the current editor
// context, e.g. the cursor position and selection into account.
// The actions are executed in two stages:
//   - Stage 1 should check whether the action is available in a current
//     context. It should be cheap and fast to compute as it is executed for all
//     available actions on every client request, which happen quite frequently.
//   - Stage 2 is performed after stage 1 and can be more expensive to compute.
//     It is performed when the user actually chooses the action.
//===----------------------------------------------------------------------===//

#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_REFACTOR_TWEAK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANGD_REFACTOR_TWEAK_H

#include "ParsedAST.h"
#include "Selection.h"
#include "SourceCode.h"
#include "index/Index.h"
#include "support/Path.h"
#include "clang/Tooling/Core/Replacement.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Error.h"
#include <optional>
#include <string>

namespace clang {
namespace clangd {

class FeatureModuleSet;

/// An interface base for small context-sensitive refactoring actions.
/// To implement a new tweak use the following pattern in a .cpp file:
///   class MyTweak : public Tweak {
///   public:
///     const char* id() const override final; // defined by REGISTER_TWEAK.
///     // implement other methods here.
///   };
///   REGISTER_TWEAK(MyTweak);
class Tweak {};

// All tweaks must be registered in the .cpp file next to their definition.
#define REGISTER_TWEAK(Subclass)

/// Calls prepare() on all tweaks that satisfy the filter, returning those that
/// can run on the selection.
std::vector<std::unique_ptr<Tweak>>
prepareTweaks(const Tweak::Selection &S,
              llvm::function_ref<bool(const Tweak &)> Filter,
              const FeatureModuleSet *Modules);

// Calls prepare() on the tweak with a given ID.
// If prepare() returns false, returns an error.
// If prepare() returns true, returns the corresponding tweak.
llvm::Expected<std::unique_ptr<Tweak>>
prepareTweak(StringRef ID, const Tweak::Selection &S,
             const FeatureModuleSet *Modules);
} // namespace clangd
} // namespace clang

#endif