Tech News
← Back to articles

Improvements to OCaml code editing: the basics of a refactor engine

read original related products more articles

Refactoring features have contributed to the popularity of editors like IntelliJ, as well as certain programming languages whose editor support offers interactive mechanisms to manage code — Gleam being an excellent example. Even though OCaml has some features related to refactoring (such as renaming occurrences, substituting typed holes with expressions, and case analysis for pattern matching), the goal of my internship was to kickstart work on a robust set of features to enable the smooth integration of multiple complementary refactoring support commands.

As part of my Tarides internship (on the editor side), I specified several useful commands, inspired by competitors and materialised in the form of RFCs, subject to discussion. There were multiple candidates, but we found that expression extraction to toplevel was the most suitable for a first experiment. Since it touched on several parts of the protocol and required tools that could be reused for other features, it was important to design the system with extensibility and modularity in mind.

In this article, I will present the results of this experiment, including the new command and some interesting use cases.

Examples

Expression extraction to toplevel will select the most inclusive expression that fits in your selection and propose to extract it. In this case, extract means that the selected expression will be moved into its own freshly generated let binding top level.

Extracting Constants

Here is a first example: Let's try to extract a constant. Let’s assume that the float 3.14159 is selected in the following code snippet:

let circle_area radius = 3.14159 *. ( radius ** 2. )

The extract action code will then be proposed, and if you apply it, the code will look like this:

let const_name1 = 3.14159 let circle_area radius = const_name1 *. ( radius ** 2. )

... continue reading