brintos

brintos / llvm-project-archived public Read only

0
0
Text · 10.7 KiB · e0d16ef Raw
254 lines · plain
1==========================2Clang's refactoring engine3==========================4 5This document describes the design of Clang's refactoring engine and provides6a couple of examples that show how various primitives in the refactoring API7can be used to implement different refactoring actions. The :doc:`LibTooling`8library provides several other APIs that are used when developing a9refactoring action.10 11Refactoring engine can be used to implement local refactorings that are12initiated using a selection in an editor or an IDE. You can combine13:doc:`AST matchers<LibASTMatchers>` and the refactoring engine to implement14refactorings that don't lend themselves well to source selection and/or have to15query ASTs for some particular nodes.16 17We assume basic knowledge about the Clang AST. See the :doc:`Introduction18to the Clang AST <IntroductionToTheClangAST>` if you want to learn more19about how the AST is structured.20 21..  FIXME: create new refactoring action tutorial and link to the tutorial22 23Introduction24------------25 26Clang's refactoring engine defines a set refactoring actions that implement27a number of different source transformations. The ``clang-refactor``28command-line tool can be used to perform these refactorings. Certain29refactorings are also available in other clients like text editors and IDEs.30 31A refactoring action is a class that defines a list of related refactoring32operations (rules). These rules are grouped under a common umbrella - a single33``clang-refactor`` command. In addition to rules, the refactoring action34provides the action's command name and description to ``clang-refactor``.35Each action must implement the ``RefactoringAction`` interface. Here's an36outline of a ``local-rename`` action:37 38.. code-block:: c++39 40  class LocalRename final : public RefactoringAction {41  public:42    StringRef getCommand() const override { return "local-rename"; }43 44    StringRef getDescription() const override {45      return "Finds and renames symbols in code with no indexer support";46    }47 48    RefactoringActionRules createActionRules() const override {49      ...50    }51  };52 53Refactoring Action Rules54------------------------55 56An individual refactoring action is responsible for creating the set of57grouped refactoring action rules that represent one refactoring operation.58Although the rules in one action may have a number of different implementations,59they should strive to produce a similar result. It should be easy for users to60identify which refactoring action produced the result regardless of which61refactoring action rule was used.62 63The distinction between actions and rules enables the creation of actions64that define a set of different rules that produce similar results. For example,65the "add missing switch cases" refactoring operation typically adds missing66cases to one switch at a time. However, it could be useful to have a67refactoring that works on all switches that operate on a particular enum, as68one could then automatically update all of them after adding a new enum69constant. To achieve that, we can create two different rules that will use one70``clang-refactor`` subcommand. The first rule will describe a local operation71that's initiated when the user selects a single switch. The second rule will72describe a global operation that works across translation units and is initiated73when the user provides the name of the enum to clang-refactor (or the user could74select the enum declaration instead). The clang-refactor tool will then analyze75the selection and other options passed to the refactoring action, and will pick76the most appropriate rule for the given selection and other options.77 78Rule Types79^^^^^^^^^^80 81Clang's refactoring engine supports several different refactoring rules:82 83- ``SourceChangeRefactoringRule`` produces source replacements that are applied84  to the source files. Subclasses that choose to implement this rule have to85  implement the ``createSourceReplacements`` member function. This type of86  rule is typically used to implement local refactorings that transform the87  source in one translation unit only.88 89- ``FindSymbolOccurrencesRefactoringRule`` produces a "partial" refactoring90  result: a set of occurrences that refer to a particular symbol. This type91  of rule is typically used to implement an interactive renaming action that92  allows users to specify which occurrences should be renamed during the93  refactoring. Subclasses that choose to implement this rule have to implement94  the ``findSymbolOccurrences`` member function.95 96The following set of quick checks might help if you are unsure about the type97of rule you should use:98 99#. If you would like to transform the source in one translation unit and if100   you don't need any cross-TU information, then the101   ``SourceChangeRefactoringRule`` should work for you.102 103#. If you would like to implement a rename-like operation with potential104   interactive components, then ``FindSymbolOccurrencesRefactoringRule`` might105   work for you.106 107How to Create a Rule108^^^^^^^^^^^^^^^^^^^^109 110Once you determine which type of rule is suitable for your needs you can111implement the refactoring by subclassing the rule and implementing its112interface. The subclass should have a constructor that takes the inputs that113are needed to perform the refactoring. For example, if you want to implement a114rule that simply deletes a selection, you should create a subclass of115``SourceChangeRefactoringRule`` with a constructor that accepts the selection116range:117 118.. code-block:: c++119 120  class DeleteSelectedRange final : public SourceChangeRefactoringRule {121  public:122    DeleteSelection(SourceRange Selection) : Selection(Selection) {}123 124    Expected<AtomicChanges>125    createSourceReplacements(RefactoringRuleContext &Context) override {126      AtomicChange Replacement(Context.getSources(), Selection.getBegin());127      Replacement.replace(Context.getSource,128                          CharSourceRange::getCharRange(Selection), "");129      return { Replacement };130    }131  private:132    SourceRange Selection;133  };134 135The rule's subclass can then be added to the list of refactoring action's136rules for a particular action using the ``createRefactoringActionRule``137function. For example, the class that's shown above can be added to the138list of action rules using the following code:139 140.. code-block:: c++141 142  RefactoringActionRules Rules;143  Rules.push_back(144    createRefactoringActionRule<DeleteSelectedRange>(145          SourceRangeSelectionRequirement())146  );147 148The ``createRefactoringActionRule`` function takes in a list of refactoring149action rule requirement values. These values describe the initiation150requirements that have to be satisfied by the refactoring engine before the151provided action rule can be constructed and invoked. The next section152describes how these requirements are evaluated and lists all the possible153requirements that can be used to construct a refactoring action rule.154 155Refactoring Action Rule Requirements156------------------------------------157 158A refactoring action rule requirement is a value whose type derives from the159``RefactoringActionRuleRequirement`` class. The type must define an160``evaluate`` member function that returns a value of type ``Expected<...>``.161When a requirement value is used as an argument to162``createRefactoringActionRule``, that value is evaluated during the initiation163of the action rule. The evaluated result is then passed to the rule's164constructor unless the evaluation produced an error. For example, the165``DeleteSelectedRange`` sample rule that's defined in the previous section166will be evaluated using the following steps:167 168#. ``SourceRangeSelectionRequirement``'s ``evaluate`` member function will be169   called first. It will return an ``Expected<SourceRange>``.170 171#. If the return value is an error the initiation will fail and the error172   will be reported to the client. Note that the client may not report the173   error to the user.174 175#. Otherwise the source range return value will be used to construct the176   ``DeleteSelectedRange`` rule. The rule will then be invoked as the initiation177   succeeded (all requirements were evaluated successfully).178 179The same series of steps applies to any refactoring rule. Firstly, the engine180will evaluate all of the requirements. Then it will check if these requirements181are satisfied (they should not produce an error). Then it will construct the182rule and invoke it.183 184The separation of requirements, their evaluation and the invocation of the185refactoring action rule allows the refactoring clients to:186 187- Disable refactoring action rules whose requirements are not supported.188 189- Gather the set of options and define a command-line / visual interface190  that allows users to input these options without ever invoking the191  action.192 193Selection Requirements194^^^^^^^^^^^^^^^^^^^^^^195 196The refactoring rule requirements that require some form of source selection197are listed below:198 199- ``SourceRangeSelectionRequirement`` evaluates to a source range when the200  action is invoked with some sort of selection. This requirement should be201  satisfied when a refactoring is initiated in an editor, even when the user202  has not selected anything (the range will contain the cursor's location in203  that case).204 205..  FIXME: Future selection requirements206 207..  FIXME: Maybe mention custom selection requirements?208 209Other Requirements210^^^^^^^^^^^^^^^^^^211 212There are several other requirements types that can be used when creating213a refactoring rule:214 215- The ``RefactoringOptionsRequirement`` requirement is an abstract class that216  should be subclassed by requirements working with options. The more217  concrete ``OptionRequirement`` requirement is a simple implementation of the218  aforementioned class that returns the value of the specified option when219  it's evaluated. The next section talks more about refactoring options and220  how they can be used when creating a rule.221 222Refactoring Options223-------------------224 225Refactoring options are values that affect a refactoring operation and are226specified either using command-line options or another client-specific227mechanism. Options should be created using a class that derives either from228the ``OptionalRequiredOption`` or ``RequiredRefactoringOption``. The following229example shows how one can created a required string option that corresponds to230the ``-new-name`` command-line option in clang-refactor:231 232.. code-block:: c++233 234  class NewNameOption : public RequiredRefactoringOption<std::string> {235  public:236    StringRef getName() const override { return "new-name"; }237    StringRef getDescription() const override {238      return "The new name to change the symbol to";239    }240  };241 242The option that's shown in the example above can then be used to create243a requirement for a refactoring rule using a requirement like244``OptionRequirement``:245 246.. code-block:: c++247 248  createRefactoringActionRule<RenameOccurrences>(249    ...,250    OptionRequirement<NewNameOption>())251  );252 253..  FIXME: Editor Bindings section254