Code Monkey home page Code Monkey logo

sway-vscode-plugin's Introduction

Sway VSCode Plugin

Visual Studio Marketplace Version discord

This extension provides LSP support for the Sway smart contract programming language.

Features

  • goto type definition
  • types and documentation on hover
  • inlay hints for types and parameter names
  • semantic syntax highlighting
  • symbol renaming
  • code actions
  • imports insertion

Coming Soon

  • code completion
  • apply suggestions from errors
  • find all references, workspace symbol search
  • ... and many more

Quick start

  1. Install the Fuel toolchain.
  2. Ensure forc-lsp is installed correctly by entering forc-lsp --version into your terminal.
  3. Install the Sway VSCode plugin.

Configuration

This extension provides configurations through VSCode's configuration settings. All configurations are under sway-lsp.*.

sway-vscode-plugin's People

Contributors

adlerjohn avatar alex-matthe avatar alicanc avatar eureka-cpu avatar fuel-bot avatar gr00vytvniks avatar joshuabatty avatar leviathanbeak avatar nfurfaro avatar sdankel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sway-vscode-plugin's Issues

Display the sway build DAG

Add a command palette for showing the workspace build DAG. The graph is generated here. We should display the dotfile contents cleanly in a VSCode sidebar. Just the name of the contract in each bubble will be fine for now.

Add code formatter

Add a canonical code formatter and document how to install/use it. Also add a CI action to check formatting.

Function parameters should be easily distinguishable from those declared inside the function

Summary

It can be seen in the screenshot that the variables defined as parameters are italicised however that does not continue to be the case in the function body.

Perhaps the parameters should also be coloured and have the same formatting in the function body to make it easier to distinguish between

  1. storage usage (once a new release is out that might add colour, #50)
  2. variables defined in the function body
  3. variables passed into the function

Screenshot

1

Support auto-comment

When adding a new line in a comment block, the new line should also be a comment

sway vscode plugin crashes on start up

The sway vscode plugin immediately crashes on startup.

This is probably due to the changes to the LSP feature becoming a plugin instead of a native command: FuelLabs/sway#1178

Error: no such subcommand: `lsp`
[Info  - 4:21:53 PM] Connection to server got closed. Server will restart.
Error: no such subcommand: `lsp`
[Info  - 4:21:53 PM] Connection to server got closed. Server will restart.
Error: no such subcommand: `lsp`
[Info  - 4:21:53 PM] Connection to server got closed. Server will restart.
Error: no such subcommand: `lsp`
[Info  - 4:21:53 PM] Connection to server got closed. Server will restart.
Error: no such subcommand: `lsp`
[Error - 4:21:53 PM] Connection to server got closed. Server will not be restarted.

Error: `A_constructor_cannot_have_a_this_parameter` when running `vsce package`

I tried running vsce package -o sway-vscode-plugin-dev.vsix per the README, and I get this error:

Executing prepublish script 'npm run vscode:prepublish'...

> [email protected] vscode:prepublish /Users/sophiedankel/Development/sway-vscode-plugin
> npm run compile


> [email protected] compile /Users/sophiedankel/Development/sway-vscode-plugin
> tsc -b

/Users/sophiedankel/Development/sway-vscode-plugin/node_modules/typescript/lib/tsc.js:5771
        A_constructor_cannot_have_a_this_parameter: diag(2681, ts.DiagnosticCategory.Error, "A_constructor_cannot_have_a_this_parameter_2681", "A constructor cannot
                                                                                                                                               ^^^^^^^^^^^^^^^^^^^^^

SyntaxError: Invalid or unexpected token
    at wrapSafe (internal/modules/cjs/loader.js:1001:16)
    at Module._compile (internal/modules/cjs/loader.js:1049:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Module.require (internal/modules/cjs/loader.js:974:19)
    at require (internal/modules/cjs/helpers.js:93:18)
    at Object.<anonymous> (/Users/sophiedankel/Development/sway-vscode-plugin/node_modules/typescript/bin/tsc:2:1)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)

Going back to commits from several months ago, I still get this error.

`forc-lsp` is not detected when installed via `fuelup` and the error message needs improvement

Summary

When I start VSCode the first thing that I see is a pop up in the bottom right stating that the LSP has crashed multiple times.
Moreover, checking the "OUTPUT" section I see a bunch of errors indicating that forc has not been found and eventually the server stops attempting to connect.

Checking my toolchain I find that I do have forc and forc-lsp installed under ~/.fuelup/some/path/ however since I use fuelup I no longer have a need for the old ~/.forc directory (which fuelup recommends to remove iirc) and thus my suspicion is that the plugin is looking in the old directory and fails to find whatever it is looking for since it no longer exists.

The error message should be improved and if the the plugin is not looking in the correct place then fuelup should be added for support.

Screenshots

1
2

No license or logo found when running `npm run install-extension`

$ npm run install-extension

> [email protected] install-extension
> vsce package -o sway-vscode-plugin.vsix && code --install-extension sway-vscode-plugin.vsix --force

Executing prepublish script 'npm run vscode:prepublish'...

> [email protected] vscode:prepublish
> npm run compile


> [email protected] compile
> tsc -b

 WARNING  LICENSE.md, LICENSE.txt or LICENSE not found
Do you want to continue? [y/N] y
 ERROR  The specified icon 'extension/images/logo.png' wasn't found in the extension.

New `storage` keyword highlighting applies highlighting when importing modules

Summary

Personally, I'm not a fan of the colour at all but I can try to ignore that - pls change it to be light grey or green or something.
What I cannot ignore is that storage is highlighted in more places than it should be highlighted e.g. when you declare storage for a contract to use.
Specifically, storage being individually highlighted when you import modules from std.
The highlighting applies as you'd expect it when using it in functions.

Screenshot

1

Display if fuel-core is running or not

This could either be in the new side bar introduced in #69, or could be placed down on the bottom status bar.

Perhaps a way of starting and stopping fuel-core in the same location would be good also.

Thoughts on VS Code plugin features / additions

I recently came across this video describing the Truffle for VS Code functionality. There's also a write-up here that goes into a bit more depth.

There are some cool ideas in here that we could get inspiration from. Some things like debugging aren't currently possible although there is an issue open here that is tracking the development.

It seems like the general idea for us though is to offer a UI for allowing developers to still interact with forc but without needing to interact with the command line. One way to do this is by harnessing the command pallet, such as what has been starting in #52. Launching fuel-core and having it appear in the UI is interesting. Also being able to right-click on a script file and have a dialog box appear for running the script is also a cool idea.

I'm sure there are many more cool features we could be looking to add. Just wanted to open an issue so we could start discussing what these could be.

Some errors aren't shown

The following script doesn't show the error in vscode:

script;

fn main() {
    x;
}

Output of forc build:

error
 --> foo/src/main.sw:0:5
  |
...
3 |     x;
  |     ^ Variable "x" does not exist in this scope.
  |
  Aborting due to 1 error.

Some errors _are_shown, so this isn't an issue that no errors are shown at all.

High CPU usage when using LSP, even when idle

At least on Windows, using this VS Code plugin keeps CPU constantly at around 15% usage on my machine. The usage never reduces to near-zero, even when left idle for hours. This is rather undesirable for power-usage reasons and also impacts other workloads on the machine. I'm not actually sure if the issue is on this repo, or FuelLabs/sway LSP code but this seems like the correct place to track this VS Code specific issue.

A screenshot of task manager, with forc.exe under VS code process:

forc.exe under VS code

Details

Tested at commit 85104aa and on the released version of the plugin (v0.2.2).

rustc: 1.60.0 stable
VS Code: 1.67.2
OS: Windows 10 Home, version 10.0.19044
CPU: Intel i7-7700k

Reloading window leaks forc LSP process

When editor window is reloaded, e.g. when enabling new plugins, leaves old LSP processes running. In normal use this rarely causes issues, but when developing the plugin itself it's rather problematic. Especially when combined with #57, it makes developing this plugin quite annoying.

Reprocing

Open a sway file in the editor. Issue with command palette (ctrl-shift-p on Windows): Developer: Reload window. This causes a new forc.exe LSP process to be spawned, as the editor reloads. However, the old process isn't cleaned up and keeps running in the background. This can be seen in task manager. Every new reload leaves one more forc.exe process behind.

Details

Tested at commit 85104aa and on the released version of the plugin (v0.2.2).

rustc: 1.60.0 stable
VS Code: 1.67.2
OS: Windows 10 Home, version 10.0.19044
CPU: Intel i7-7700k

Add a command for showing the syntax tree of the currently open sway file.

Rust-analyzer has a command you can execute from the command palette Rust Analyzer: Show Syntax Tree. It then opens up a separate window in VScode that shows the syntax tree for the currently open file.

syntax tree

It would be really handy if we could add 2 commands to the sway plugin, 1 for showing the parsed ast nodes, and one for showing the typed ast nodes of the current file. I find myself loading various examples and printing out the nodes when trying to inspect the AST of sway files. This feature would help when debugging the language server a lot.

I imagine we could introduce another custom call back similar to the runnables one where the client can request either the parsed or typed ast nodes to be displayed.

Unable to find extension in VSCode

Context

I have decided to use Arch as my daily driver for a new workstation.
After setting up most of the workstation I have opened up VSCode and searched for the extension.

When I search for "sway" or "fuel" I do not find anything recommended related to our plugin.
I have not altered any settings in the editor.
Following the installation instructions here did not work.
Specifically copying ext install FuelLabs.sway-vscode-plugin and while having VSCode selected clicking Ctrl+P and pasting that command in the text box followed by pressing enter.

In order to install the extension I must go to the downloads page for the releases and select one of the .vsix files, in this case it was 0.2.3.
To install the extension you must run the command

code --install-extension /path/to/vsix/file.vsix

More information can be found here.

It can be seen in the screenshots that even after having the extension installed from the file it still does not come up in a search however it does now appear under the "installed" extensions.

In order to reproduce the environment the reader is pointed towards Garuda Linux, specifically the "Garuda KDE Dr460nized" version.
The kernel and release are visibile in the image as well.

Screenshot

3
2
1

Custom types should be highlighted similar to primitive types e.g. `u64`.

Summary

Taking a look at the imports (use...) and the custom types declared as parameter types it can be seen that they are white / not highlighted while the u64 is highlighted.

Add highlights so that the custom types are highlighted in the function (parameter types) and imports.
Perhaps data structures such as struct & enum should be one colour while imported functions should be another colour.

Screenshot

1

`struct` and `enum` keywords are not the correct highlight color

the struct and enum keywords are being incorrectly highlighted. Also, enum variants are highlighted differently depending on if they contain data or not.

I'm using the match_expressions_mismatched example in the sway repo e2e tests folder as an example here. Below you can see how the tokens are highlighted currently in sway.

sway-lsp example

And copying that same example into a new rust project, you can see the correct color highlighting that we should be doing.

rust-analyzer example

related to #59

Revamp the `README.md`

The current information should be moved to a separate .md file for contributing as the information there is not relevant to end users of the language server. The information in this file is what is presented to the user when downloading the extension from the VScode marketplace. As such, we should spruce this up a bit.

Some initial ideas are to have a logo, an overview of the language server. Perhaps even .gif files showing how to access and use each of the supported LSP capabilities.

See this link for a collection of awesome readme files from github projects for inspiration https://github.com/matiassingers/awesome-readme

Add a "run" button on top of `main` function

Rust analyzer has a run & debug button that hovers above the main function. It would be cool to provide a run button and add a debug option when debugging becomes available.

There will have to be some communication with the language server for this to the VS Code plugin, i.e the server needs to determine if the file is a script, if a main function is present, and where in the code the main function is located. Using this information the type script code then knows if it should, and where to place the run button in the editor.

VS Code run

Create a pipeline allowing the client to request custom data from the server

In order to enable #54 to happen, we need to open up a communication channel between the server and the client.

As a small test, I thought we should allow the client to request from the server what kind of file is currently open in the editor, i.e is the open file a script, predicate, library, or contract. I've outlined the steps that need to be taken by both the server and the client below.

Server Side

  1. Scan the current file and store if it is a script, predicate, library or contract
  2. Register a custom method on tower-lsp (see IWANTTOBETHATGUY inlay hints example here)
  3. Create a new data structure for transmitting the data we want to send in JSON-RPC format
  4. Have the custom call back function call into a method in session.rs that reports file type

Client Side

  1. Register a JSON RPC method for calling into our function
  2. Attach that method to an existing LSP callback. i.e didChange (see how rust analyzer does this for an example)
  3. Wait for a response from the server and deserialize the JSON message into a local data structure for storing the data.
  4. Do something useful with the data

Once we have successfully implemented this framework, it should be fairly trivial for the client to request other data such as the location of main and test functions for placing runnable buttons etc.

The Sway Language Server server crashed 5 times in the last 3 minutes

Hey guys!!!
I have run into a problem with the language server, autoformat does not work

My code you can find it here
https://github.com/sway-gang/sway-lend/blob/master/contracts/market/src/main.sw

To open the file you can use these commands

git clone https://github.com/sway-gang/sway-lend
cd sway lend
git checkout
git checkout fe2508784f7dc11e6878dfd83136b81cb52e2701   
code ./contracts/market/src/main.sw

Here is screenshot
image

Sway language server output

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Char index out of bounds: char index 32982, Rope/RopeSlice char length 32749', /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/ropey-1.5.0/src/rope.rs:345:41
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[Info  - 1:54:55 PM] Connection to server got closed. Server will restart.
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Char index out of bounds: char index 32982, Rope/RopeSlice char length 32749', /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/ropey-1.5.0/src/rope.rs:345:41
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[Info  - 1:54:59 PM] Connection to server got closed. Server will restart.
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Char index out of bounds: char index 32982, Rope/RopeSlice char length 32749', /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/ropey-1.5.0/src/rope.rs:345:41
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[Info  - 1:55:30 PM] Connection to server got closed. Server will restart.
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Char index out of bounds: char index 32982, Rope/RopeSlice char length 32749', /Users/runner/.cargo/registry/src/github.com-1ecc6299db9ec823/ropey-1.5.0/src/rope.rs:345:41
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[Info  - 5:39:30 PM] Connection to server got closed. Server will restart.

Sway LSP Client output

INFO [1/4/2023, 7:27:10 PM]: Starting the Sway Language Client and Server
INFO [1/4/2023, 7:27:10 PM]: Extension version: 0.2.7
INFO [1/4/2023, 7:27:10 PM]: Using configuration {
  trace: {
    server: 'off',
    extension: false,
    'fuel-core': { logfile: '/tmp/fuel-core_sway-vscode-plugin.log' }
  },
  debug: { showCollectedTokensAsWarnings: 'off' },
  logging: { level: 'error' },
  inlayHints: { renderColons: true, typeHints: true, maxLength: 25 }
}
INFO [1/4/2023, 7:27:10 PM]: Client has Connected to the Sway Language Server Successfully!
INFO [1/4/2023, 7:27:10 PM]: Starting the Sway Language Client and Server
INFO [1/4/2023, 7:27:10 PM]: Extension version: 0.2.7
INFO [1/4/2023, 7:27:10 PM]: Using configuration {
  trace: {
    server: 'off',
    extension: false,
    'fuel-core': { logfile: '/tmp/fuel-core_sway-vscode-plugin.log' }
  },
  debug: { showCollectedTokensAsWarnings: 'off' },
  logging: { level: 'error' },
  inlayHints: { renderColons: true, typeHints: true, maxLength: 25 }
}

I think perhaps the server is disturbed by the logo, which is located on lines 3-10

Some tokens are taking on incorrect syntax highlighting during editing

@Braqzen noted in Slack that they are noticing some strange syntax highlighting behavior. See image below. I haven't come across this myself but making an issue so we can keep track of it.

Some funky colors after I delete the fee check in the require and then the two line comments above it. After adding them back in for screenshot purposes it did not fix itself as seen in the image. This happens often btw and randomly so I usually ignore it but this is a bit more extreme than usual. Restarting vscode fixes it. plugin v0.2.3

1 (3)

Sway Test Explorer

The app-dev team recently suggested taking a look at the Mocha Test Explorer. It has a side bar showing all of the test functions in the file. You can then run or debug each test using UI elements in the side panel. Would be really cool if we could do something similar.

mocha test

@mitchmindtree mentioned, "In theory something like this should eventually be possible using a combination of the forc-test crate (currently pretty limited) and a future Sway debugger (heavily WIP, currently blocked)."

Replace workspace view implementation with LSP calls

This PR added a sidebar panel with a workspace view, intended to show all sway files and their ABI methods, supporting workspaces with more than one Forc.toml.

The implementation is quite inefficient as it uses readFileSync and contains to naively find and display sway file contents. This should be replaced with calls to the sway LSP server.

An API that returns the following information would be enough to replace what's currently built:

type SwayFileType = 'contract' | 'script' | 'predicate' | 'library';

interface AbiMethod {
  name: string;
}

interface SwayFile {
  path: string;
  type: SwayFileType;
  abiMethods: AbiMethod[];
  isEntrypoint: boolean;
}

interface ForcToml {
  path: string;
  authors: string;
  entry: string;
  name: string; // This is actually the only field that's currently needed
}

interface ForcProject {
  forcToml: ForcToml
  swayFiles: SwayFile[];
}

interface ForcWorkspace {
  members: ForcProject
}

// API
getWorkspace(): ForcWorkspace

In the future we could add to the AbiMethods type, i.e.

interface AbiMethod {
  name: string;
  runnable: boolean;
  argumentTypes: SwayType[];
  returnType: SwayType;
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.