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(lsp): allow function rename #4294

Merged
merged 52 commits into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
52 commits
Select commit Hold shift + click to select a range
f941c04
feat(lsp): allow function rename
kobyhallx Feb 7, 2024
8456a58
Merge remote-tracking branch 'origin/master' into kh-rename-functions
kobyhallx Feb 7, 2024
daf83ed
Merge branch 'master' into kh-rename-functions
kobyhallx Feb 8, 2024
e685934
chore: move collection point
kobyhallx Feb 8, 2024
c9ba252
feat: add func rename with imports
kobyhallx Feb 11, 2024
df38fb6
chore: cleanup
kobyhallx Feb 12, 2024
d73f177
Merge remote-tracking branch 'origin/master' into kh-rename-functions
kobyhallx Feb 12, 2024
3cef0a4
Merge branch 'master' into kh-rename-functions
kobyhallx Feb 12, 2024
39d7d56
chore: remove globals for now
kobyhallx Feb 12, 2024
d77236c
chore: clippy
kobyhallx Feb 12, 2024
2d124bd
chore: clippy - unnecesary ret
kobyhallx Feb 12, 2024
09e898f
chore: clippy - map instead and_then
kobyhallx Feb 12, 2024
78913ac
Merge branch 'master' into kh-rename-functions
kobyhallx Feb 12, 2024
9718234
Merge branch 'master' into kh-rename-functions
kobyhallx Feb 12, 2024
ab455b1
chore: review nits
kobyhallx Feb 12, 2024
d7cd372
chore: spells
kobyhallx Feb 12, 2024
4421a2d
chore: name change
kobyhallx Feb 13, 2024
d564ac8
chore: name change
kobyhallx Feb 13, 2024
f0b81a2
Fix bug with renaming imported functions from submodules
jfecher Feb 13, 2024
0b0eca7
Add unreachable cases
jfecher Feb 13, 2024
7cb7bc7
Merge branch 'master' into kh-rename-functions
jfecher Feb 13, 2024
33b50dc
Fix merge
jfecher Feb 13, 2024
7280c9d
Merge branch 'master' into kh-rename-functions
jfecher Feb 22, 2024
0802086
clippy
jfecher Feb 22, 2024
8122dc8
Merge branch 'kh-rename-functions' of https://github.com/noir-lang/no…
jfecher Feb 22, 2024
a9b785c
Fmt and clippy
jfecher Feb 22, 2024
62c5cad
Merge branch 'master' into kh-rename-functions
TomAFrench Feb 22, 2024
a34e4db
Merge branch 'master' into kh-rename-functions
TomAFrench Jun 25, 2024
d598adf
chore: fix merge
TomAFrench Jun 25, 2024
9d5577c
Merge branch 'master' into kh-rename-functions
asterite Jun 27, 2024
7724b01
Add tests for lsp rename, and use the legacy resolver to make them work
asterite Jun 27, 2024
d18e0a9
Implement lsp rename using elaborator
asterite Jun 27, 2024
52ce934
Check that matches actually match the name being renamed
asterite Jun 27, 2024
4db9e6c
Use separate programs for lsp tests
asterite Jun 27, 2024
aee04c7
clippy
asterite Jun 27, 2024
58bc455
Merge branch 'master' into kh-rename-functions
asterite Jun 27, 2024
2d89ab4
Merge branch 'master' into kh-rename-functions
asterite Jun 27, 2024
2d92617
Undo changes to resolver
asterite Jun 27, 2024
a2fc465
Don't use legacy resolver in another place either
asterite Jun 27, 2024
8b5aaae
Skip empty location spans (otherwise they produce a panic)
asterite Jun 27, 2024
33a695c
Merge branch 'master' into kh-rename-functions
asterite Jun 27, 2024
4da3335
Remove some code duplication in lsp rename tests
asterite Jun 28, 2024
b9f3d76
Extract test_utils::init_lsp_server
asterite Jun 28, 2024
bf87231
process_rename_request only needs TextDocumentPositionParams
asterite Jun 28, 2024
07b2ccb
chore: refactor tests to make it easier to check all cases
TomAFrench Jun 28, 2024
b8dbd04
chore: fix type
TomAFrench Jun 28, 2024
684389a
chore: fmt
TomAFrench Jun 28, 2024
7a2f0f7
chore: add instance of qualified path to test program
TomAFrench Jun 28, 2024
7532717
Let lsp rename function work well with qualified paths
asterite Jun 28, 2024
303dc9b
Remove extra tests, and move consts inside functions
asterite Jun 28, 2024
641c74f
Merge branch 'master' into kh-rename-functions
asterite Jun 28, 2024
777bbbf
Merge branch 'master' into kh-rename-functions
TomAFrench Jul 2, 2024
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
7 changes: 7 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions compiler/noirc_frontend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ small-ord-set = "0.1.3"
regex = "1.9.1"
tracing.workspace = true
petgraph = "0.6"
rangemap = "1.4.0"

[dev-dependencies]
strum = "0.24"
Expand Down
30 changes: 26 additions & 4 deletions compiler/noirc_frontend/src/hir/resolution/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ use crate::graph::CrateId;
use crate::hir::def_map::{LocalModuleId, ModuleDefId, TryFromModuleDefId, MAIN_FUNCTION};
use crate::hir_def::stmt::{HirAssignStatement, HirForStatement, HirLValue, HirPattern};
use crate::node_interner::{
DefinitionId, DefinitionKind, ExprId, FuncId, NodeInterner, StmtId, StructId, TraitId,
TraitImplId, TraitMethodId,
DefinitionId, DefinitionKind, DependencyId, ExprId, FuncId, NodeInterner, StmtId, StructId,
TraitId, TraitImplId, TraitMethodId,
};
use crate::{
hir::{def_map::CrateDefMap, resolution::path_resolver::PathResolver},
Expand Down Expand Up @@ -1409,6 +1409,8 @@ impl<'a> Resolver<'a> {
!= FunctionVisibility::Public
{
let span = hir_ident.location.span;
let func_def = self.interner.function_modifiers(&id);
tracing::debug!("Func definition: {:?}", (id, span, func_def));
self.check_can_reference_function(
id,
span,
Expand Down Expand Up @@ -1463,10 +1465,30 @@ impl<'a> Resolver<'a> {
}
ExpressionKind::Call(call_expr) => {
// Get the span and name of path for error reporting
let func = self.resolve_expression(*call_expr.func);
let func = self.resolve_expression(*call_expr.clone().func);

let arguments = vecmap(call_expr.arguments, |arg| self.resolve_expression(arg));
let arguments =
vecmap(call_expr.clone().arguments, |arg| self.resolve_expression(arg));
let location = Location::new(expr.span, self.file);

if let ExpressionKind::Variable(path) = call_expr.clone().func.kind {
let (hir_ident, _var_scope_index) = self.get_ident_from_path(path);
if hir_ident.id != DefinitionId::dummy_id() {
if let DefinitionKind::Function(func_def_id) =
self.interner.definition(hir_ident.id).kind
{
if let Some(func_meta) = self.interner.func_meta.get(&func_def_id) {
self.interner.add_reference(
(DependencyId::Function(func_def_id), func_meta.location),
(
DependencyId::CallExpression(func),
Location::new(call_expr.func.span, self.file),
kobyhallx marked this conversation as resolved.
Show resolved Hide resolved
),
);
}
}
}
}
HirExpression::Call(HirCallExpression { func, arguments, location })
}
ExpressionKind::MethodCall(call_expr) => {
Expand Down
1 change: 1 addition & 0 deletions compiler/noirc_frontend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pub mod ast;
pub mod debug;
pub mod graph;
pub mod lexer;
pub mod locations;
pub mod monomorphization;
pub mod node_interner;
pub mod parser;
Expand Down
98 changes: 98 additions & 0 deletions compiler/noirc_frontend/src/locations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
use fm::FileId;
use noirc_errors::Location;
use rangemap::RangeMap;

Check warning on line 3 in compiler/noirc_frontend/src/locations.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (rangemap)
use rustc_hash::FxHashMap;

use crate::{macros_api::NodeInterner, node_interner::DependencyId};
use petgraph::prelude::NodeIndex as PetGraphIndex;

Check warning on line 7 in compiler/noirc_frontend/src/locations.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (petgraph)

#[derive(Debug, Default)]
pub(crate) struct LocationStore {
map_file_to_range: FxHashMap<FileId, RangeMap<u32, PetGraphIndex>>,
}

impl LocationStore {
pub(crate) fn add_location(&mut self, location: Location, node_index: PetGraphIndex) {
let range_map = self.map_file_to_range.entry(location.file).or_insert_with(RangeMap::new);
range_map.insert(location.span.start()..location.span.end(), node_index);
}

pub(crate) fn get_node_from_location(&self, location: Location) -> Option<PetGraphIndex> {
let range_map = self.map_file_to_range.get(&location.file)?;
Some(*range_map.get(&location.span.start())?)
}
}

impl NodeInterner {
pub(crate) fn add_reference(
&mut self,
referenced: (DependencyId, Location),
reference: (DependencyId, Location),
) {
let referenced_index = self.get_or_insert_reference(referenced);
let reference_index = self.get_or_insert_reference(reference);
self.graph_references.update_edge(referenced_index, reference_index, ());
self.location_store.add_location(referenced.1, referenced_index);
self.location_store.add_location(reference.1, reference_index);
}

pub(crate) fn get_or_insert_reference(
&mut self,
(id, location): (DependencyId, Location),
) -> PetGraphIndex {
if let Some(index) = self.graph_references_indices.get(&id) {
return *index;
}

let index = self.graph_references.add_node((id, location));
self.graph_references_indices.insert(id, index);
index
}

pub fn check_rename_possible(&self, location: Location) -> bool {
self.location_store.get_node_from_location(location).is_some()
}

pub fn find_rename_symbols_at(&self, location: Location) -> Option<Vec<Location>> {
let node_index = self.location_store.get_node_from_location(location)?;

let mut edit_locations: Vec<Location> = Vec::new();

let reference_node = self.graph_references[node_index];
let found_locations = match reference_node.0 {
DependencyId::Struct(_) => todo!(),
DependencyId::Global(_) => todo!(),
DependencyId::Function(_) => {
edit_locations.extend(self.get_edit_locations(node_index));
edit_locations
}
DependencyId::Alias(_) => todo!(),
DependencyId::CallExpression(_) => {
if let Some(referenced_node_index) = self
.graph_references
.neighbors_directed(node_index, petgraph::Direction::Incoming)

Check warning on line 73 in compiler/noirc_frontend/src/locations.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (petgraph)
.next()
{
edit_locations.extend(self.get_edit_locations(referenced_node_index));
}
edit_locations
}
};
Some(found_locations)
}

fn get_edit_locations(&self, referenced_node_index: PetGraphIndex) -> Vec<Location> {
let mut edit_locations: Vec<Location> = Vec::new();
let (_referenced_id, referencing_location) = self.graph_references[referenced_node_index];
edit_locations.push(referencing_location);
jfecher marked this conversation as resolved.
Show resolved Hide resolved

self.graph_references
.neighbors_directed(referenced_node_index, petgraph::Direction::Outgoing)

Check warning on line 90 in compiler/noirc_frontend/src/locations.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (petgraph)
.for_each(|reference_node_index| {
let (_reference_dependency_id, reference_location) =
self.graph_references[reference_node_index];
edit_locations.push(reference_location);
});
edit_locations
}
}
18 changes: 16 additions & 2 deletions compiler/noirc_frontend/src/node_interner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
use fm::FileId;
use iter_extended::vecmap;
use noirc_errors::{Location, Span, Spanned};
use petgraph::algo::tarjan_scc;

Check warning on line 8 in compiler/noirc_frontend/src/node_interner.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (petgraph)

Check warning on line 8 in compiler/noirc_frontend/src/node_interner.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (tarjan)
use petgraph::prelude::DiGraph;

Check warning on line 9 in compiler/noirc_frontend/src/node_interner.rs

View workflow job for this annotation

GitHub Actions / Code

Unknown word (petgraph)
use petgraph::prelude::NodeIndex as PetGraphIndex;

use crate::ast::Ident;
Expand All @@ -25,6 +25,7 @@
function::{FuncMeta, HirFunction},
stmt::HirStatement,
};
use crate::locations::LocationStore;
use crate::token::{Attributes, SecondaryAttribute};
use crate::{
BinaryOpKind, ContractFunctionType, FunctionDefinition, FunctionVisibility, Generics, Shared,
Expand Down Expand Up @@ -164,6 +165,13 @@

/// Stores the [Location] of a [Type] reference
pub(crate) type_ref_locations: Vec<(Type, Location)>,

/// Store the location of the references in the graph
pub(crate) graph_references: DiGraph<(DependencyId, Location), ()>,
/// Tracks the index of the references in the graph
pub(crate) graph_references_indices: HashMap<DependencyId, PetGraphIndex>,
kobyhallx marked this conversation as resolved.
Show resolved Hide resolved
/// Store the location of the references in the graph
pub(crate) location_store: LocationStore,
jfecher marked this conversation as resolved.
Show resolved Hide resolved
}

/// A dependency in the dependency graph may be a type or a definition.
Expand All @@ -182,6 +190,7 @@
Global(StmtId),
Function(FuncId),
Alias(TypeAliasId),
CallExpression(ExprId),
}

/// A trait implementation is either a normal implementation that is present in the source
Expand Down Expand Up @@ -494,6 +503,9 @@
primitive_methods: HashMap::new(),
type_alias_ref: Vec::new(),
type_ref_locations: Vec::new(),
location_store: LocationStore::default(),
graph_references: petgraph::graph::DiGraph::new(),
graph_references_indices: HashMap::new(),
};

// An empty block expression is used often, we add this into the `node` on startup
Expand Down Expand Up @@ -1464,13 +1476,13 @@
self.add_dependency(DependencyId::Struct(dependent), DependencyId::Global(dependency));
}

fn add_dependency(&mut self, dependent: DependencyId, dependency: DependencyId) {
pub(crate) fn add_dependency(&mut self, dependent: DependencyId, dependency: DependencyId) {
let dependent_index = self.get_or_insert_dependency(dependent);
let dependency_index = self.get_or_insert_dependency(dependency);
self.dependency_graph.update_edge(dependent_index, dependency_index, ());
}

fn get_or_insert_dependency(&mut self, id: DependencyId) -> PetGraphIndex {
pub(crate) fn get_or_insert_dependency(&mut self, id: DependencyId) -> PetGraphIndex {
if let Some(index) = self.dependency_graph_indices.get(&id) {
return *index;
}
Expand Down Expand Up @@ -1520,6 +1532,7 @@
}
// Mutually recursive functions are allowed
DependencyId::Function(_) => (),
_ => (),
jfecher marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Expand Down Expand Up @@ -1547,6 +1560,7 @@
};
Cow::Owned(self.pattern_name_and_location(&let_stmt.pattern).0)
}
_ => Cow::Borrowed(""),
jfecher marked this conversation as resolved.
Show resolved Hide resolved
};

let mut cycle = index_to_string(scc[start_index]).to_string();
Expand Down
11 changes: 8 additions & 3 deletions tooling/lsp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ use async_lsp::{
};
use fm::{codespan_files as files, FileManager};
use fxhash::FxHashSet;
use lsp_types::CodeLens;
use lsp_types::{
request::{PrepareRenameRequest, Rename},
CodeLens,
};
use nargo::{
package::{Package, PackageType},
parse_all,
Expand All @@ -43,8 +46,8 @@ use notifications::{
};
use requests::{
on_code_lens_request, on_formatting, on_goto_declaration_request, on_goto_definition_request,
on_goto_type_definition_request, on_initialize, on_profile_run_request, on_shutdown,
on_test_run_request, on_tests_request,
on_goto_type_definition_request, on_initialize, on_prepare_rename_request,
on_profile_run_request, on_rename_request, on_shutdown, on_test_run_request, on_tests_request,
};
use serde_json::Value as JsonValue;
use thiserror::Error;
Expand Down Expand Up @@ -113,6 +116,8 @@ impl NargoLspService {
.request::<request::GotoDefinition, _>(on_goto_definition_request)
.request::<request::GotoDeclaration, _>(on_goto_declaration_request)
.request::<request::GotoTypeDefinition, _>(on_goto_type_definition_request)
.request::<PrepareRenameRequest, _>(on_prepare_rename_request)
.request::<Rename, _>(on_rename_request)
.notification::<notification::Initialized>(on_initialized)
.notification::<notification::DidChangeConfiguration>(on_did_change_configuration)
.notification::<notification::DidOpenTextDocument>(on_did_open_text_document)
Expand Down
12 changes: 10 additions & 2 deletions tooling/lsp/src/requests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use async_lsp::ResponseError;
use fm::codespan_files::Error;
use lsp_types::{
DeclarationCapability, Location, Position, TextDocumentSyncCapability, TextDocumentSyncKind,
TypeDefinitionProviderCapability, Url,
TypeDefinitionProviderCapability, Url, WorkDoneProgressOptions,
};
use nargo_fmt::Config;
use serde::{Deserialize, Serialize};
Expand All @@ -29,14 +29,16 @@ mod code_lens_request;
mod goto_declaration;
mod goto_definition;
mod profile_run;
mod rename;
mod test_run;
mod tests;

pub(crate) use {
code_lens_request::collect_lenses_for_package, code_lens_request::on_code_lens_request,
goto_declaration::on_goto_declaration_request, goto_definition::on_goto_definition_request,
goto_definition::on_goto_type_definition_request, profile_run::on_profile_run_request,
test_run::on_test_run_request, tests::on_tests_request,
rename::on_prepare_rename_request, rename::on_rename_request, test_run::on_test_run_request,
tests::on_tests_request,
};

/// LSP client will send initialization request after the server has started.
Expand Down Expand Up @@ -106,6 +108,12 @@ pub(crate) fn on_initialize(
definition_provider: Some(lsp_types::OneOf::Left(true)),
declaration_provider: Some(DeclarationCapability::Simple(true)),
type_definition_provider: Some(TypeDefinitionProviderCapability::Simple(true)),
rename_provider: Some(lsp_types::OneOf::Right(lsp_types::RenameOptions {
prepare_provider: Some(true),
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
})),
},
server_info: None,
})
Expand Down
Loading
Loading