Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: faster LSP #6045

Closed
wants to merge 3 commits into from
Closed
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
24 changes: 17 additions & 7 deletions tooling/lsp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use nargo::{
use nargo_toml::{find_file_manifest, resolve_workspace_from_toml, PackageSelection};
use noirc_driver::{file_manager_with_stdlib, prepare_crate, NOIR_ARTIFACT_VERSION_STRING};
use noirc_frontend::{
graph::{CrateId, CrateName},
graph::{CrateGraph, CrateId, CrateName},
hir::{
def_map::{parse_file, CrateDefMap},
Context, FunctionNameMatch, ParsedFiles,
Expand Down Expand Up @@ -92,15 +92,26 @@ pub struct LspState {
open_documents_count: usize,
input_files: HashMap<String, String>,
cached_lenses: HashMap<String, Vec<CodeLens>>,
cached_definitions: HashMap<PathBuf, NodeInterner>,
cached_parsed_files: HashMap<PathBuf, (usize, (ParsedModule, Vec<ParserError>))>,
cached_def_maps: HashMap<PathBuf, BTreeMap<CrateId, CrateDefMap>>,
workspace_cache: HashMap<PathBuf, WorkspaceCacheData>,
package_cache: HashMap<PathBuf, PackageCacheData>,
options: LspInitializationOptions,

// Tracks files that currently have errors, by package root.
files_with_errors: HashMap<PathBuf, HashSet<Url>>,
}

struct WorkspaceCacheData {
file_manager: FileManager,
}

struct PackageCacheData {
crate_id: CrateId,
crate_graph: CrateGraph,
node_interner: NodeInterner,
def_maps: BTreeMap<CrateId, CrateDefMap>,
}

impl LspState {
fn new(
client: &ClientSocket,
Expand All @@ -112,12 +123,11 @@ impl LspState {
solver: WrapperSolver(Box::new(solver)),
input_files: HashMap::new(),
cached_lenses: HashMap::new(),
cached_definitions: HashMap::new(),
open_documents_count: 0,
cached_parsed_files: HashMap::new(),
cached_def_maps: HashMap::new(),
workspace_cache: HashMap::new(),
package_cache: HashMap::new(),
open_documents_count: 0,
options: Default::default(),

files_with_errors: HashMap::new(),
}
}
Expand Down
126 changes: 116 additions & 10 deletions tooling/lsp/src/notifications/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,18 @@ use std::collections::HashSet;
use std::ops::ControlFlow;
use std::path::PathBuf;

use crate::insert_all_files_for_workspace_into_file_manager;
use crate::{
insert_all_files_for_workspace_into_file_manager, PackageCacheData, WorkspaceCacheData,
};
use async_lsp::{ErrorCode, LanguageClient, ResponseError};
use fm::{FileManager, FileMap};
use fm::{FileId, FileManager, FileMap};
use fxhash::FxHashMap as HashMap;
use lsp_types::{DiagnosticTag, Url};
use noirc_driver::check_crate;
use noirc_errors::{DiagnosticKind, FileDiagnostic};
use noirc_frontend::ast::{NoirFunction, NoirTraitImpl, TraitImplItemKind, TypeImpl};
use noirc_frontend::parser::ItemKind;
use noirc_frontend::ParsedModule;

use crate::types::{
notification, Diagnostic, DiagnosticSeverity, DidChangeConfigurationParams,
Expand Down Expand Up @@ -43,8 +48,14 @@ pub(crate) fn on_did_open_text_document(

let document_uri = params.text_document.uri;
let output_diagnostics = true;
let only_check_open_files = false;

match process_workspace_for_noir_document(state, document_uri, output_diagnostics) {
match process_workspace_for_noir_document(
state,
document_uri,
output_diagnostics,
only_check_open_files,
) {
Ok(_) => {
state.open_documents_count += 1;
ControlFlow::Continue(())
Expand All @@ -62,8 +73,14 @@ pub(super) fn on_did_change_text_document(

let document_uri = params.text_document.uri;
let output_diagnostics = false;
let only_check_open_files = true;

match process_workspace_for_noir_document(state, document_uri, output_diagnostics) {
match process_workspace_for_noir_document(
state,
document_uri,
output_diagnostics,
only_check_open_files,
) {
Ok(_) => ControlFlow::Continue(()),
Err(err) => ControlFlow::Break(Err(err)),
}
Expand All @@ -79,13 +96,20 @@ pub(super) fn on_did_close_text_document(
state.open_documents_count -= 1;

if state.open_documents_count == 0 {
state.cached_definitions.clear();
state.package_cache.clear();
state.workspace_cache.clear();
}

let document_uri = params.text_document.uri;
let output_diagnostics = false;
let only_check_open_files = false;

match process_workspace_for_noir_document(state, document_uri, output_diagnostics) {
match process_workspace_for_noir_document(
state,
document_uri,
output_diagnostics,
only_check_open_files,
) {
Ok(_) => ControlFlow::Continue(()),
Err(err) => ControlFlow::Break(Err(err)),
}
Expand All @@ -97,8 +121,14 @@ pub(super) fn on_did_save_text_document(
) -> ControlFlow<Result<(), async_lsp::Error>> {
let document_uri = params.text_document.uri;
let output_diagnostics = true;
let only_check_open_files = false;

match process_workspace_for_noir_document(state, document_uri, output_diagnostics) {
match process_workspace_for_noir_document(
state,
document_uri,
output_diagnostics,
only_check_open_files,
) {
Ok(_) => ControlFlow::Continue(()),
Err(err) => ControlFlow::Break(Err(err)),
}
Expand All @@ -111,6 +141,7 @@ pub(crate) fn process_workspace_for_noir_document(
state: &mut LspState,
document_uri: Url,
output_diagnostics: bool,
only_check_open_files: bool,
) -> Result<(), async_lsp::Error> {
let file_path = document_uri.to_file_path().map_err(|_| {
ResponseError::new(ErrorCode::REQUEST_FAILED, "URI is not a valid file path")
Expand All @@ -128,7 +159,28 @@ pub(crate) fn process_workspace_for_noir_document(
&mut workspace_file_manager,
);

let parsed_files = parse_diff(&workspace_file_manager, state);
let mut parsed_files = parse_diff(&workspace_file_manager, state);

// If we only want to check the currently open files, we empty function bodies of files that aren't open.
// These function bodies will error, but we are not interested in those errors (we don't report errors in this
// case). The function types are correct, though, because the types in the signature remain unchanged.
// Doing this greatly speeds up the time it takes to reanalyze a crate after incremental edits without saving
// (type-checking body functions is much slower than emptying them)
if only_check_open_files {
let mut currently_open_files: HashSet<FileId> = HashSet::new();
for filename in state.input_files.keys() {
let filename = filename.strip_prefix("file://").unwrap();
if let Some(file_id) = workspace_file_manager.name_to_id(PathBuf::from(filename)) {
currently_open_files.insert(file_id);
}
}

for (file_id, (parsed_module, _errors)) in parsed_files.iter_mut() {
if !currently_open_files.is_empty() && !currently_open_files.contains(file_id) {
empty_parsed_module_function_bodies(parsed_module);
}
}
};

for package in workspace.into_iter() {
let (mut context, crate_id) =
Expand All @@ -154,9 +206,17 @@ pub(crate) fn process_workspace_for_noir_document(
package,
Some(&file_path),
);

state.cached_lenses.insert(document_uri.to_string(), collected_lenses);
state.cached_definitions.insert(package.root_dir.clone(), context.def_interner);
state.cached_def_maps.insert(package.root_dir.clone(), context.def_maps);
state.package_cache.insert(
package.root_dir.clone(),
PackageCacheData {
crate_id,
crate_graph: context.crate_graph,
node_interner: context.def_interner,
def_maps: context.def_maps,
},
);

let fm = &context.file_manager;
let files = fm.as_file_map();
Expand All @@ -166,6 +226,11 @@ pub(crate) fn process_workspace_for_noir_document(
}
}

state.workspace_cache.insert(
workspace.root_dir.clone(),
WorkspaceCacheData { file_manager: workspace_file_manager },
);

Ok(())
}

Expand Down Expand Up @@ -256,6 +321,47 @@ pub(super) fn on_exit(
ControlFlow::Continue(())
}

fn empty_parsed_module_function_bodies(parsed_module: &mut ParsedModule) {
for item in &mut parsed_module.items {
match &mut item.kind {
ItemKind::Function(noir_function) => empty_noir_function_body(noir_function),
ItemKind::TraitImpl(noir_trait_impl) => {
empty_noir_trait_impl_function_bodies(noir_trait_impl);
}
ItemKind::Impl(noir_impl) => empty_noir_impl_function_bodies(noir_impl),
ItemKind::Submodules(parsed_sub_module) => {
empty_parsed_module_function_bodies(&mut parsed_sub_module.contents);
}
ItemKind::Import(_, _)
| ItemKind::Struct(_)
| ItemKind::Trait(_)
| ItemKind::TypeAlias(_)
| ItemKind::Global(_)
| ItemKind::ModuleDecl(_)
| ItemKind::InnerAttribute(_) => (),
}
}
}

fn empty_noir_trait_impl_function_bodies(noir_trait_impl: &mut NoirTraitImpl) {
for item in &mut noir_trait_impl.items {
match &mut item.item.kind {
TraitImplItemKind::Function(noir_function) => empty_noir_function_body(noir_function),
TraitImplItemKind::Constant(..) | TraitImplItemKind::Type { .. } => (),
}
}
}

fn empty_noir_impl_function_bodies(noir_impl: &mut TypeImpl) {
for (noir_function, _span) in &mut noir_impl.methods {
empty_noir_function_body(&mut noir_function.item);
}
}

fn empty_noir_function_body(noir_function: &mut NoirFunction) {
noir_function.def.body.statements.clear();
}

#[cfg(test)]
mod notification_tests {
use crate::test_utils;
Expand Down
Loading
Loading