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

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,30 @@

([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
1 change: 1 addition & 0 deletions 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
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
7 changes: 5 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 @@ -1250,7 +1251,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 +1290,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
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
124 changes: 117 additions & 7 deletions compiler-core/src/language_server/engine.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::{
analyse::name::correct_name_case,
ast::{
CustomType, Definition, ModuleConstant, SrcSpan, TypedArg, TypedExpr, TypedFunction,
TypedModule, TypedPattern,
ArgNames, CustomType, Definition, ModuleConstant, Pattern, SrcSpan, TypedArg, TypedExpr,
TypedFunction, TypedModule, TypedPattern,
},
build::{type_constructor_from_modules, Located, Module, UnqualifiedImport},
config::PackageConfig,
Expand All @@ -13,8 +13,8 @@ use crate::{
line_numbers::LineNumbers,
paths::ProjectPaths,
type_::{
self, printer::Printer, Deprecation, ModuleInterface, Type, TypeConstructor,
ValueConstructorVariant,
self, error::VariableOrigin, printer::Printer, Deprecation, ModuleInterface, Type,
TypeConstructor, ValueConstructor, ValueConstructorVariant,
},
Error, Result, Warning,
};
Expand All @@ -23,8 +23,9 @@ use ecow::EcoString;
use itertools::Itertools;
use lsp::CodeAction;
use lsp_types::{
self as lsp, DocumentSymbol, Hover, HoverContents, MarkedString, Position, Range,
SignatureHelp, SymbolKind, SymbolTag, TextEdit, Url,
self as lsp, DocumentSymbol, Hover, HoverContents, MarkedString, Position,
PrepareRenameResponse, Range, SignatureHelp, SymbolKind, SymbolTag, TextEdit, Url,
WorkspaceEdit,
};
use std::sync::Arc;

Expand All @@ -38,6 +39,7 @@ use super::{
RedundantTupleInCaseSubject, TurnIntoUse,
},
completer::Completer,
rename::{rename_local_variable, VariableRenameKind},
signature_help, src_span_to_lsp_range, DownloadDependencies, MakeLocker,
};

Expand Down Expand Up @@ -494,6 +496,114 @@ where
})
}

pub fn prepare_rename(
&mut self,
params: lsp::TextDocumentPositionParams,
) -> Response<Option<PrepareRenameResponse>> {
self.respond(|this| {
let (_, found) = match this.node_at_position(&params) {
Some(value) => value,
None => return Ok(None),
};

let success_response = Some(PrepareRenameResponse::DefaultBehavior {
default_behavior: true,
});

Ok(match found {
Located::Expression(TypedExpr::Var {
constructor:
ValueConstructor {
variant: ValueConstructorVariant::LocalVariable { origin, .. },
..
},
..
})
| Located::Pattern(Pattern::Variable { origin, .. }) => match origin {
VariableOrigin::Variable(_)
| VariableOrigin::AssignmentPattern
| VariableOrigin::LabelShorthand(_) => success_response,
VariableOrigin::Generated => None,
},
Located::Pattern(Pattern::Assign { .. }) => success_response,
Located::Arg(arg) => match &arg.names {
ArgNames::Named { .. } | ArgNames::NamedLabelled { .. } => success_response,
ArgNames::Discard { .. } | ArgNames::LabelledDiscard { .. } => None,
},
_ => None,
})
})
}

pub fn rename(&mut self, params: lsp::RenameParams) -> Response<Option<WorkspaceEdit>> {
self.respond(|this| {
let position = &params.text_document_position;

let (lines, found) = match this.node_at_position(position) {
Some(value) => value,
None => return Ok(None),
};

let Some(module) = this.module_for_uri(&position.text_document.uri) else {
return Ok(None);
};

Ok(match found {
Located::Expression(TypedExpr::Var {
constructor:
ValueConstructor {
variant: ValueConstructorVariant::LocalVariable { location, origin },
..
},
..
})
| Located::Pattern(Pattern::Variable {
location, origin, ..
}) => match origin {
VariableOrigin::Variable(_) | VariableOrigin::AssignmentPattern => {
rename_local_variable(
module,
&lines,
&params,
*location,
VariableRenameKind::Variable,
)
}
VariableOrigin::LabelShorthand(_) => rename_local_variable(
module,
&lines,
&params,
*location,
VariableRenameKind::LabelShorthand,
),
VariableOrigin::Generated => None,
},
Located::Pattern(Pattern::Assign { location, .. }) => rename_local_variable(
module,
&lines,
&params,
*location,
VariableRenameKind::Variable,
),
Located::Arg(arg) => match &arg.names {
ArgNames::Named { location, .. }
| ArgNames::NamedLabelled {
name_location: location,
..
} => rename_local_variable(
module,
&lines,
&params,
*location,
VariableRenameKind::Variable,
),
ArgNames::Discard { .. } | ArgNames::LabelledDiscard { .. } => None,
},
_ => None,
})
})
}

fn respond<T>(&mut self, handler: impl FnOnce(&mut Self) -> Result<T>) -> Response<T> {
let result = handler(self);
let warnings = self.take_warnings();
Expand Down Expand Up @@ -963,7 +1073,7 @@ fn hover_for_expression(
}

fn hover_for_imported_value(
value: &type_::ValueConstructor,
value: &ValueConstructor,
location: &SrcSpan,
line_numbers: LineNumbers,
hex_module_imported_from: Option<&ModuleInterface>,
Expand Down
Loading
Loading