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

Add "generate function" code action #4168

Merged
merged 3 commits into from
Jan 16, 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
28 changes: 28 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,34 @@

### Language server

- The language server can now generate the definition of functions that do not
exist in the current file. For example if I write the following piece of code:

```gleam
import gleam/io

pub type Pokemon {
Pokemon(pokedex_number: Int, name: String)
}

pub fn main() {
io.println(to_string(pokemon))
// ^ If you put your cursor over this function that is
// not implemented yet
}
```

Triggering the "generate function" code action, the language server will
generate the following function for you:

```gleam
fn to_string(pokemon: Pokemon) -> String {
todo
}
```

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

- The language server can now fill in the labels of any function call, even when
only some of the arguments are provided. For example:

Expand Down
146 changes: 145 additions & 1 deletion compiler-core/src/language_server/code_action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use crate::{
build::{Located, Module},
io::{BeamCompiler, CommandExecutor, FileSystemReader, FileSystemWriter},
line_numbers::LineNumbers,
parse::extra::ModuleExtra,
parse::{extra::ModuleExtra, lexer::str_to_keyword},
type_::{
self,
error::{ModuleSuggestion, VariableOrigin},
Expand Down Expand Up @@ -3759,3 +3759,147 @@ fn pretty_constructor_name(
}
}
}

/// Builder for the "generate function" code action.
/// Whenever someone hovers an invalid expression that is inferred to have a
/// function type the language server can generate a function definition for it.
/// For example:
///
/// ```gleam
/// pub fn main() {
/// wibble(1, 2, "hello")
/// // ^ [generate function]
/// }
/// ```
///
/// Will generate the following definition:
///
/// ```gleam
/// pub fn wibble(arg_0: Int, arg_1: Int, arg_2: String) -> a {
/// todo
/// }
/// ```
///
pub struct GenerateFunction<'a> {
module: &'a Module,
params: &'a CodeActionParams,
edits: TextEdits<'a>,
last_visited_function_end: Option<u32>,
function_to_generate: Option<FunctionToGenerate<'a>>,
}

struct FunctionToGenerate<'a> {
name: &'a str,
arguments_types: Vec<Arc<Type>>,
return_type: Arc<Type>,
previous_function_end: Option<u32>,
}

impl<'a> GenerateFunction<'a> {
pub fn new(
module: &'a Module,
line_numbers: &'a LineNumbers,
params: &'a CodeActionParams,
) -> Self {
Self {
module,
params,
edits: TextEdits::new(line_numbers),
last_visited_function_end: None,
function_to_generate: None,
}
}

pub fn code_actions(mut self) -> Vec<CodeAction> {
self.visit_typed_module(&self.module.ast);

let Some(FunctionToGenerate {
name,
arguments_types,
previous_function_end: Some(insert_at),
return_type,
}) = self.function_to_generate
else {
return vec![];
};

let mut printer = Printer::new(&self.module.ast.names);
let args = if let [arg_type] = arguments_types.as_slice() {
let arg_name = arg_type
.named_type_name()
.map(|(_type_module, type_name)| type_name.to_snake_case())
.filter(|name| is_valid_function_name(name))
.unwrap_or(String::from("arg"));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use a real word rather than arg. We don't abbreviate in Gleam.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would you prefer "value" or "argument" or something else entirely?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Value seems fine

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll do it!


format!("{arg_name}: {}", printer.print_type(arg_type))
} else {
arguments_types
.iter()
.enumerate()
.map(|(index, arg_type)| {
let type_ = printer.print_type(arg_type);
format!("arg_{}: {}", index + 1, type_)
})
.join(", ")
};
let return_type = printer.print_type(&return_type);

self.edits.insert(
insert_at,
format!("\n\nfn {name}({args}) -> {return_type} {{\n todo\n}}"),
);

let mut action = Vec::with_capacity(1);
CodeActionBuilder::new("Generate function")
.kind(CodeActionKind::REFACTOR_REWRITE)
.changes(self.params.text_document.uri.clone(), self.edits.edits)
.preferred(false)
.push_to(&mut action);
action
}
}

impl<'ast> ast::visit::Visit<'ast> for GenerateFunction<'ast> {
fn visit_typed_function(&mut self, fun: &'ast ast::TypedFunction) {
self.last_visited_function_end = Some(fun.end_position);
ast::visit::visit_typed_function(self, fun);
}

fn visit_typed_expr_invalid(&mut self, location: &'ast SrcSpan, type_: &'ast Arc<Type>) {
let invalid_range = self.edits.src_span_to_lsp_range(*location);
if within(self.params.range, invalid_range) {
let name_range = location.start as usize..location.end as usize;
let candidate_name = self.module.code.get(name_range);
match (candidate_name, type_.fn_types()) {
(None, _) | (_, None) => return,
(Some(name), _) if !is_valid_function_name(name) => return,
(Some(name), Some((arguments_types, return_type))) => {
self.function_to_generate = Some(FunctionToGenerate {
name,
arguments_types,
return_type,
previous_function_end: self.last_visited_function_end,
})
}
}
}

ast::visit::visit_typed_expr_invalid(self, location, type_);
}
}

#[must_use]
fn is_valid_function_name(name: &str) -> bool {
if !name.starts_with(|char: char| char.is_ascii_lowercase()) {
return false;
}

for char in name.chars() {
let is_valid_char = char.is_ascii_digit() || char.is_ascii_lowercase() || char == '_';
if !is_valid_char {
return false;
}
}

str_to_keyword(name).is_none()
}
5 changes: 3 additions & 2 deletions compiler-core/src/language_server/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ use super::{
code_action_convert_unqualified_constructor_to_qualified, code_action_import_module,
code_action_inexhaustive_let_to_case, AddAnnotations, CodeActionBuilder, DesugarUse,
ExpandFunctionCapture, ExtractVariable, FillInMissingLabelledArgs, GenerateDynamicDecoder,
LabelShorthandSyntax, LetAssertToCase, PatternMatchOnValue, RedundantTupleInCaseSubject,
TurnIntoUse,
GenerateFunction, LabelShorthandSyntax, LetAssertToCase, PatternMatchOnValue,
RedundantTupleInCaseSubject, TurnIntoUse,
},
completer::Completer,
signature_help, src_span_to_lsp_range, DownloadDependencies, MakeLocker,
Expand Down Expand Up @@ -335,6 +335,7 @@ where
actions.extend(TurnIntoUse::new(module, &lines, &params).code_actions());
actions.extend(ExpandFunctionCapture::new(module, &lines, &params).code_actions());
actions.extend(ExtractVariable::new(module, &lines, &params).code_actions());
actions.extend(GenerateFunction::new(module, &lines, &params).code_actions());
actions.extend(
PatternMatchOnValue::new(module, &lines, &params, &this.compiler).code_actions(),
);
Expand Down
56 changes: 56 additions & 0 deletions compiler-core/src/language_server/tests/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ const EXPAND_FUNCTION_CAPTURE: &str = "Expand function capture";
const GENERATE_DYNAMIC_DECODER: &str = "Generate dynamic decoder";
const PATTERN_MATCH_ON_ARGUMENT: &str = "Pattern match on argument";
const PATTERN_MATCH_ON_VARIABLE: &str = "Pattern match on variable";
const GENERATE_FUNCTION: &str = "Generate function";

macro_rules! assert_code_action {
($title:expr, $code:literal, $range:expr $(,)?) => {
Expand Down Expand Up @@ -4689,3 +4690,58 @@ fn map(list: List(a), fun: fn(a) -> b) { todo }
find_position_of("tuple").to_selection()
);
}

#[test]
fn generate_function_works_with_invalid_call() {
assert_code_action!(
GENERATE_FUNCTION,
"
pub fn main() -> Bool {
wibble(1, True, 2.3)
}
",
find_position_of("wibble").to_selection()
);
}

#[test]
fn generate_function_works_with_pipeline_steps() {
assert_code_action!(
GENERATE_FUNCTION,
"
pub fn main() {
[1, 2, 3]
|> sum
|> int_to_string
}

fn int_to_string(n: Int) -> String {
todo
}
",
find_position_of("sum").to_selection()
);
}

#[test]
fn generate_function_works_with_pipeline_steps_1() {
assert_code_action!(
GENERATE_FUNCTION,
"
pub fn main() {
[1, 2, 3]
|> map(int_to_string)
|> join
}

fn map(list: List(a), fun: fn(a) -> b) -> List(b) {
todo
}

fn join(n: List(String)) -> String {
todo
}
",
find_position_of("int_to_string").to_selection()
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
source: compiler-core/src/language_server/tests/action.rs
expression: "\npub fn main() -> Bool {\n wibble(1, True, 2.3)\n}\n"
---
----- BEFORE ACTION

pub fn main() -> Bool {
wibble(1, True, 2.3)
}


----- AFTER ACTION

pub fn main() -> Bool {
wibble(1, True, 2.3)
}

fn wibble(arg_1: Int, arg_2: Bool, arg_3: Float) -> Bool {
todo
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
source: compiler-core/src/language_server/tests/action.rs
expression: "\npub fn main() {\n [1, 2, 3]\n |> sum\n |> int_to_string\n}\n\nfn int_to_string(n: Int) -> String {\n todo\n}\n"
---
----- BEFORE ACTION

pub fn main() {
[1, 2, 3]
|> sum
|> int_to_string
}

fn int_to_string(n: Int) -> String {
todo
}


----- AFTER ACTION

pub fn main() {
[1, 2, 3]
|> sum
|> int_to_string
}

fn sum(list: List(Int)) -> Int {
todo
}

fn int_to_string(n: Int) -> String {
todo
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
source: compiler-core/src/language_server/tests/action.rs
expression: "\npub fn main() {\n [1, 2, 3]\n |> map(int_to_string)\n |> join\n}\n\nfn map(list: List(a), fun: fn(a) -> b) -> List(b) {\n todo\n}\n\nfn join(n: List(String)) -> String {\n todo\n}\n"
---
----- BEFORE ACTION

pub fn main() {
[1, 2, 3]
|> map(int_to_string)
|> join
}

fn map(list: List(a), fun: fn(a) -> b) -> List(b) {
todo
}

fn join(n: List(String)) -> String {
todo
}


----- AFTER ACTION

pub fn main() {
[1, 2, 3]
|> map(int_to_string)
|> join
}

fn int_to_string(int: Int) -> String {
todo
}

fn map(list: List(a), fun: fn(a) -> b) -> List(b) {
todo
}

fn join(n: List(String)) -> String {
todo
}
Loading