Skip to content

Guidance on adding my own refactoring functionality #2969

Closed

Description

@venkatd

Is your feature request related to a problem? Please describe.

I find myself doing some things repeatedly like wrapping/unwrapping widgets, reordering them, or extracting widgets to separate files. I'd like to first experiment with my own workflow, then contribute the successful experiments back to dart-code, but my sense is that there's a learning curve to messing with the language server.

Describe the solution you'd like
I'd like to implement a refactoring to extract functions/classes into separate files. My current workflow is:

  • Cut/paste the widget/function and all imports into a new file
  • Add an import reference to the new file
  • Run organize imports on the original file to remove unused references
  • Run organize imports on the new file to remove unused references

I'd like to be able to highlight a group of classes/functions/etc and hit a button "extract to file", type the name of the file and it does all this for me.

There's the question of what to do with shared dependencies between the original and new file but I can deal with that situation after the easy case.

Describe alternatives you've considered
I was thinking of implementing my own vscode extension that uses hacky string processing to accomplish this but wasn't sure if this would end up causing me more headache.

Activity

  1. added
    is enhancement
    on Nov 29, 2020
  2. DanTup commented on Nov 30, 2020

    @DanTup
    Member

    You're right that all of the refactors like this are handled in the Dart analysis server. Dart-Code doesn't do any language parsing itself, so it doesn't have the necessary information to do this reliably in the extension code itself (which would be the same as trying to do it in your own extension - as you suspected).

    I think the best way for this to be implemented would be in a quick-fix ("code action"), however I don't think that would be able to do this:

    I'd like to be able to highlight a group of classes/functions/etc and hit a button "extract to file", type the name of the file and it does all this for me.

    Right now, code actions can only accept a single range, not multiple. To support multiple selections may require changes to the LSP specification/clients.

    There are two ways to contribute code actions to the server - in the server code itself, or as a plugin. Which is best may depend on how general the fix is. @bwilkerson may have thoughts on the best direction for something like this (though it sounds like it may be the same/a superset of dart-lang/sdk#38374).

  3. added and removed
    is enhancement
    on Nov 30, 2020
  4. bwilkerson commented on Nov 30, 2020

    @bwilkerson

    I'd like to be able to highlight a group of classes/functions/etc and hit a button "extract to file", type the name of the file and it does all this for me.

    The other thing that code actions, as implemented in the Dart language server, don't support is querying for additional information. There would be no way to prompt the user for the name of the file, which is why we haven't yet implemented this as a code action. Unfortunately, reworking the Dart language server's support for code actions to allow them to prompt the user for information would likely be a fairly significant task because right now it does all of the work of determining whether the action is feasible and computing the edits in a single step. It would need to split that into two steps so that the prompting could be done only if the action is selected by the user.

    So while I don't think it's currently possible to support this in the Dart language server, doing it as a separate plugin without analysis would likely produce poor results and is unlikely to be done in a way that would make it easy to integrate into the language server (which I would very much like to see happen). I wish I had a better answer.

    There's the question of what to do with shared dependencies between the original and new file but I can deal with that situation after the easy case.

    I'm not sure what you mean by "shared dependencies", but if you're thinking about updating references to the widget/function, then yes, that would also need to be done.

    ... though it sounds like it may be the same/a superset of dart-lang/sdk#38374.

    Other than the possible requirement of selecting multiple widgets/functions in a single operation, yes, it sounds like the same thing, though I'd recommend moving one declaration at a time (such as a widget class) and allowing the specified file to be an existing file, because I think it would be more useful.

  5. venkatd commented on Nov 30, 2020

    @venkatd
    Author

    Thanks for the thorough explanation. I agree one file at a time would make more sense.

    One idea for later: make it easier to create refactoring plugins. Maybe in the form of dart packages.

    Something like:

    class ExtractClassCodeAction implements DartCodeAction {
        Iterable<EditOperation> perform(EditScope scope) {
          // access scope to query the info you need (deps to the class, their files, imports in current file, etc)
          // return edit operations to perform the refactor
        }
    }

    This way, I as a Flutter dev could easily write my own refactors without needing to learn too much about the dart analyzer internals. I think it'd open up a way for the community to experiment with automating many mechanical actions. For example

    • Organize constructors & instance variables in a class
    • Make everything in the file without no external dependencies private
    • Generate a test for the selected class

    ... and so on

  6. bwilkerson commented on Dec 1, 2020

    @bwilkerson

    ... make it easier to create refactoring plugins.

    We would love to do that.

    Unfortunately there's a technical issue that we haven't yet figured out how to work around that prevents it from being as easy as we'd like. Specifically, a running Dart application (such as the language server) can only dynamically load and run other Dart code in an isolate, and that Dart code has to be a full application with a main method that can communicate with the invoking isolate via the isolate protocols. The isolate protocols don't support passing complex objects between the isolates, so the code you want to write would need to be able to (re-)analyze the same code that the server has already analyzed and be ready to respond to requests from the client.

    We have support for plugins of that form. It's provided in the analyzer_plugin package, which provides most of the wrapper code described above and allows plugin authors to focus on writing the pieces they're trying to contribute. But it still isn't trivial to write a plugin, so we don't encourage it's use.

    If you have ideas for how to make it easier for authors like yourself to contribute code actions or other language server enhancements, we'd love to hear them.

    However, I will note that even if we could find a non-isolate-based solution, it isn't clear that we should be running arbitrary code that we don't control in the same process as the language server because it could potentially damage the user experience. For example, consider a user-contributed piece of code that contained an infinite loop. Using isolates helps protect the language server from bugs in plugins because it's able to respond even if the plugins don't.

  7. venkatd commented on Dec 2, 2020

    @venkatd
    Author

    Ah yes I'm seeing them here: https://github.com/dart-lang/sdk/tree/master/pkg/analysis_server/lib/src/services/refactoring

    These are all rough ideas right now. I'd have to think more about them to see if they even make sense.

    One idea would be to allow the plugin to query the information it need and serialize it to json to send over the isolate. Though I suppose this might add more complexity/boilerplate and increase the performance overhead. If, GraphQL style, a plugin could query all necessary info in one request, hopefully it could help reduce the need for round trips. GraphQL itself would be overkill but perhaps a protocol that allows requesting all info necessary.

    With regards slowing down the language server, perhaps constraints could be put on these plugins. For example, some sort of time budget for the "this action is possible" query and a reduced api surface such as only being able to return a config for, say, what types of classes/functions/types a refactor applies to.

    And while I think the initial prompt is performance critical, I would be OK with waiting for the code action itself to be long running (ex waiting for it to rewrite 40 dependencies).

    In terms of an API, perhaps something that mirrors code builder (https://github.com/dart-lang/code_builder) could make modifying the AST easier?

  8. bwilkerson commented on Dec 2, 2020

    @bwilkerson

    Ah yes I'm seeing them here: https://github.com/dart-lang/sdk/tree/master/pkg/analysis_server/lib/src/services/refactoring

    Just to be clear: The analysis server makes a distinction between refactoring, which require user interaction, and code actions, which don't. And the code actions are actually referred to as "quick fixes", following the Eclipse nomenclature that was prevalent when it was first implemented. So you'll find the implementation of code actions in https://github.com/dart-lang/sdk/tree/master/pkg/analysis_server/lib/src/services/correction/dart.

    One idea would be to allow the plugin to query the information it need and serialize it to json to send over the isolate.

    We also thought about that possibility. Our expectation was that the amount of data being transferred would cause performance issues, but I don't believe that we ever implemented that approach, so we don't have any data to support that assumption.

    With regards slowing down the language server, perhaps constraints could be put on these plugins.

    Those are in place. Time critical operations, such as code completion, will wait a limited amount of time for a plugin to respond and will return the results it has if the time limit is reached before all of the plugins have completed. I think the server is fairly well protected as a result of plugin code being run in an isolate. The concern I was expressing was purely a hypothetical one.

    For example, some sort of time budget for the "this action is possible" query ...

    I don't think that code actions work that way in LSP (with a two part "tell me what actions are available", "tell me what to do in response to the user selecting this action" division), but I know that they aren't implemented that way in the analysis server. You have to be able to provide a complete set of edits up front in order for an action to be presented to the user.

    In terms of an API, perhaps something that mirrors code builder ... could make modifying the AST easier?

    Almost everyone assumes that the best way to edit code is by modifying an AST, but that turns out not to be true. While you want to understand the code by looking at a resolved AST, it's actually easier and faster to just compose a set of text edits when modifying the code than it is to update an AST and have the edits computed for you.

  9. venkatd commented on Dec 3, 2020

    @venkatd
    Author

    Just to be clear: The analysis server makes a distinction between refactoring, which require user interaction, and code actions, which don't. And the code actions are actually referred to as "quick fixes", following the Eclipse nomenclature that was prevalent when it was first implemented. So you'll find the implementation of code actions in https://github.com/dart-lang/sdk/tree/master/pkg/analysis_server/lib/src/services/correction/dart.

    Didn't realize. In that case, my personal motivation is much more on refactoring over code actions.

    Those are in place. Time critical operations, such as code completion, will wait a limited amount of time for a plugin to respond and will return the results it has if the time limit is reached before all of the plugins have completed. I think the server is fairly well protected as a result of plugin code being run in an isolate. The concern I was expressing was purely a hypothetical one.

    Oh great! If the scope is just refactoring, are the perf considerations less serious?

    I don't think that code actions work that way in LSP (with a two part "tell me what actions are available", "tell me what to do in response to the user selecting this action" division), but I know that they aren't implemented that way in the analysis server. You have to be able to provide a complete set of edits up front in order for an action to be presented to the user.

    This is for the code actions and refactors? Are refactors done in two steps?

    Almost everyone assumes that the best way to edit code is by modifying an AST, but that turns out not to be true. While you want to understand the code by looking at a resolved AST, it's actually easier and faster to just compose a set of text edits when modifying the code than it is to update an AST and have the edits computed for you.

    Could you clarify? Do you mean the AST is useful for querying the data, but when you finally want to make any edits, you're better off returning a set of replacements (i.e., start, end, replacementText)

  10. bwilkerson commented on Dec 3, 2020

    @bwilkerson

    If the scope is just refactoring, are the perf considerations less serious?

    Yes. The primary performance issue with code actions is that we have to be able to provide a list of code actions before the user has a chance to look at them, otherwise they don't show up, and the code actions need to have the edits to be applied delivered at the same time.

    You have to be able to provide a complete set of edits up front in order for an action to be presented to the user.

    This is for the code actions and refactors?

    That comment was specific to code actions.

    Are refactors done in two steps?

    The Dart analysis server supports two protocols: the original protocol that we had developed before LSP was published and LSP. The answer to this question is different in the two protocols, but I suspect that you're only interested in the answer for LSP, so that's the answer I'll give.

    To the best of my knowledge (Danny can correct me if I'm wrong here), LSP only supports one refactoring (rename) and doesn't even provide the support we'd need to prompt the user for information in order to implement other refactorings as commands. So, I don't believe that it's possible for an LSP server to contribute refactorings at this time.

    Do you mean the AST is useful for querying the data, but when you finally want to make any edits, you're better off returning a set of replacements (i.e., start, end, replacementText)

    The protocol only allows the server to return a set of edits to the client, so that's a hard requirement. The question is how those edits are to be computed. Many people assume that we would modify the AST and then compare the result to the original AST in order to generate the edits, but it turns out that it's both easier to implement and faster to execute to just compose the edits directly rather than to go through an AST editing phase.

  11. venkatd commented on Dec 7, 2020

    @venkatd
    Author

    Makes sense, thanks!

    I've got some refactoring options related to extracting local vars, extracting methods, and some Flutter specific ones. Are those implemented outside of the LSP?

  12. DanTup commented on Dec 7, 2020

    @DanTup
    Member

    To the best of my knowledge (Danny can correct me if I'm wrong here), LSP only supports one refactoring (rename) and doesn't even provide the support we'd need to prompt the user for information in order to implement other refactorings as commands. So, I don't believe that it's possible for an LSP server to contribute refactorings at this time.

    Yep, pretty much. We do have Extract Method and Extract Widget too, though they're slightly compromised because of these restrictions.

    Rename is a first-class feature in LSP, so that one works fairly well as the client implements the interaction for prompting for a name and such.

    For Extract Widget and Extract Method, you may notice that when using LSP they always use the names newMethod and NewWidget and leave it for you to rename manually - that's because we're unable to ask for a name, or automatically invoke the rename feature after modifying the code.

    The only other way to provide (interactive) refactors is to have custom code in the client and then call commands from the server to interact with the user. However this would require all LSP clients to implement that command/interactivity so with some small exceptions (like Flutter Outline) it's generally best to avoid them and stick within the LSP message set.

    I've got some refactoring options related to extracting local vars, extracting methods, and some Flutter specific ones

    The non-extract ones (eg. extract local vars) don't need any interactivity and so they're implemented as simple code actions in the server, and not refactors.

  13. venkatd commented on Dec 8, 2020

    @venkatd
    Author

    I did some further research on this issue and ran into this. It might be familiar to you :)
    microsoft/language-server-protocol#642

    That's a frustrating limitation of LSP. It sounds like either we'd have to implement the custom logic outside of LSP (so we'd have logic duplicated for IntelliJ/vscode) or live with the current situation. That seems to defeat the purpose of LSP for this use case.

  14. DanTup commented on Dec 8, 2020

    @DanTup
    Member

    ran into this. It might be familiar to you :)

    Indeed 😄

    That one is really a fallback I'd prefer not to use though. We could already work around it if a Dart LSP client is going to implement custom commands by having them also include a list of them in the initializationOptions. As you say, this would require custom work in each editor which is what LSP is trying to avoid (I've recently been removing custom methods where an LSP-spec'd alternative has become available).

    The best option is definitely to try and have LSP extended to support what's required. There's an open issue at microsoft/language-server-protocol#724 about supporting snippets in edits applied by code actions that could solve some of these (for example when extracting a method we could have linked placeholders that let you type the name after inserting).

  15. venkatd commented on Dec 8, 2020

    @venkatd
    Author

    From my limited viewpoint, it feels the options from best to worst are:

    1. There's a standard LSP protocol that the language can conform to
    2. A non-standard LSP API (no standard to follow, but at least each implementer can keep their logic in the LSP service instead of duplicating the logic in every editor)
    3. The client implements it (jetbrains, vsc, sublime, etc, basically the madness before LSP)

    The VSC team could gradually standardize features so popular things in category (2) could make their way into category (1). Then the implementers could replace their custom implementations with standards where possible. Because implementers would have less code to maintain, I imagine they'd have a strong incentive to migrate to LSP standards as they are released.

    Unfortunately it feels like the current perspective is to push things to category (3) :(

    What would be the most relevant LSP issue to participate in?

  16. DanTup commented on Dec 9, 2020

    @DanTup
    Member

    What would be the most relevant LSP issue to participate in?

    This depends a little on the specifics of what you want to do. Using your example from above (move some selecting of code to another file), assuming selecting everything in a single selection is reasonable then I think what's missing is some way to have a code action that could ask the user for a filename (either as a command initiated by the server, or as part of the code action data that the client can collect before invoking the code action's command - perhaps by including well-defined command variables in the args?).

    I would probably start by opening an issue in the LSP repo specifically about supporting this to start a discussion. As far as I can tell, there aren't any existing similar issues. The LSP devs may have some ideas on the best way to achieve something like this (eg. whether it should be a first-class LSP feature, or something more generic that can be used by many actions - the experience of the first could be better (for example supporting multiple selections more easily), but the latter could be more flexible).

    That doesn't answer the questions about how best to implement the Dart server side of this - although if the request is specifically dart-lang/sdk#38374, then it may be something that makes sense natively in the server without plugins - that's something Brian may have an opinion on.

  17. bwilkerson commented on Dec 9, 2020

    @bwilkerson

    ... then it may be something that makes sense natively in the server without plugins ...

    Of course I have an opinion :-)

    Being able to reorganize code is a general purpose utility that would benefit everyone, so I'd very much like to see it implemented in the analysis server. We just need a protocol that allows us to interact with the user or, better yet, specify how the client should interact with the user.

    Ideally I'd like to see them add general refactoring support that would allow servers to specify, for each refactoring, a set of parameters that users need to provide, where each parameter would include enough information for the client to build an appropriate UI. For example, being able to specify a description of the parameter ("Move to file") and the type of data being collected (file path). There are several useful refactorings that require more than a single piece of data, and it would be nice if clients could present a single dialog to collect everything all at once.

  18. venkatd commented on Dec 9, 2020

    @venkatd
    Author

    I agree that ideally the language server handles this. A schema of the inputs to start would be great.

    I suppose it could be left up to the client how to collect this info, kind of like a frontend-backend separation where the backend doesn't care how the args were collected as long it's all there.

    For example, if the first argument is a class, selecting it via right click vs. autocomplete search should be irrelevant to the LSP and would allow editors to experiment with different UIs for the same operation.

    My largest pain point is the inability to restructure code. Things such as:

    • Extracting things into separate files
    • Moving files to different directories and renaming them

    As our codebase grows, we manage complexity by breaking things into subsystems organized into files and folders. We don't redraw these boundaries as often as we'd like to because of the friction.

  19. bwilkerson commented on Dec 9, 2020

    @bwilkerson

    I share your pain. Copy/paste is a horrid UX; we should have much better support in this day and age. Hopefully we'll be able to provide that better support soon.

  20. DanTup commented on Dec 9, 2020

    @DanTup
    Member

    @bwilkerson

    Ideally I'd like to see them add general refactoring support that would allow servers to specify, for each refactoring, a set of parameters that users need to provide, where each parameter would include enough information for the client to build an appropriate UI

    Yeah, this makes sense to me, although I do think editors can provide a better experience for the common refactors by implementing them specially (for example the rename refactor).

    I've opened microsoft/language-server-protocol#1164 as somewhere to have a discussion about this and see what the opinions are there.

    @venkatd

    My largest pain point is the inability to restructure code. Things such as:

    • Extracting things into separate files
    • Moving files to different directories and renaming them

    I think these are both fairly common requests. The first one would be less of an issue if we could bring imports with copy/paste - something the Dart server does support, but unfortunately neither VS Code nor LSP do.

    The latter should get a little easier with https://dart-review.googlesource.com/c/sdk/+/175485, though initially it only supports single file moves/renames.

  21. added this to the Backlog milestone on Aug 24, 2021
  22. pattobrien commented on Dec 20, 2022

    @pattobrien

    @DanTup would the functionality discussed in this comment be available to packages that extend analyzer_plugin as well? i.e. would plugins be able to create their own Refactorings that depend on user input? I can supply some of my use cases if necessary.

  23. DanTup commented on Dec 21, 2022

    @DanTup
    Member

    @pattobrien this isn't currently possible and I don't know if it's planned, but if you have some concrete use cases in mind, that might be useful information if this is considered (fyi @bwilkerson).

  24. bwilkerson commented on Dec 21, 2022

    @bwilkerson

    It isn't currently planned, but if we decide to support plugins we would definitely consider this use case.

  25. DanTup commented on Aug 4, 2025

    @DanTup
    Member

    I'm just tidying up the issue tracker. This issue is a little old and a fair bit has changed since. There are more refactors available via Dart-Code, and many of them are no longer coded specifically into here but instead driven by the server.

    There's also work ongoing for a new plugin system in the server (see dart-lang/sdk#53402).

    If there are refactors that are missing (and don't already have issues), we should file new issues in dart-lang/sdk. And similarly, if there is functionality desired for plugins that isn't available in the new system (and don't have existing issues), we should file them in dart-lang/sdk too.

    Thanks!

  26. removed this from the Backlog milestone on Aug 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions