Skip to content

Commit 5ad6d97

Browse files
autofix-ci[bot]Sysix
authored andcommitted
[autofix.ci] apply automated fixes
1 parent f5f4793 commit 5ad6d97

File tree

8 files changed

+122
-30
lines changed

8 files changed

+122
-30
lines changed

Cargo.lock

Lines changed: 0 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/oxc_language_server/Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ oxc_diagnostics = { workspace = true }
2727
oxc_formatter = { workspace = true }
2828
oxc_linter = { workspace = true, features = ["language_server"] }
2929
oxc_parser = { workspace = true }
30-
oxc_span = { workspace = true }
3130

3231
#
3332
env_logger = { workspace = true, features = ["humantime"] }

crates/oxc_language_server/src/file_system.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ impl LSPFileSystem {
2121
self.files.pin().insert(uri.clone(), content);
2222
}
2323

24-
#[expect(dead_code)] // used for the oxc_formatter in the future
2524
pub fn get(&self, uri: &Uri) -> Option<String> {
2625
self.files.pin().get(uri).cloned()
2726
}
Lines changed: 67 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,69 @@
1-
use serde::{Deserialize, Serialize};
1+
use serde::{Deserialize, Deserializer, Serialize, de::Error};
2+
use serde_json::Value;
23

3-
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
4+
#[derive(Debug, Default, Serialize, Clone)]
45
#[serde(rename_all = "camelCase")]
5-
pub struct FormatOptions;
6+
pub struct FormatOptions {
7+
pub experimental: bool,
8+
}
9+
10+
impl<'de> Deserialize<'de> for FormatOptions {
11+
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
12+
where
13+
D: Deserializer<'de>,
14+
{
15+
let value = Value::deserialize(deserializer)?;
16+
FormatOptions::try_from(value).map_err(Error::custom)
17+
}
18+
}
19+
20+
impl TryFrom<Value> for FormatOptions {
21+
type Error = String;
22+
23+
fn try_from(value: Value) -> Result<Self, Self::Error> {
24+
let Some(object) = value.as_object() else {
25+
return Err("no object passed".to_string());
26+
};
27+
28+
Ok(Self {
29+
experimental: object
30+
.get("fmt.experimental")
31+
.is_some_and(|run| serde_json::from_value::<bool>(run.clone()).unwrap_or_default()),
32+
})
33+
}
34+
}
35+
36+
#[cfg(test)]
37+
mod test {
38+
use serde_json::json;
39+
40+
use super::FormatOptions;
41+
42+
#[test]
43+
fn test_valid_options_json() {
44+
let json = json!({
45+
"fmt.experimental": true,
46+
});
47+
48+
let options = FormatOptions::try_from(json).unwrap();
49+
assert!(options.experimental);
50+
}
51+
52+
#[test]
53+
fn test_empty_options_json() {
54+
let json = json!({});
55+
56+
let options = FormatOptions::try_from(json).unwrap();
57+
assert!(!options.experimental);
58+
}
59+
60+
#[test]
61+
fn test_invalid_options_json() {
62+
let json = json!({
63+
"fmt.experimental": "what", // should be bool
64+
});
65+
66+
let options = FormatOptions::try_from(json).unwrap();
67+
assert!(!options.experimental);
68+
}
69+
}

crates/oxc_language_server/src/formatter/server_formatter.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,14 @@ impl ServerFormatter {
1616
}
1717

1818
#[expect(clippy::unused_self)]
19-
pub fn run_single(&self, uri: &Uri) -> Option<Vec<TextEdit>> {
19+
pub fn run_single(&self, uri: &Uri, content: Option<String>) -> Option<Vec<TextEdit>> {
2020
let path = uri.to_file_path()?;
2121
let source_type = get_supported_source_type(&path)?;
22-
let source_text = std::fs::read_to_string(path).expect("Failed to read file");
22+
let source_text = if let Some(content) = content {
23+
content
24+
} else {
25+
std::fs::read_to_string(&path).ok()?
26+
};
2327

2428
let allocator = Allocator::new();
2529
let ret = Parser::new(&allocator, &source_text, source_type)

crates/oxc_language_server/src/main.rs

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -167,8 +167,6 @@ impl LanguageServer for Backend {
167167
if worker.needs_init_linter().await {
168168
needed_configurations.insert(worker.get_root_uri().clone(), worker);
169169
}
170-
// ToDo: check for configuration
171-
worker.init_formatter().await;
172170
}
173171

174172
if !needed_configurations.is_empty() {
@@ -178,23 +176,21 @@ impl LanguageServer for Backend {
178176
// every worker should be initialized already in `initialize` request
179177
vec![Some(Options::default()); needed_configurations.len()]
180178
};
179+
let default_options = Options::default();
181180

182181
for (index, worker) in needed_configurations.values().enumerate() {
183-
worker
184-
.init_linter(
185-
configurations
186-
.get(index)
187-
.unwrap_or(&None)
188-
.as_ref()
189-
.unwrap_or(&Options::default()),
190-
)
191-
.await;
182+
let configuration =
183+
configurations.get(index).unwrap_or(&None).as_ref().unwrap_or(&default_options);
184+
185+
worker.init_linter(configuration).await;
186+
worker.init_formatter(&configuration.format).await;
192187
}
193188
}
194189

190+
let mut registrations = vec![];
191+
195192
// init all file watchers
196193
if capabilities.dynamic_watchers {
197-
let mut registrations = vec![];
198194
for worker in workers {
199195
registrations.push(Registration {
200196
id: format!("watcher-{}", worker.get_root_uri().as_str()),
@@ -204,10 +200,21 @@ impl LanguageServer for Backend {
204200
})),
205201
});
206202
}
203+
}
207204

208-
if let Err(err) = self.client.register_capability(registrations).await {
209-
warn!("sending registerCapability.didChangeWatchedFiles failed: {err}");
210-
}
205+
if capabilities.dynamic_formatting {
206+
registrations.push(Registration {
207+
id: "dynamic-formatting".to_string(),
208+
method: "textDocument/formatting".to_string(),
209+
register_options: None,
210+
});
211+
}
212+
213+
if registrations.is_empty() {
214+
return;
215+
}
216+
if let Err(err) = self.client.register_capability(registrations).await {
217+
warn!("sending registerCapability.didChangeWatchedFiles failed: {err}");
211218
}
212219
}
213220

@@ -410,11 +417,16 @@ impl LanguageServer for Backend {
410417
)
411418
.await;
412419

420+
let default_options = Options::default();
413421
for (index, folder) in params.event.added.iter().enumerate() {
414422
let worker = WorkspaceWorker::new(folder.uri.clone());
415423
// get the configuration from the response and init the linter
416424
let options = configurations.get(index).unwrap_or(&None);
417-
worker.init_linter(options.as_ref().unwrap_or(&Options::default())).await;
425+
let options = options.as_ref().unwrap_or(&default_options);
426+
427+
worker.init_linter(options).await;
428+
worker.init_formatter(&options.format).await;
429+
418430
added_registrations.push(Registration {
419431
id: format!("watcher-{}", worker.get_root_uri().as_str()),
420432
method: "workspace/didChangeWatchedFiles".to_string(),
@@ -603,7 +615,7 @@ impl LanguageServer for Backend {
603615
let Some(worker) = workers.iter().find(|worker| worker.is_responsible_for_uri(uri)) else {
604616
return Ok(None);
605617
};
606-
Ok(worker.format_file(uri).await)
618+
Ok(worker.format_file(uri, self.file_system.read().await.get(uri)).await)
607619
}
608620
}
609621

crates/oxc_language_server/src/options.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ mod test {
3434
"options": {
3535
"run": true,
3636
"configPath": "./custom.json",
37+
"fmt.experimental": true
3738
}
3839
}]);
3940

@@ -46,5 +47,6 @@ mod test {
4647
assert_eq!(options.lint.run, Run::OnType); // fallback
4748
assert_eq!(options.lint.config_path, Some("./custom.json".into()));
4849
assert!(options.lint.flags.is_empty());
50+
assert!(options.format.experimental);
4951
}
5052
}

crates/oxc_language_server/src/worker.rs

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use crate::{
1616
apply_all_fix_code_action, apply_fix_code_actions, ignore_this_line_code_action,
1717
ignore_this_rule_code_action,
1818
},
19-
formatter::server_formatter::ServerFormatter,
19+
formatter::{options::FormatOptions, server_formatter::ServerFormatter},
2020
linter::{
2121
error_with_position::{DiagnosticReport, PossibleFixContent},
2222
options::LintOptions,
@@ -57,8 +57,11 @@ impl WorkspaceWorker {
5757
*self.server_linter.write().await = Some(ServerLinter::new(&self.root_uri, &options.lint));
5858
}
5959

60-
pub async fn init_formatter(&self) {
61-
*self.server_formatter.write().await = Some(ServerFormatter::new());
60+
pub async fn init_formatter(&self, options: &FormatOptions) {
61+
if options.experimental {
62+
debug!("experimental formatter enabled");
63+
*self.server_formatter.write().await = Some(ServerFormatter::new());
64+
}
6265
}
6366

6467
// WARNING: start all programs (linter, formatter) before calling this function
@@ -156,12 +159,12 @@ impl WorkspaceWorker {
156159
server_linter.run_single(uri, content, run_type).await
157160
}
158161

159-
pub async fn format_file(&self, uri: &Uri) -> Option<Vec<TextEdit>> {
162+
pub async fn format_file(&self, uri: &Uri, content: Option<String>) -> Option<Vec<TextEdit>> {
160163
let Some(server_formatter) = &*self.server_formatter.read().await else {
161164
return None;
162165
};
163166

164-
server_formatter.run_single(uri)
167+
server_formatter.run_single(uri, content)
165168
}
166169

167170
async fn revalidate_diagnostics(
@@ -327,6 +330,16 @@ impl WorkspaceWorker {
327330
*options_guard = changed_options.clone();
328331
}
329332

333+
if current_option.format.experimental != changed_options.format.experimental {
334+
if changed_options.format.experimental {
335+
debug!("experimental formatter enabled");
336+
*self.server_formatter.write().await = Some(ServerFormatter::new());
337+
} else {
338+
debug!("experimental formatter disabled");
339+
*self.server_formatter.write().await = None;
340+
}
341+
}
342+
330343
if Self::needs_linter_restart(&current_option.lint, &changed_options.lint) {
331344
let files = {
332345
let server_linter_guard = self.server_linter.read().await;

0 commit comments

Comments
 (0)