ISSUE DESCRIPTION Extract function extracts too much When triggering Extract function…
- User
ISSUE DESCRIPTION
Extract function extracts too much When triggering
Extract functionwith the selection:/// prepare an empty gleam project in the `target_path` /// fn prepare_project_structure( target_path target: TargetPath, user_id user_id: uuid.Uuid, ) -> Result(Nil, SubmitError) { // get the priv dir use priv <- result.try( application.priv_directory("gleeps") |> result.replace_error(FailedToFindPrivDirectory), ) // copy the base project to the target_path use _ <- result.try( simplifile.copy_directory(filepath.join(priv, "base_project"), target.path) |> result.replace_error(FailedToCopyBaseProject), ) // replace $PROJECT_NAME placeholder in the gleam.toml // <-------------------------------------------------------------- selected from here let toml_path = target.path |> filepath.join("gleam.toml") use gleam_toml <- result.try( toml_path |> simplifile.read |> result.replace_error(FailedToReadGleamToml), ) let gleam_toml = gleam_toml |> string.replace("$PROJECT_NAME", with: user_id_to_string(user_id)) simplifile.write(toml_path, gleam_toml) |> result.replace_error(FailedToWriteGleamToml) // <---------------------------------------------------------------- to here }It will extract the entire function content into a new function leaving:
fn prepare_project_structure( target_path target: TargetPath, user_id user_id: uuid.Uuid, ) -> Result(Nil, SubmitError) { function(target, user_id) }instead of the expected:
/// prepare an empty gleam project in the `target_path` /// fn prepare_project_structure( target_path target: TargetPath, user_id user_id: uuid.Uuid, ) -> Result(Nil, SubmitError) { // get the priv dir use priv <- result.try( application.priv_directory("gleeps") |> result.replace_error(FailedToFindPrivDirectory), ) // copy the base project to the target_path use _ <- result.try( simplifile.copy_directory(filepath.join(priv, "base_project"), target.path) |> result.replace_error(FailedToCopyBaseProject), ) // replace $PROJECT_NAME placeholder in the gleam.toml function(target, user_id) } fn function( target: TargetPath, user_id: uuid.Uuid, ) -> Result(Nil, SubmitError) { let toml_path = target.path |> filepath.join("gleam.toml") use gleam_toml <- result.try( toml_path |> simplifile.read |> result.replace_error(FailedToReadGleamToml), ) let gleam_toml = gleam_toml |> string.replace("$PROJECT_NAME", with: user_id_to_string(user_id)) simplifile.write(toml_path, gleam_toml) |> result.replace_error(FailedToWriteGleamToml) }Using gleam
1.16.0in neovim nightlyInterface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work. For example, if you made a mistake and want to revert your changes, you can use
git checkout <file>to restore the file to its original state. You can also reset all changes in the repository usinggit reset --hardcommand. Additionally, you can usegit stashandgit stash popto temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you callsubmit) usinggit statusorgit diffcommands. However you don't need to usegit addorgit commitbefore submitting your changes. In fact,submitonly submits currently unstaged changes because it usesgit diffto get the changes that need to be submitted.CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
- If an error was reported in the issue description, I have successfully reproduced it.
- If an error was reported in the issue description, I have confirmed that my fix resolves the error.
- I have thought about edge cases and made sure my fix handles them as well.
- I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass. I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /gleam, current file: none) bash-$
- Assistant
I'll start by exploring the repository to understand the codebase and locate relevant files for the "Extract function" feature. First, let's see what's in the current directory.
- Assistant
The issue is about "Extract function" which is an LSP/code action. Let me search for the relevant code.
- Assistant
Let me look at the code_action.rs file which is likely where the extract function feature is implemented.
- Assistant
The issue is about "Extract function" code action. Let me search for "extract_function" or similar.
- Assistant
Let me look at the ExtractFunction struct and its implementation to understand how it determines the range of statements to extract.
- Assistant
Let me understand the issue better. The problem is that when extracting a function, it's extracting too much content - it's extracting the entire function body instead of just the selected statements.
Let me look at how the extraction determines which statements to include.
- Assistant
Let me continue reading the implementation to understand how statements are extracted.
- Assistant
Let me look at the visitor implementation to understand how it determines what to extract, particularly how it determines the boundaries of the selection.
- Assistant
Now I need to look at the visitor implementation, specifically
visit_typed_statement, which is where statements are visited and the selection range is checked. - Assistant
Now I'm starting to understand the structure. The issue is about extracting function with a selection that spans multiple statements. Let me look at the
can_extract_statementmethod and how statements are tracked. The key issue is that when a selection starts after some statements and ends before the last statement, the entire function body is being extracted instead of just the selected statements.Let me look more at the visitor code:
- Assistant
Let me understand the problem better. The issue is that when selecting multiple statements within a function, the
Extract functionaction extracts the entire function content instead of just the selected portion.Let me look at the
can_extract_statementmethod and how statements are tracked when they're part of a function body. - Assistant
Let me look at the
can_extract_statementmethod and thevisit_typed_functionmethod more closely. - Assistant
Let me look at the
withinandoverlapshelper functions. - Assistant
Let me search more broadly.
- Assistant
Let me look at the
withinandoverlapshelper functions. - Assistant
Now let me look at how the code edits are generated. Let me look at
extract_statementsandextract_code_in_tail_position. - Assistant
Let me look at the
extract_code_in_tail_positionandextract_statementsmethods more carefully. - Assistant
Let me look at both functions.
- Assistant
Now let me understand the problem better. Let me look at how
usestatements are represented in the AST. - Assistant
Now let me look at the tests for this feature to understand the expected behavior:
- Assistant
The issue seems to be about the "Extract function" code action in the Gleam language server. Let me search for the actual test file and look at the tests for the Extract Function feature.
- Assistant
Let me look at the test for extracting function from statements to understand the expected behavior better. Let me also look for tests related to extracting from a function body where not all statements are selected.
- Assistant
Let me look at the expected output of
extract_function_from_statementstest: - Assistant
Let me now look at how
usestatements have their location set in the AST, because the issue is likely thatusestatements consume a large location range. - Assistant
Let me check what
TypedStatement::location()returns for different statement types. - Assistant
I see a critical piece! Let me look at how
TypedStatement::location()works for aUsestatement:Statement::Use(use_) => use_.location.merge(&use_.call.location()),This is key! A
usestatement's location is the merge of theuseline location and thecall.location(). Since ausestatement's call contains the entire desugared callback (including all following statements), the statement's location can span the entire rest of the function body.Let me check how the function body is structured.
- Assistant
Now I'm getting a clearer picture. The key issue is that
TypedStatement::location()for aUsestatement merges theuseline with the entire callback body:Statement::Use(use_) => use_.location.merge(&use_.call.location()),This means a
usestatement's location spans from theusekeyword all the way to the end of the block (becausecall.location()includes the callback body). Let me verify by looking at the visitor'svisit_typed_statementand howusestatements interact with selection. - Assistant
Let me look at how the visitor traverses
usestatements: - Assistant
Now let me understand the full picture. The key is how Gleam represents the function body with
usestatements. Let me check theTypedFunctionbody structure: - Assistant
Let me search more broadly.
- Assistant
Let me check the
Functionstruct: - Assistant
Now let me look at how the function body is structured when there are
usestatements. I need to understand if the body has multiple statements or just one. - Assistant
Let me look at the visit_typed_function in the visit module.
- Assistant
Let me understand how
usestatements affect the function body structure. Let me look at how use is desugared during type checking: - Assistant
Let me look at
infer_use: - Assistant
Let me look at how function bodies with
usestatements are typed: - Assistant
Now I understand the problem. In Gleam,
usestatements consume all following statements into a callback. So the function body after type-checking is a singleUsestatement whoselocation()spans the entire function body (because it'suse_.location.merge(&use_.call.location())). When the user selects a subset of statements within theuseblock, thecan_extract_statementcheck sees the selection overlaps with the Use statement's range and extracts everything.Let me verify this by looking at existing tests with
usestatements: - Assistant
Let me search for tests that specifically test extracting functions containing
use: - Assistant
Let me look at the snapshot test files to understand the expected outputs:
- Assistant
Let me search for snapshot files with extract_function.
- Assistant
Let me find the snapshot directory.
- Assistant
Let me find the extract_function snapshot files.
- Assistant
Let me look at the full
can_extract_expressionmethod: - Assistant
Let me look at the full function.
- Assistant
Now I understand the core issue. The problem is that when a function starts with
usestatements, the entire function body is wrapped into a single Use statement in the typed AST. The Use statement'slocation()merges theuseline with the entire call location (which includes the callback body), so it spans the whole function body. When the user selects a subset of statements within the Use callback, thecan_extract_statementcheck incorrectly determines that the Use statement itself should be extracted.Let me check if
ExtractFunctionoverridesvisit_typed_use: - Assistant
I see that there's a
visit_typed_useimplementation. Let me look at it: - Assistant
This
visit_typed_useis for a different visitor (extract variable). Let me check which visitors are defined forExtractFunction: - Assistant
Now I understand the full picture. Let me look at the
visit_typed_useoverride (this one is for extract variable, not extract function). TheExtractFunctionvisitor doesn't overridevisit_typed_use.Let me trace the full problem flow. The key insight is:
-
In Gleam,
usestatements consume all following statements into a callback. After type-checking, the function body contains just oneUsestatement whoselocation()spans the entire function body (becausestatement.location()forUsemerges theuseline with the call's location). -
can_extract_statementchecksoverlaps(statement_range, selected_range)using this merged range, finds an overlap, and then checks!completely_within(selected_range, statement_range)- which returns true when the selection extends to the edge of the function. -
This causes the entire Use statement (and thus the entire function body) to be extracted.
The fix needs two parts:
- In
can_extract_statement, forUsestatements, useuse_.location(just the use line) instead ofstatement.location(). - Override
visit_typed_useinExtractFunctionto traverse into the callback body when the selection is inside it (not on the use line).
Let me implement this:
-
- Assistant
Now I understand the issue. The key problem is:
-
In Gleam's typed AST, when a function starts with
use, the entire function body becomes a singleUsestatement. Itslocation()merges theuseline withuse_.call.location(), spanning the entire function body. -
can_extract_statementforUsechecks!completely_within(selected_range, statement_range)wherestatement_rangeis this merged range. Sincecompletely_withinuses strict inequality, when the selection ends at the same position as the statement range, it returns false, making!completely_withintrue, so the entire Use is considered extractable. -
Additionally, even if we fix
can_extract_statement, the visitor would still traverse into the call expression viavisit_typed_use, and the call expression (which also spans the entire function) would be extracted byvisit_typed_expr→can_extract_expression.
The fix requires two changes:
- In
can_extract_statement, forUsestatements, useuse_.location(just the use line) instead ofstatement.location()(merged range). - Override
visit_typed_useinExtractFunctionto traverse into the callback body directly when the selection doesn't overlap with the use line.
Let me first implement the fix:
-
- Assistant
Now let me implement the fix. First, let me modify
can_extract_statementforUsestatements: - Assistant
Now let me add the
visit_typed_useoverride to theExtractFunctionvisitor. Let me find the right place to add it: - Assistant
Now I need to add a
visit_typed_useoverride. Let me add it right aftervisit_typed_expr_block: - Assistant
Let me verify the changes look correct:
- Assistant
Let me also see the visit_typed_use override:
- Assistant
Good, the changes look correct. Now let me build and run the existing tests to make sure I haven't broken anything:
- Assistant
Let me check the Rust toolchain setup:
- Assistant
Let me check if there's a specific toolchain needed.
- Assistant
Let me check what's installed via rustup.
- Assistant
Let me run the tests again:
- Assistant
I see a compile error.
body.last()returns&TypedStatementdirectly (sinceVec1guarantees at least one element), notOption. Let me fix this: - Assistant
Let me check the Vec1 type.
- Assistant
Vec1 is probably from the
vec1crate. Let me look at howbody.last()is used elsewhere. - Assistant
I see.
body.last()forVec1returns a reference directly (not anOption). Let me fix the code: - Assistant
Now let me rebuild and test:
- Assistant
All 22 existing extract_function tests pass. Let me run the full test suite for the language-server package:
- Assistant
All 1537 tests pass. Now let me also write a quick script to verify the fix handles the specific case from the issue. Let me look at how tests are structured:
- Assistant
Let me look at the test macros to understand how to write a test:
- Assistant
Let me look at the snapshot for
extract_function_from_statementsto understand the expected output format: - Assistant
Now let me write a test that verifies the fix. Let me first add a test case to the test file:
- Assistant
Let me look at the test structure near the end of extract function tests to find a good place to add a test:
- Assistant
Let me see what's after
extract_use_in_tail_position: - Assistant
Now let me add a test for the specific bug. I'll add it after the existing use-related extract tests:
- Assistant
Now let me add a test for the bug fix. I'll add it right before line 12953:
- Assistant
Let me run the new test to see if it passes:
- Assistant
The test output looks correct! The two
usestatements remain in the original function and only the selected statements (let candlet d) are extracted. Let me accept the snapshot: - Assistant
Let me find and accept the pending snapshot:
- Assistant
Let me check the new snapshot content and accept it:
- Assistant
The output looks correct. Let me accept the snapshot:
- Assistant
Now let me run all the extract function tests again to make sure everything passes:
- Assistant
All 23 extract_function tests pass. Let me run the full test suite to make sure nothing is broken:
- Assistant
All 1538 tests pass. Let me also verify by running the compiler-core tests:
- Assistant
Let me also check if there are any other extract-related tests that might be affected:
- Assistant
All 180 extract-related tests pass. Let me now review the final changes:
- Assistant
Let me see the full diff:
- Assistant
Let me also check the new snapshot file:
- Assistant
The snapshot output is correct and matches the expected behavior from the issue. Let me run one final comprehensive test:
- Assistant
Let me check the full output:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
claude-sonnet-5Compare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.6-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →
Qwen/Qwen3.5-35B-A3BCompare side by side →