You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/contributing/plugin-tutorial.md
+50-49
Original file line number
Diff line number
Diff line change
@@ -1,23 +1,24 @@
1
1
# Let’s write a Haskell Language Server plugin
2
+
Originally written by Pepe Iborra, maintained by the Haskell community.
2
3
3
4
Haskell Language Server is an LSP server for the Haskell programming language. It builds on several previous efforts
4
-
to create a Haskell IDE, you can find many more details on the history and architecture in the [IDE 2020](https://mpickering.github.io/ide/index.html) community page.
5
+
to create a Haskell IDE. You can find many more details on the history and architecture in the [IDE 2020](https://mpickering.github.io/ide/index.html) community page.
5
6
6
7
In this article we are going to cover the creation of an HLS plugin from scratch: a code lens to display explicit import lists.
7
-
Along the way we will learn about HLS, its plugin model, and the relationship with ghcide and LSP.
8
+
Along the way we will learn about HLS, its plugin model, and the relationship with `ghcide` and LSP.
8
9
9
10
## Introduction
10
11
11
12
Writing plugins for HLS is a joy. Personally, I enjoy the ability to tap into the gigantic bag of goodies that is GHC, as well as the IDE integration thanks to LSP.
12
13
13
-
In the last couple of months I have written various HLS (and ghcide) plugins for things like:
14
+
In the last couple of months I have written various HLS (and `ghcide`) plugins for things like:
14
15
15
16
1. Suggest imports for variables not in scope,
16
17
2. Remove redundant imports,
17
-
2. Evaluate code in comments (a la doctest),
18
-
3. Integrate the retrie refactoring library.
18
+
2. Evaluate code in comments (à la [doctest](https://docs.python.org/3/library/doctest.html)),
19
+
3. Integrate the [retrie](https://github.com/facebookincubator/retrie) refactoring library.
19
20
20
-
These plugins are small but meaningful steps towards a more polished IDE experience, and in writing them I didn't have to worry about performance, UI, distribution, or even think for the most part, since it's always another tool (usually GHC) doing all the heavy lifting. The plugins also make these tools much more accessible to all the users of HLS.
21
+
These plugins are small but meaningful steps towards a more polished IDE experience, and in writing them I didn't have to worry about performance, UI, distribution, or even think for the most part, since it's always another tool (usually GHC) doing all the heavy lifting. The plugins also make these tools much more accessible to all users of HLS.
21
22
22
23
## The task
23
24
@@ -27,14 +28,14 @@ Here is a visual statement of what we want to accomplish:
27
28
28
29
And here is the gist of the algorithm:
29
30
30
-
1. Request the type checking artefacts from the ghcide subsystem
31
-
2. Extract the actual import lists from the typechecked AST,
31
+
1. Request the type checking artifacts from the `ghcide` subsystem
32
+
2. Extract the actual import lists from the type-checked AST,
32
33
3. Ask GHC to produce the minimal import lists for this AST,
33
-
4. For every import statement without a explicit import list, find out the minimal import list, and produce a code lens to display it together with a command to graft it on.
34
+
4. For every import statement without an explicit import list, find out the minimal import list, and produce a code lens to display it together with a command to graft it on.
34
35
35
36
## Setup
36
37
37
-
To get started, let’s fetch the HLS repo and build it. You need at least GHC 9.0 for this:
38
+
To get started, let’s fetch the HLS repository and build it. You need at least GHC 9.0 for this:
A plugin has a unique id, a set of rules, a set of command handlers, and a set of"providers":
71
+
A plugin has a unique ID, a set of rules, a set of command handlers, and a set of"providers":
71
72
72
-
*Rules add new targets to the Shake build graph defined in ghcide.99%of plugins need not define any new rules.
73
+
*Rules add new targets to the Shake build graph defined in`ghcide`.99%of plugins need not define any new rules.
73
74
*Commands are an LSP abstraction for actions initiated by the user which are handled in the server.These actions can be long running and involve multiple modules.Many plugins define command handlers.
74
75
*Providers are a query-like abstraction where the LSP client asks the server for information.These queries must be fulfilled as quickly as possible.
75
76
76
77
TheHLS codebase includes several plugins under the namespace `Ide.Plugin.*`, the most relevant are:
77
78
78
-
-The ghcide plugin, which embeds ghcide as a plugin (ghcide is also the engine under HLS).
79
-
-The example and example2 plugins, offering a dubious welcome to new contributors
80
-
-The ormolu, fourmolu, floskell and stylish-haskell plugins, a testament to the code formatting wars of our community.
81
-
-The eval plugin, a code lens provider to evaluate code in comments
82
-
-The retrie plugin, a code actions provider to execute retrie commands
79
+
-The`ghcide` plugin, which embeds `ghcide` as a plugin (`ghcide` is also the engine under HLS),
80
+
-The`example`and`example2` plugins, offering a dubious welcome to new contributors,
81
+
-The`ormolu`, `fourmolu`, `floskell`and`stylish-haskell` plugins, a testament to the code formatting wars of our community,
82
+
-The`eval` plugin, a code lens provider to evaluate code in comments,
83
+
-The`retrie` plugin, a code actions provider to execute retrie commands.
83
84
84
85
I would recommend looking at the existing plugins for inspiration and reference.
85
86
@@ -134,11 +135,11 @@ Providers are functions that receive some inputs and produce an IO computation t
134
135
135
136
All providers receive an `LSP.LspFuncs` value, which is a record of functions to perform LSP actions.Most providers can safely ignore this argument, since the LSP interaction is automatically managed by HLS.
136
137
Someof its capabilities are:
137
-
-Querying the LSP client capabilities
138
-
-Manual progress reporting and cancellation, for plugins that provide long running commands (like the Retrie plugin),
139
-
-Custom user interactions via [message dialogs](https://microsoft.github.io/language-server-protocol/specification#window_showMessage).For instance, the Retrie plugin uses this to report skipped modules.
138
+
-Querying the LSP client capabilities,
139
+
-Manual progress reporting and cancellation, for plugins that provide long running commands (like the `retrie` plugin),
140
+
-Custom user interactions via [message dialogs](https://microsoft.github.io/language-server-protocol/specification#window_showMessage).For instance, the `retrie` plugin uses this to report skipped modules.
140
141
141
-
The second argumentplugins receive is `IdeState`, which encapsulates all the ghcide state including the build graph.This allows to request ghcide rule results, which leverages Shake to parallelize and reuse previous results as appropriate.Rule types are instances of the `RuleResult` type family, and
142
+
The second argument, which plugins receive, is `IdeState`. `IdeState` encapsulates all the `ghcide` state including the build graph.This allows to request `ghcide` rule results, which leverages Shake to parallelize and reuse previous results as appropriate.Rule types are instances of the `RuleResult` type family, and
142
143
most of them are defined in `Development.IDE.Core.RuleTypes`.Some relevant rule types are:
143
144
```haskell
144
145
--| The parse tree for the file using GetFileContents
@@ -157,7 +158,7 @@ type instance RuleResult GhcSessionDeps = HscEnvEq
157
158
typeinstanceRuleResultGetModSummary=ModSummary
158
159
```
159
160
160
-
The`use` family of combinators allow to request rule results.For example, the following code is used in the Eval plugin to request a GHC session and a module summary (for the imports) in order to set up an interactive evaluation environment
161
+
The`use` family of combinators allows to request rule results.For example, the following code is used in the `eval` plugin to request a GHC session and a module summary (for the imports) in order to set up an interactive evaluation environment
161
162
```haskell
162
163
let nfp = toNormalizedFilePath' fp
163
164
session <- runAction "runEvalCmd.ghcSession" state $ use_ GhcSessionDeps nfp
@@ -167,7 +168,7 @@ The `use` family of combinators allow to request rule results. For example, the
167
168
There are three flavours of `use` combinators:
168
169
169
170
1.`use*` combinators block and propagate errors,
170
-
2.`useWithStale*` combinators block and switch to stale data in case of error,
171
+
2.`useWithStale*` combinators block and switch to stale data in case of an error,
171
172
3.`useWithStaleFast*` combinators return immediately with stale data if any, or block otherwise.
172
173
173
174
## LSP abstractions
@@ -199,7 +200,7 @@ To keep things simple our plugin won't make use of the unresolved facility, embe
199
200
200
201
## The explicit imports plugin
201
202
202
-
To provide code lenses, our plugin must define a code lens provider as well as a Command handler.
203
+
To provide code lenses, our plugin must define a code lens provider as well as a command handler.
203
204
The code at `Ide.Plugin.Example` shows how the convenience `defaultPluginDescriptor` function is used
204
205
to bootstrap the plugin and how to add the desired providers:
205
206
@@ -221,7 +222,7 @@ Our plugin provider has two components that need to be fleshed out. Let's start
221
222
importLensCommand::PluginCommand
222
223
```
223
224
224
-
`PluginCommand` is a type synonym defined in `LSP.Types` as:
225
+
`PluginCommand` is a datatype defined in `LSP.Types` as:
225
226
226
227
```haskell
227
228
dataPluginCommand=foralla. (FromJSONa) =>
@@ -241,7 +242,7 @@ type CommandFunction a =
241
242
```
242
243
243
244
`CommandFunction` takes in the familiar `LspFuncs` and `IdeState` arguments, together with a JSON encoded argument.
244
-
I recommend checking the LSPspecin order to understand how commands work, but briefly the LSP server (us) initially sends a command descriptor to the client, in this case as part of a code lens.When the client decides to execute the command on behalf of a user action (in this case a click on the code lens), the client sends this descriptor back to the LSP server which then proceeds to handle and execute the command.The latter part is implemented by the `commandFunc` field of our `PluginCommand` value.
245
+
I recommend checking the LSPspecificationsin order to understand how commands work, but briefly the LSP server (us) initially sends a command descriptor to the client, in this case as part of a code lens.When the client decides to execute the command on behalf of a user action (in this case a click on the code lens), the client sends this descriptor back to the LSP server which then proceeds to handle and execute the command.The latter part is implemented by the `commandFunc` field of our `PluginCommand` value.
245
246
246
247
For our command, we are going to have a very simple handler that receives a diff (`WorkspaceEdit`) and returns it to the client.The diff will be generated by our code lens provider and sent as part
247
248
of the code lens to the LSP client, who will send it back to our command handler when the user activates
The code lens provider implements all the steps of the algorithm described earlier:
272
273
273
-
> 1. Request the type checking artefacts from the ghcide subsystem
274
-
> 2. Extract the actual import lists from the typechecked AST,
274
+
> 1. Request the type checking artefacts from the `ghcide` subsystem
275
+
> 2. Extract the actual import lists from the type-checked AST,
275
276
> 3. Ask GHC to produce the minimal import lists for this AST,
276
-
> 4. For every import statement without a explicit import list, find out what's the minimal import list, and produce a code lens to display it together with a diff to graft the import list in.
277
+
> 4. For every import statement without an explicit import list, find out the minimal import list, and produce a code lens to display it together with a command to graft it on.
277
278
278
279
The provider takes the usual `LspFuncs` and `IdeState` argument, as well as a `CodeLensParams` value containing the URI
279
280
for a file, and returns an IO action producing either an error or a list of code lenses for that file.
@@ -282,7 +283,7 @@ for a file, and returns an IO action producing either an error or a list of code
282
283
provider::CodeLensProvider
283
284
provider _lspFuncs -- LSP functions, not used
284
285
state -- ghcide state, used to retrieve typechecking artifacts
@@ -309,18 +310,18 @@ provider _lspFuncs -- LSP functions, not used
309
310
=return$Right (List[])
310
311
```
311
312
312
-
Note how simple it is to retrieve the type checking artifacts for the module as well as a fully setup Ghc session via the Ghcide rules.
313
+
Note how simple it is to retrieve the type checking artifacts for the module as well as a fully setup GHC session via the `ghcide` rules.
313
314
314
315
The function `extractMinimalImports` extracts the import statements from the AST and generates the minimal import lists, implementing steps 2 and 3 of the algorithm.
315
-
The details of the GHC api are not relevant to this tutorial, but the code is terse and easy to read:
316
+
The details of the GHC API are not relevant to this tutorial, but the code is terse and easy to read:
The function `generateLens` implements the last piece of the algorithm, step 4, producing a code lens for an import statement that lacks an import list. Note how the code lens includes an `ImportCommandParams` value
341
+
The function `generateLens` implements step 4 of the algorithm, producing a code lens for an import statement that lacks an import list. Note how the code lens includes an `ImportCommandParams` value
341
342
that contains a workspace edit that rewrites the import statement, as expected by our command provider.
_command <-Just<$> mkLspCommand pId importCommandId title _arguments
375
-
--create and return the code lens
376
+
--Create and return the code lens
376
377
return$JustCodeLens{..}
377
378
|otherwise
378
379
=returnNothing
379
380
```
380
381
381
382
## Wrapping up
382
383
383
-
There's only one haskell code change left to do at this point: "link" the plugin in the `HlsPlugins` HLS module.
384
-
However integrating the plugin in haskell-language-server itself will need some changes in config files. The best way is looking for the id (f.e. `hls-class-plugin`) of an existing plugin:
385
-
-`./cabal*.project` and `./stack*.yaml`: add the plugin package in the `packages` field
386
-
-`./haskell-language-server.cabal`: add a conditional block with the plugin package dependency
387
-
-`./.github/workflows/test.yml`: add a block to run the test suite of the plugin
388
-
-`./.github/workflows/hackage.yml`: add the plugin to the component list to release the plugin package to hackage
389
-
-`./*.nix`: add the plugin to nix builds
384
+
There's only one Haskell code change left to do at this point: "link" the plugin in the `HlsPlugins` HLS module.
385
+
However integrating the plugin in HLS itself will need some changes in configuration files. The best way is looking for the ID (f.e. `hls-class-plugin`) of an existing plugin:
386
+
-`./cabal*.project` and `./stack*.yaml`: add the plugin package in the `packages` field,
387
+
-`./haskell-language-server.cabal`: add a conditional block with the plugin package dependency,
388
+
-`./.github/workflows/test.yml`: add a block to run the test suite of the plugin,
389
+
-`./.github/workflows/hackage.yml`: add the plugin to the component list to release the plugin package to Hackage,
390
+
-`./*.nix`: add the plugin to Nix builds.
390
391
391
392
The full code as used in this tutorial, including imports, can be found in [this Gist](https://gist.github.com/pepeiborra/49b872b2e9ad112f61a3220cdb7db967) as well as in this [branch](https://github.com/pepeiborra/ide/blob/imports-lens/src/Ide/Plugin/ImportLens.hs)
0 commit comments