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 code action to ignore unused Result value #3255

Closed
wants to merge 1 commit 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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@

([Giacomo Cavalieri](https://github.com/giacomocavalieri))

- Added a code action to add `let _ = ` to an unused result value.
([Leah Ulmschneider](https://github.com/leah-u))

### Bug Fixes

- Fixed a bug where the compiler would output a confusing error message when
Expand Down
97 changes: 97 additions & 0 deletions compiler-core/src/language_server/code_action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -276,3 +276,100 @@ impl<'a> RedundantTupleInCaseSubject<'a> {
}
}
}

/// Code action to add `let _ = ` in front of an unused result value
///
/// # Example:
///
/// ```gleam
/// fn main() {
/// Ok(0)
/// Nil
/// }
/// ```
///
/// Becomes:
///
/// ```gleam
/// fn main() {
/// let _ = Ok(0)
/// Nil
/// }
/// ```
pub struct UnusedResultValue<'a> {
line_numbers: LineNumbers,
params: &'a CodeActionParams,
module: &'a ast::TypedModule,
edit: Option<TextEdit>,
}

impl<'ast> ast::visit::Visit<'ast> for UnusedResultValue<'_> {
fn visit_typed_function(&mut self, fun: &'ast ast::TypedFunction) {
self.visit_statements(&fun.body);
ast::visit::visit_typed_function(self, fun);
}

fn visit_typed_expr_block(
&mut self,
location: &'ast SrcSpan,
statements: &'ast [ast::TypedStatement],
) {
self.visit_statements(statements);
ast::visit::visit_typed_expr_block(self, location, statements);
}
}

impl<'a> UnusedResultValue<'a> {
pub fn new(module: &'a build::Module, params: &'a CodeActionParams) -> Self {
Self {
line_numbers: LineNumbers::new(&module.code),
params,
module: &module.ast,
edit: None,
}
}

pub fn code_actions(mut self) -> Vec<CodeAction> {
self.visit_typed_module(self.module);
let Some(edit) = self.edit else {
return vec![];
};

let mut actions = vec![];
CodeActionBuilder::new("Assign unused Result value to `_`")
.kind(CodeActionKind::QUICKFIX)
.changes(self.params.text_document.uri.clone(), vec![edit])
.preferred(true)
.push_to(&mut actions);

actions
}

fn visit_statements(&mut self, statements: &[ast::TypedStatement]) {
let count = statements.len();
for (i, stmt) in statements.iter().enumerate() {
// Check all statements except the last in the body
if i >= count - 1 {
break;
}

if let ast::Statement::Expression(expr) = stmt {
if expr.type_().is_result() {
let location = expr.location();
let range = src_span_to_lsp_range(location, &self.line_numbers);
if overlaps(self.params.range, range) {
self.edit =
Some(self.assign_discard(SrcSpan::new(location.start, location.start)));
}
}
}
}
}

fn assign_discard(&self, location: SrcSpan) -> TextEdit {
TextEdit {
range: src_span_to_lsp_range(location, &self.line_numbers),
new_text: "let _ = ".to_owned(),
}
}
}
3 changes: 2 additions & 1 deletion compiler-core/src/language_server/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use std::sync::Arc;
use strum::IntoEnumIterator;

use super::{
code_action::{CodeActionBuilder, RedundantTupleInCaseSubject},
code_action::{CodeActionBuilder, RedundantTupleInCaseSubject, UnusedResultValue},
src_span_to_lsp_range, DownloadDependencies, MakeLocker,
};

Expand Down Expand Up @@ -258,6 +258,7 @@ where

code_action_unused_imports(module, &params, &mut actions);
actions.extend(RedundantTupleInCaseSubject::new(module, &params).code_actions());
actions.extend(UnusedResultValue::new(module, &params).code_actions());

Ok(if actions.is_empty() {
None
Expand Down
92 changes: 86 additions & 6 deletions compiler-core/src/language_server/tests/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ fn engine_response(src: &str, line: u32) -> engine::Response<Option<Vec<lsp_type

const REMOVE_UNUSED_IMPORTS_TITLE: &str = "Remove unused imports";
const REMOVE_REDUNDANT_TUPLES: &str = "Remove redundant tuples";
const ASSIGN_UNUSED_RESULT: &str = "Assign unused Result value to `_`";

fn apply_first_code_action_with_title(src: &str, line: u32, title: &str) -> String {
let response = engine_response(src, line)
Expand Down Expand Up @@ -91,13 +92,13 @@ fn apply_code_edit(
panic!("Unknown url {}", change_url)
}
for edit in change {
let start =
line_numbers.byte_index(edit.range.start.line, edit.range.start.character) - offset;
let end =
line_numbers.byte_index(edit.range.end.line, edit.range.end.character) - offset;
let start = line_numbers.byte_index(edit.range.start.line, edit.range.start.character)
as i32
- offset;
let end = line_numbers.byte_index(edit.range.end.line, edit.range.end.character) as i32
- offset;
let range = (start as usize)..(end as usize);
offset += end - start;
offset -= edit.new_text.len() as u32;
offset += end - start - edit.new_text.len() as i32;
lpil marked this conversation as resolved.
Show resolved Hide resolved
result.replace_range(range, &edit.new_text);
}
}
Expand Down Expand Up @@ -177,6 +178,85 @@ pub fn main() {
)
}

#[test]
fn test_assign_unused_result() {
let code = "
pub fn main() {
Ok(0)
Nil
}
";

insta::assert_snapshot!(apply_first_code_action_with_title(
code,
2,
ASSIGN_UNUSED_RESULT
));
}

#[test]
fn test_assign_unused_result_in_block() {
let code = "
pub fn main() {
{
Ok(0)
Nil
}
Nil
}
";

insta::assert_snapshot!(apply_first_code_action_with_title(
code,
3,
ASSIGN_UNUSED_RESULT
));
}

#[test]
fn test_assign_unused_result_only_first_action() {
let code = "
pub fn main() {
Ok(0)
Ok(0)
Nil
}
";

insta::assert_snapshot!(apply_first_code_action_with_title(
code,
2,
ASSIGN_UNUSED_RESULT
));
}

#[test]
#[should_panic(expected = "No code action produced by the engine")]
fn test_assign_unused_result_not_on_return_value() {
let code = "
pub fn main() {
Ok(0)
}
";

let _ = apply_first_code_action_with_title(code, 2, ASSIGN_UNUSED_RESULT);
}

#[test]
#[should_panic(expected = "No code action produced by the engine")]
fn test_assign_unused_result_not_on_return_value_in_block() {
let code = "
pub fn main() {
let _ = {
Ok(0)
}
Nil
}
";

let _ = apply_first_code_action_with_title(code, 3, ASSIGN_UNUSED_RESULT);
}

#[test]
fn test_remove_redundant_tuple_in_case_subject_simple() {
let code = "
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
source: compiler-core/src/language_server/tests/action.rs
expression: "apply_first_code_action_with_title(code, 2, ASSIGN_UNUSED_RESULT)"
---
pub fn main() {
let _ = Ok(0)
Nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
source: compiler-core/src/language_server/tests/action.rs
expression: "apply_first_code_action_with_title(code, 3, ASSIGN_UNUSED_RESULT)"
---
pub fn main() {
{
let _ = Ok(0)
Nil
}
Nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
source: compiler-core/src/language_server/tests/action.rs
expression: "apply_first_code_action_with_title(code, 2, ASSIGN_UNUSED_RESULT)"
---
pub fn main() {
let _ = Ok(0)
Ok(0)
Nil
}
Loading