Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions crates/oxc_language_server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ doctest = false
[dependencies]
oxc_allocator = { workspace = true }
oxc_diagnostics = { workspace = true }
oxc_formatter = { workspace = true }
oxc_linter = { workspace = true, features = ["language_server"] }
oxc_parser = { workspace = true }

#
env_logger = { workspace = true, features = ["humantime"] }
Expand Down
14 changes: 11 additions & 3 deletions crates/oxc_language_server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ These options can be passed with [initialize](#initialize), [workspace/didChange
| `unusedDisableDirectives` | `"allow" \| "warn"` \| "deny"` | `"allow"` | Define how directive comments like `// oxlint-disable-line` should be reported, when no errors would have been reported on that line anyway |
| `typeAware` | `true` \| `false` | `false` | Enables type-aware linting |
| `flags` | `Map<string, string>` | `<empty>` | Special oxc language server flags, currently only one flag key is supported: `disable_nested_config` |
| `fmt.experimental` | `true` \| `false` | `false` | Enables experimental formatting with `oxc_formatter` |

## Supported LSP Specifications from Server

Expand All @@ -45,7 +46,8 @@ The client can pass the workspace options like following:
"tsConfigPath": null,
"unusedDisableDirectives": "allow",
"typeAware": false,
"flags": {}
"flags": {},
"fmt.experimental": false
}
}]
}
Expand Down Expand Up @@ -81,7 +83,8 @@ The client can pass the workspace options like following:
"tsConfigPath": null,
"unusedDisableDirectives": "allow",
"typeAware": false,
"flags": {}
"flags": {},
"fmt.experimental": false
}
}]
}
Expand Down Expand Up @@ -142,6 +145,10 @@ Returns a list of [CodeAction](https://microsoft.github.io/language-server-proto

Returns a [PublishDiagnostic object](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#publishDiagnosticsParams)

#### [textDocument/formatting](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textDocument_formatting)

Returns a list of [TextEdit](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#textEdit)

## Optional LSP Specifications from Client

### Client
Expand Down Expand Up @@ -170,6 +177,7 @@ The client can return a response like:
"tsConfigPath": null,
"unusedDisableDirectives": "allow",
"typeAware": false,
"flags": {}
"flags": {},
"fmt.experimental": false
}]
```
15 changes: 8 additions & 7 deletions crates/oxc_language_server/src/capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,19 @@ impl From<ClientCapabilities> for Capabilities {
watched_files.dynamic_registration.is_some_and(|dynamic| dynamic)
})
});
// TODO: enable it when we support formatting
// let formatting = value.text_document.as_ref().is_some_and(|text_document| {
// text_document.formatting.is_some_and(|formatting| {
// formatting.dynamic_registration.is_some_and(|dynamic| dynamic)
// })
// });
let dynamic_formatting = value.text_document.as_ref().is_some_and(|text_document| {
text_document.formatting.is_some_and(|formatting| {
formatting.dynamic_registration.is_some_and(|dynamic| dynamic)
})
});

Self {
code_action_provider,
workspace_apply_edit,
workspace_execute_command,
workspace_configuration,
dynamic_watchers,
dynamic_formatting: false,
dynamic_formatting,
}
}
}
Expand Down Expand Up @@ -100,6 +99,8 @@ impl From<Capabilities> for ServerCapabilities {
} else {
None
},
// the server supports formatting, but it will tell the client if he enabled the setting
document_formatting_provider: None,
..ServerCapabilities::default()
}
}
Expand Down
1 change: 0 additions & 1 deletion crates/oxc_language_server/src/file_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ impl LSPFileSystem {
self.files.pin().insert(uri.clone(), content);
}

#[expect(dead_code)] // used for the oxc_formatter in the future
pub fn get(&self, uri: &Uri) -> Option<String> {
self.files.pin().get(uri).cloned()
}
Expand Down
1 change: 1 addition & 0 deletions crates/oxc_language_server/src/formatter/mod.rs
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
pub mod options;
pub mod server_formatter;
70 changes: 67 additions & 3 deletions crates/oxc_language_server/src/formatter/options.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,69 @@
use serde::{Deserialize, Serialize};
use serde::{Deserialize, Deserializer, Serialize, de::Error};
use serde_json::Value;

#[derive(Debug, Default, Serialize, Deserialize, Clone)]
#[derive(Debug, Default, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct FormatOptions;
pub struct FormatOptions {
pub experimental: bool,
}

impl<'de> Deserialize<'de> for FormatOptions {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = Value::deserialize(deserializer)?;
FormatOptions::try_from(value).map_err(Error::custom)
}
}

impl TryFrom<Value> for FormatOptions {
type Error = String;

fn try_from(value: Value) -> Result<Self, Self::Error> {
let Some(object) = value.as_object() else {
return Err("no object passed".to_string());
};

Ok(Self {
experimental: object
.get("fmt.experimental")
.is_some_and(|run| serde_json::from_value::<bool>(run.clone()).unwrap_or_default()),
})
}
}

#[cfg(test)]
mod test {
use serde_json::json;

use super::FormatOptions;

#[test]
fn test_valid_options_json() {
let json = json!({
"fmt.experimental": true,
});

let options = FormatOptions::try_from(json).unwrap();
assert!(options.experimental);
}

#[test]
fn test_empty_options_json() {
let json = json!({});

let options = FormatOptions::try_from(json).unwrap();
assert!(!options.experimental);
}

#[test]
fn test_invalid_options_json() {
let json = json!({
"fmt.experimental": "what", // should be bool
});

let options = FormatOptions::try_from(json).unwrap();
assert!(!options.experimental);
}
}
57 changes: 57 additions & 0 deletions crates/oxc_language_server/src/formatter/server_formatter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use oxc_allocator::Allocator;
use oxc_formatter::{FormatOptions, Formatter, get_supported_source_type};
use oxc_parser::{ParseOptions, Parser};
use tower_lsp_server::{
UriExt,
lsp_types::{Position, Range, TextEdit, Uri},
};

use crate::LSP_MAX_INT;

pub struct ServerFormatter;

impl ServerFormatter {
pub fn new() -> Self {
Self {}
}

#[expect(clippy::unused_self)]
pub fn run_single(&self, uri: &Uri, content: Option<String>) -> Option<Vec<TextEdit>> {
let path = uri.to_file_path()?;
let source_type = get_supported_source_type(&path)?;
let source_text = if let Some(content) = content {
content
} else {
std::fs::read_to_string(&path).ok()?
};

let allocator = Allocator::new();
let ret = Parser::new(&allocator, &source_text, source_type)
.with_options(ParseOptions {
parse_regular_expression: false,
// Enable all syntax features
allow_v8_intrinsics: true,
allow_return_outside_function: true,
// `oxc_formatter` expects this to be false
preserve_parens: false,
})
.parse();

if !ret.errors.is_empty() {
return None;
}

let options = FormatOptions::default();
let code = Formatter::new(&allocator, options).build(&ret.program);

// nothing has changed
if code == source_text {
return Some(vec![]);
}

Some(vec![TextEdit::new(
Range::new(Position::new(0, 0), Position::new(LSP_MAX_INT, 0)),
code,
)])
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ use tower_lsp_server::lsp_types::{

use oxc_diagnostics::Severity;

// max range for LSP integer is 2^31 - 1
// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#baseTypes
const LSP_MAX_INT: u32 = 2u32.pow(31) - 1;
use crate::LSP_MAX_INT;

#[derive(Debug, Clone)]
pub struct DiagnosticReport {
Expand Down
Loading
Loading