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

Implement renaming for local variables #4185

Merged
merged 15 commits into from
Jan 20, 2025
Merged
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: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,30 @@
better names using the type of the code it's generating.
([Giacomo Cavalieri](https://github.com/giacomocavalieri))

- The Language Server now provides the ability to rename local variables.
For example:

```gleam
pub fn main() {
let wibble = 10
// ^ If you put your cursor here, and trigger a rename
wibble + 1
}
```

Triggering a rename and entering `my_number` results in this code:


```gleam
pub fn main() {
let my_number = 10
my_number + 1
}
```

([Surya Rose](https://github.com/GearsDatapacks))


### Formatter

### Bug fixes
Expand Down
41 changes: 40 additions & 1 deletion compiler-core/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1524,6 +1524,7 @@ pub enum ClauseGuard<Type, RecordTag> {
location: SrcSpan,
type_: Type,
name: EcoString,
definition_location: SrcSpan,
},

TupleIndex {
Expand Down Expand Up @@ -1950,7 +1951,6 @@ impl TypedPattern {
| Pattern::VarUsage { .. }
| Pattern::Assign { .. }
| Pattern::Discard { .. }
| Pattern::BitArray { .. }
| Pattern::StringPrefix { .. }
| Pattern::Invalid { .. } => Some(Located::Pattern(self)),

Expand All @@ -1972,6 +1972,11 @@ impl TypedPattern {
.or_else(|| tail.as_ref().and_then(|p| p.find_node(byte_index))),

Pattern::Tuple { elems, .. } => elems.iter().find_map(|p| p.find_node(byte_index)),

Pattern::BitArray { segments, .. } => segments
.iter()
.find_map(|segment| segment.find_node(byte_index))
.or(Some(Located::Pattern(self))),
}
.or(Some(Located::Pattern(self)))
}
Expand Down Expand Up @@ -2048,6 +2053,16 @@ impl TypedExprBitArraySegment {
}
}

impl TypedPatternBitArraySegment {
pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> {
self.value.find_node(byte_index).or_else(|| {
self.options
.iter()
.find_map(|option| option.find_node(byte_index))
})
}
}

pub type TypedConstantBitArraySegmentOption = BitArrayOption<TypedConstant>;

#[derive(Debug, PartialEq, Eq, Clone)]
Expand Down Expand Up @@ -2177,6 +2192,30 @@ impl<A> BitArrayOption<A> {
}
}

impl BitArrayOption<TypedPattern> {
pub fn find_node(&self, byte_index: u32) -> Option<Located<'_>> {
match self {
BitArrayOption::Bytes { .. }
| BitArrayOption::Int { .. }
| BitArrayOption::Float { .. }
| BitArrayOption::Bits { .. }
| BitArrayOption::Utf8 { .. }
| BitArrayOption::Utf16 { .. }
| BitArrayOption::Utf32 { .. }
| BitArrayOption::Utf8Codepoint { .. }
| BitArrayOption::Utf16Codepoint { .. }
| BitArrayOption::Utf32Codepoint { .. }
| BitArrayOption::Signed { .. }
| BitArrayOption::Unsigned { .. }
| BitArrayOption::Big { .. }
| BitArrayOption::Little { .. }
| BitArrayOption::Native { .. }
| BitArrayOption::Unit { .. } => None,
BitArrayOption::Size { value, .. } => value.find_node(byte_index),
}
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum TodoKind {
Keyword,
Expand Down
2 changes: 2 additions & 0 deletions compiler-core/src/ast/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use crate::analyse::TargetSupport;
use crate::build::Target;
use crate::config::PackageConfig;
use crate::line_numbers::LineNumbers;
use crate::type_::error::VariableOrigin;
use crate::type_::expression::FunctionDefinition;
use crate::type_::{Deprecation, Problems, PRELUDE_MODULE_NAME};
use crate::warning::WarningEmitter;
Expand Down Expand Up @@ -234,6 +235,7 @@ wibble}"#,
publicity: Publicity::Private,
variant: ValueConstructorVariant::LocalVariable {
location: SrcSpan { start: 5, end: 11 },
origin: VariableOrigin::Variable("wibble".into()),
},
type_: type_::int(),
},
Expand Down
50 changes: 48 additions & 2 deletions compiler-core/src/ast/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,8 +325,9 @@ pub trait Visit<'ast> {
location: &'ast SrcSpan,
name: &'ast EcoString,
type_: &'ast Arc<Type>,
definition_location: &'ast SrcSpan,
) {
visit_typed_clause_guard_var(self, location, name, type_);
visit_typed_clause_guard_var(self, location, name, type_, definition_location);
}

fn visit_typed_clause_guard_tuple_index(
Expand Down Expand Up @@ -485,6 +486,10 @@ pub trait Visit<'ast> {
visit_typed_pattern_bit_array(self, location, segments);
}

fn visit_typed_pattern_bit_array_option(&mut self, option: &'ast BitArrayOption<TypedPattern>) {
visit_typed_pattern_bit_array_option(self, option);
}

fn visit_typed_pattern_string_prefix(
&mut self,
location: &'ast SrcSpan,
Expand Down Expand Up @@ -1250,7 +1255,8 @@ where
location,
type_,
name,
} => v.visit_typed_clause_guard_var(location, name, type_),
definition_location,
} => v.visit_typed_clause_guard_var(location, name, type_, definition_location),
super::ClauseGuard::TupleIndex {
location,
index,
Expand Down Expand Up @@ -1288,6 +1294,7 @@ pub fn visit_typed_clause_guard_var<'a, V>(
_location: &'a SrcSpan,
_name: &'a EcoString,
_type_: &'a Arc<Type>,
_definition_location: &'a SrcSpan,
) where
V: Visit<'a> + ?Sized,
{
Expand Down Expand Up @@ -1579,6 +1586,45 @@ pub fn visit_typed_pattern_bit_array<'a, V>(
{
for segment in segments {
v.visit_typed_pattern(&segment.value);
for option in segment.options.iter() {
v.visit_typed_pattern_bit_array_option(option);
}
}
}

pub fn visit_typed_pattern_bit_array_option<'a, V>(
v: &mut V,
option: &'a BitArrayOption<TypedPattern>,
) where
V: Visit<'a> + ?Sized,
{
match option {
BitArrayOption::Bytes { location: _ } => { /* TODO */ }
BitArrayOption::Int { location: _ } => { /* TODO */ }
BitArrayOption::Float { location: _ } => { /* TODO */ }
BitArrayOption::Bits { location: _ } => { /* TODO */ }
BitArrayOption::Utf8 { location: _ } => { /* TODO */ }
BitArrayOption::Utf16 { location: _ } => { /* TODO */ }
BitArrayOption::Utf32 { location: _ } => { /* TODO */ }
BitArrayOption::Utf8Codepoint { location: _ } => { /* TODO */ }
BitArrayOption::Utf16Codepoint { location: _ } => { /* TODO */ }
BitArrayOption::Utf32Codepoint { location: _ } => { /* TODO */ }
BitArrayOption::Signed { location: _ } => { /* TODO */ }
BitArrayOption::Unsigned { location: _ } => { /* TODO */ }
BitArrayOption::Big { location: _ } => { /* TODO */ }
BitArrayOption::Little { location: _ } => { /* TODO */ }
BitArrayOption::Native { location: _ } => { /* TODO */ }
BitArrayOption::Size {
location: _,
value,
short_form: _,
} => {
v.visit_typed_pattern(value);
}
BitArrayOption::Unit {
location: _,
value: _,
} => { /* TODO */ }
}
}

Expand Down
46 changes: 45 additions & 1 deletion compiler-core/src/language_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ mod feedback;
mod files;
mod messages;
mod progress;
mod rename;
mod router;
mod server;
mod signature_help;
Expand All @@ -21,7 +22,7 @@ use crate::{
paths::ProjectPaths, Result,
};
use camino::Utf8PathBuf;
use lsp_types::{Position, Range, Url};
use lsp_types::{Position, Range, TextEdit, Url};
use std::any::Any;

#[derive(Debug)]
Expand Down Expand Up @@ -49,6 +50,49 @@ pub fn src_span_to_lsp_range(location: SrcSpan, line_numbers: &LineNumbers) -> R
)
}

/// A little wrapper around LineNumbers to make it easier to build text edits.
///
#[derive(Debug)]
pub struct TextEdits<'a> {
line_numbers: &'a LineNumbers,
edits: Vec<TextEdit>,
}

impl<'a> TextEdits<'a> {
pub fn new(line_numbers: &'a LineNumbers) -> Self {
TextEdits {
line_numbers,
edits: vec![],
}
}

pub fn src_span_to_lsp_range(&self, location: SrcSpan) -> Range {
src_span_to_lsp_range(location, self.line_numbers)
}

pub fn replace(&mut self, location: SrcSpan, new_text: String) {
self.edits.push(TextEdit {
range: src_span_to_lsp_range(location, self.line_numbers),
new_text,
})
}

pub fn insert(&mut self, at: u32, new_text: String) {
self.replace(SrcSpan { start: at, end: at }, new_text)
}

pub fn delete(&mut self, location: SrcSpan) {
self.replace(location, "".to_string())
}

fn delete_range(&mut self, range: Range) {
self.edits.push(TextEdit {
range,
new_text: "".into(),
})
}
}

fn path(uri: &Url) -> Utf8PathBuf {
// The to_file_path method is available on these platforms
#[cfg(any(unix, windows, target_os = "redox", target_os = "wasi"))]
Expand Down
44 changes: 1 addition & 43 deletions compiler-core/src/language_server/code_action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use super::{
compiler::LspProjectCompiler,
edits::{add_newlines_after_import, get_import_edit, position_of_first_definition_if_import},
engine::{overlaps, within},
src_span_to_lsp_range,
src_span_to_lsp_range, TextEdits,
};

#[derive(Debug)]
Expand Down Expand Up @@ -80,48 +80,6 @@ impl CodeActionBuilder {
}
}

/// A little wrapper around LineNumbers to make it easier to build text edits.
///
struct TextEdits<'a> {
line_numbers: &'a LineNumbers,
edits: Vec<TextEdit>,
}

impl<'a> TextEdits<'a> {
pub fn new(line_numbers: &'a LineNumbers) -> Self {
TextEdits {
line_numbers,
edits: vec![],
}
}

pub fn src_span_to_lsp_range(&self, location: SrcSpan) -> Range {
src_span_to_lsp_range(location, self.line_numbers)
}

pub fn replace(&mut self, location: SrcSpan, new_text: String) {
self.edits.push(TextEdit {
range: src_span_to_lsp_range(location, self.line_numbers),
new_text,
})
}

pub fn insert(&mut self, at: u32, new_text: String) {
self.replace(SrcSpan { start: at, end: at }, new_text)
}

pub fn delete(&mut self, location: SrcSpan) {
self.replace(location, "".to_string())
}

fn delete_range(&mut self, range: Range) {
self.edits.push(TextEdit {
range,
new_text: "".into(),
})
}
}

/// Code action to remove literal tuples in case subjects, essentially making
/// the elements of the tuples into the case's subjects.
///
Expand Down
Loading
Loading