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 16 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
29 changes: 27 additions & 2 deletions compiler/noirc_frontend/src/hir/def_collector/dc_crate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,20 @@ use crate::hir::type_check::{type_check_func, TypeCheckError, TypeChecker};
use crate::hir::Context;

use crate::macros_api::{MacroError, MacroProcessor};
use crate::node_interner::{FuncId, GlobalId, NodeInterner, StructId, TraitId, TypeAliasId};
use crate::node_interner::{
DependencyId, FuncId, GlobalId, NodeInterner, StructId, TraitId, TypeAliasId,
};

use crate::parser::{ParserError, SortedModule};
use crate::{
ExpressionKind, Ident, LetStatement, Literal, NoirFunction, NoirStruct, NoirTrait,
NoirTypeAlias, Path, PathKind, Type, TypeBindings, UnresolvedGenerics,
UnresolvedTraitConstraint, UnresolvedType,
};

use fm::FileId;
use iter_extended::vecmap;
use noirc_errors::{CustomDiagnostic, Span};
use noirc_errors::{CustomDiagnostic, Location, Span};
use std::collections::{BTreeMap, HashMap};

use std::vec;
Expand Down Expand Up @@ -268,6 +271,7 @@ impl DefCollector {

// Resolve unresolved imports collected from the crate, one by one.
for collected_import in def_collector.collected_imports {
let module_id = collected_import.module_id;
match resolve_import(crate_id, collected_import, &context.def_maps) {
Ok(resolved_import) => {
// Populate module namespaces according to the imports used
Expand All @@ -278,6 +282,9 @@ impl DefCollector {
let result = current_def_map.modules[resolved_import.module_scope.0]
.import(name.clone(), ns, resolved_import.is_prelude);

let file_id = current_def_map.file_id(module_id);
add_import_reference(ns, &name, &mut context.def_interner, file_id);

if let Err((first_def, second_def)) = result {
let err = DefCollectorErrorKind::Duplicate {
typ: DuplicateType::Import,
Expand Down Expand Up @@ -381,6 +388,24 @@ impl DefCollector {
}
}

fn add_import_reference(
def_id: crate::macros_api::ModuleDefId,
name: &Ident,
interner: &mut NodeInterner,
file_id: FileId,
) {
if name.span() == Span::empty(0) {
// We ignore empty spans at 0 location, this must be Stdlib
return;
}
if let crate::macros_api::ModuleDefId::FunctionId(func_id) = def_id {
interner.add_reference_for(
DependencyId::Function(func_id),
(DependencyId::FunctionCall, Location::new(name.span(), file_id)),
);
}
}

fn inject_prelude(
crate_id: CrateId,
context: &Context,
Expand Down
9 changes: 8 additions & 1 deletion compiler/noirc_frontend/src/hir/resolution/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1417,7 +1417,7 @@ impl<'a> Resolver<'a> {
// Otherwise, then it is referring to an Identifier
// This lookup allows support of such statements: let x = foo::bar::SOME_GLOBAL + 10;
// If the expression is a singular indent, we search the resolver's current scope as normal.
let (hir_ident, var_scope_index) = self.get_ident_from_path(path);
let (hir_ident, var_scope_index) = self.get_ident_from_path(path.clone());
jfecher marked this conversation as resolved.
Show resolved Hide resolved

if hir_ident.id != DefinitionId::dummy_id() {
match self.interner.definition(hir_ident.id).kind {
Expand All @@ -1436,6 +1436,13 @@ impl<'a> Resolver<'a> {
self.interner.function_visibility(id),
);
}

if let Some(func_meta) = self.interner.func_meta.get(&id) {
self.interner.add_reference(
(DependencyId::Function(id), func_meta.location),
(DependencyId::FunctionCall, hir_ident.location),
);
}
jfecher marked this conversation as resolved.
Show resolved Hide resolved
}
DefinitionKind::Global(global_id) => {
if let Some(current_item) = self.current_item {
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
108 changes: 108 additions & 0 deletions compiler/noirc_frontend/src/locations.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
use fm::FileId;
use noirc_errors::Location;
use rangemap::RangeMap;
use rustc_hash::FxHashMap;

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

#[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.graph_references.add_node((reference.0, reference.1));
self.graph_references.add_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 add_reference_for(
&mut self,
referenced_id: DependencyId,
reference: (DependencyId, Location),
) {
let Some(referenced_index) = self.graph_references_indices.get(&referenced_id) else { panic!("Compiler Error: Referenced index not found") };

let reference_index = self.graph_references.add_node((reference.0, reference.1));
self.graph_references.add_edge(*referenced_index, reference_index, ());
self.location_store.add_location(reference.1, reference_index);
}

pub(crate) fn add_definition(&mut self, referenced: (DependencyId, Location)) {
let referenced_index = self.get_or_insert_reference(referenced);
self.location_store.add_location(referenced.1, referenced_index);
}

#[tracing::instrument(skip(self), ret)]
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 reference_node = self.graph_references[node_index];
let found_locations: Vec<Location> = match reference_node.0 {
DependencyId::Alias(_) | DependencyId::Struct(_) | DependencyId::Global(_) => todo!(),
TomAFrench marked this conversation as resolved.
Show resolved Hide resolved
DependencyId::Function(_) => self.get_edit_locations(node_index),

DependencyId::FunctionCall => {
let referenced_node_index = self
.graph_references
.neighbors_directed(node_index, petgraph::Direction::Incoming)
.next()?;

self.get_edit_locations(referenced_node_index)
}
};
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)
.for_each(|reference_node_index| {
let (_reference_dependency_id, reference_location) =
self.graph_references[reference_node_index];
edit_locations.push(reference_location);
});
edit_locations
}
}
24 changes: 21 additions & 3 deletions compiler/noirc_frontend/src/node_interner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ use crate::hir_def::{
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 @@ -60,7 +61,7 @@ pub struct NodeInterner {
function_modules: HashMap<FuncId, ModuleId>,

/// This graph tracks dependencies between different global definitions.
/// This is used to ensure the absense of dependency cycles for globals and types.
/// This is used to ensure the absence of dependency cycles for globals and types.
dependency_graph: DiGraph<DependencyId, ()>,

/// To keep track of where each DependencyId is in `dependency_graph`, we need
Expand Down Expand Up @@ -167,6 +168,13 @@ pub struct NodeInterner {

/// 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 @@ -185,6 +193,7 @@ pub enum DependencyId {
Global(GlobalId),
Function(FuncId),
Alias(TypeAliasId),
FunctionCall,
jfecher marked this conversation as resolved.
Show resolved Hide resolved
}

/// A trait implementation is either a normal implementation that is present in the source
Expand Down Expand Up @@ -512,6 +521,9 @@ impl Default for NodeInterner {
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 @@ -788,6 +800,10 @@ impl NodeInterner {
contract_function_type: Some(if function.is_open { Open } else { Secret }),
is_internal: Some(function.is_internal),
};
self.add_definition((
DependencyId::Function(id),
Location::new(function.name.span(), location.file),
));
self.push_function_definition(id, modifiers, module, location)
}

Expand Down Expand Up @@ -1539,13 +1555,13 @@ impl NodeInterner {
self.add_dependency(dependent, DependencyId::Function(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 @@ -1590,6 +1606,7 @@ impl NodeInterner {
}
// Mutually recursive functions are allowed
DependencyId::Function(_) => (),
_ => (),
jfecher marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Expand All @@ -1611,6 +1628,7 @@ impl NodeInterner {
DependencyId::Global(id) => {
Cow::Borrowed(self.get_global(id).ident.0.contents.as_ref())
}
_ => 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
6 changes: 6 additions & 0 deletions cspell.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
"indexmap",
"injective",
"Inlines",
"Instrumenter",
"interner",
"intrinsics",
"jmp",
Expand All @@ -102,6 +103,7 @@
"lvalue",
"Maddiaa",
"mathbb",
"memfs",
"merkle",
"metas",
"minreq",
Expand All @@ -127,6 +129,7 @@
"nouner",
"pedersen",
"peekable",
"petgraph",
"plonkc",
"PLONKish",
"pprof",
Expand All @@ -136,6 +139,7 @@
"pseudocode",
"pubkey",
"quantile",
"rangemap",
"repr",
"reqwest",
"rfind",
Expand All @@ -157,6 +161,7 @@
"subtyping",
"swcurve",
"Taiko",
"tarjan",
"tecurve",
"tempdir",
"tempfile",
Expand All @@ -174,6 +179,7 @@
"urem",
"USERPROFILE",
"vecmap",
"vitkov",
"wasi",
"wasmer",
"Weierstraß",
Expand Down
Loading
Loading