Skip to content

Commit

Permalink
perf(lsp): optimize formatting minified files (denoland#20829)
Browse files Browse the repository at this point in the history
  • Loading branch information
nayeemrmn committed Oct 9, 2023
1 parent 2167a52 commit 35f028d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 16 deletions.
30 changes: 14 additions & 16 deletions cli/lsp/language_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1651,11 +1651,11 @@ impl Inner {
}

// spawn a blocking task to allow doing other work while this is occurring
let format_result = deno_core::unsync::spawn_blocking({
let text_edits = deno_core::unsync::spawn_blocking({
let fmt_options = self.fmt_options.options.clone();
let document = document.clone();
move || {
match document.maybe_parsed_source() {
let format_result = match document.maybe_parsed_source() {
Some(Ok(parsed_source)) => {
format_parsed_source(&parsed_source, &fmt_options)
}
Expand All @@ -1672,26 +1672,24 @@ impl Inner {
// it's not a js/ts file, so attempt to format its contents
format_file(&file_path, &document.content(), &fmt_options)
}
};
match format_result {
Ok(Some(new_text)) => Some(text::get_edits(
&document.content(),
&new_text,
document.line_index().as_ref(),
)),
Ok(None) => Some(Vec::new()),
Err(err) => {
lsp_warn!("Format error: {:#}", err);
None
}
}
}
})
.await
.unwrap();

let text_edits = match format_result {
Ok(Some(new_text)) => Some(text::get_edits(
&document.content(),
&new_text,
document.line_index().as_ref(),
)),
Ok(None) => Some(Vec::new()),
Err(err) => {
// TODO(lucacasonato): handle error properly
lsp_warn!("Format error: {:#}", err);
None
}
};

self.performance.measure(mark);
if let Some(text_edits) = text_edits {
if text_edits.is_empty() {
Expand Down
12 changes: 12 additions & 0 deletions cli/lsp/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,18 @@ pub fn get_edits(a: &str, b: &str, line_index: &LineIndex) -> Vec<TextEdit> {
if a == b {
return vec![];
}
// Heuristic to detect things like minified files. `diff()` is expensive.
if b.chars().filter(|c| *c == '\n').count()
> line_index.utf8_offsets.len() * 3
{
return vec![TextEdit {
range: lsp::Range {
start: lsp::Position::new(0, 0),
end: line_index.position_utf16(TextSize::from(a.len() as u32)),
},
new_text: b.to_string(),
}];
}
let chunks = diff(a, b);
let mut text_edits = Vec::<TextEdit>::new();
let mut iter = chunks.iter().peekable();
Expand Down

0 comments on commit 35f028d

Please sign in to comment.