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:rs/// 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:
rsfn prepare_project_structure( target_path target: TargetPath, user_id user_id: uuid.Uuid, ) -> Result(Nil, SubmitError) { function(target, user_id) }instead of the expected:
rs Assistant
I'll start by exploring the repository structure to understand the codebase and then find the relevant code for the "Extract function" feature.
Assistant
This is the Gleam compiler repository. The issue is about the "Extract function" feature in the language server. Let me explore the language-server directory.
Assistant
Let me look at the
ExtractFunctioncode in detail.Assistant
Now let me look at the visitor implementation for
ExtractFunction.Assistant
Let me look at how
usestatements are represented in the AST.Assistant
Let me check the
location()implementation forStatement.Assistant
Let me look at the helper functions
completely_within,within,overlaps, etc.Assistant
Let me look at the existing tests for extract function to understand the test format.
Assistant
Let me search for tests involving
usewith extract function.Assistant
Let me look at the test helpers to understand the format.
Assistant
Let me write a reproduction test. First let me look at how the
assert_code_action!macro works.Assistant
Let me look at how the typed body is structured for
usestatements. Let me check the typing ofuse.Assistant
Now I understand the structure. When there's a
usestatement, thefollowing_expressions(everything after theuse) get collected into a callback function. So the body of a function withusestatements becomes a single statement: the firstuse's call, whose callback contains the rest.Wait, let me look at the broader context to see how
infer_useis called and how the body is structured.Assistant
This is the key insight. When the type checker encounters a
usestatement, it consumes all remaining statements into the callback. So the typed body has the firstusewhose callback contains everything after it. Let me look atvisit_typed_use.Assistant
Now let me look at
can_extract_expressionin detail.Assistant
Let me look at the default
visit_typed_exprforFnto understand how the body is traversed.Assistant
This is getting complex. Let me write a reproduction test to see the actual behavior. First, let me look at how
find_position_ofandselect_untilwork.Assistant
Let me build the language-server tests first to make sure the environment works.
Assistant
Now let me write a reproduction test. Let me add a temporary test to the action.rs file.
Assistant
Let me add a temporary reproduction test at the end of the action.rs file.
Assistant
The "d" matched the wrong occurrence. Let me fix the test with unique markers.
Assistant
The file got cut. Let me check the line count.
Assistant
The
head -n -16command removed too much. The original file had 14837 lines, but now I have 14840. Wait, that doesn't make sense. Let me check git diff to see what happened.Actually, the issue is that the
head -n -16removed the last 16 lines, but then I appended the test again? No. Let me check git status.Assistant
Let me restore the file from git and start over.
Assistant
Let me append the test properly with unique markers.
Assistant
The "zzz" matched the wrong occurrence (in
use zzz). Let me fix the test to select the correct range usingnth_occurrence.Assistant
Let me add debug prints to understand what's happening in the code.
Assistant
The debug print is before
visit_typed_module. Let me fix its placement.Assistant
So
functionis None after the visit. My trace was wrong. Let me add debug prints to the visitor methods.Assistant
The
!in the comment caused an issue with bash history expansion but the python wrote the file. Let me check if the replace happened correctly.Assistant
The replace didn't happen due to bash escaping. Let me use a file-based approach.
Assistant
The issue is my test code doesn't type-check -
wibble(f)takes 1 arg butuse a <- wibble(1)calls with 2. Let me fix the test.Assistant
I checked out the file which removed debug prints. Let me first run the test with the fixed wibble.
Assistant
My reproduction actually produces the CORRECT output. The bug isn't reproduced. Let me re-add debug prints and trace through to understand the real behavior, then craft a test that reproduces the actual bug.
Assistant
The visit_typed_statement patch was applied but visit_typed_expr failed. Let me check why - the file may have been partially modified. Let me check.
Assistant
I see, the previous debug print (from my earlier patch that I thought was reverted) is still there. The git checkout reverted the test file but the code_action.rs had the debug from the earlier patch2 attempt. Wait no. Let me check git status.
Assistant
Let me revert code_action.rs and start fresh with a cleaner debug approach.
Assistant
Now let me add comprehensive debug prints cleanly.
Assistant
I found the key difference. In my repro, the selection ends at the START of
zzz(char 2), which is BEFORE use1's range end (char 5), socompletely_withinis true and use1 is NOT extracted.In the issue, the selection ends at the END of the last expression, which EQUALS use1's range end, making
completely_withinfalse and use1 gets extracted (the bug).Let me modify my repro to select until the END of the last statement.
Assistant
Even with
under_last_charit produces correct output. The selection end needs to equal use1's range end exactly. Let me re-add debug prints and test with an offset that places selection.end exactly at the span end.Assistant
Now let me update the test to place selection.end exactly at the span end using
with_char_offset.Assistant
I've reproduced the bug! The entire function body is extracted. Let me look at the debug output to confirm the trace.
Assistant
I've reproduced the bug. The trace confirms: when
selection.end == use_range.end(selecting to the end of the callback),completely_withinreturns false (strict<), making the outermostuseextractable, which extracts the entire function.The root cause: a
usestatement's location extends to the end of its callback (end of the block/function). When the user selects content inside the callback that ends at the callback's end, the strictcompletely_withincheck fails to recognize the selection as "within" the use, so it extracts the whole use instead of traversing deeper.Let me look at the
can_extract_statementcode once more and implement the fix.Assistant
Now let me implement the fix. I'll change the
Use/Assertcase to use an inclusive-end check so that selecting to the end of ause's callback still traverses deeper instead of extracting the wholeuse.Assistant
Still extracting everything. Let me re-add debug to see what's happening with the fix applied.
Assistant
use3 still has
can_extract=truebecause the selection starts atlet cc(before use3). But more importantly, I need to check if the callbackFnexpression is being extracted. Let me re-add the extraction debug print.Assistant
The trace reveals the deeper issue: the
use's desugared Call expression (loc=45-131, the whole function) is being extracted viacan_extract_expression, because!completely_within(strict end) returns true whenselection.end == expr.end. I need to fixcan_extract_expressiontoo. Let me first revert the debug prints and check existing tests that might be affected.Assistant
Let me apply both fixes: the
can_extract_statementUse/Assert fix and thecan_extract_expressiongeneral fix. Let me write a combined patch.Assistant
The bug is fixed - the output is now correct. The test only "failed" due to no snapshot. Let me remove my temp test and run the full extract function test suite to check for regressions.
Assistant
All 179 extract tests pass. Let me run the full action test suite to be thorough.
Assistant
All 881 action tests pass. Let me run the full language-server test suite.
Assistant
All 1537 tests pass. Let me verify no debug prints remain in the code.
Assistant
Let me view the final diff to verify the changes are clean.
Assistant
The diff is clean. Now let me verify edge cases with temporary tests. Let me test a scenario with uses before but no use in the middle of the selection, and selecting to the end.
Assistant
Both edge cases produce correct output. Let me also verify that selecting the whole
use(from theusekeyword to the end) still extracts the whole use, to ensure I didn't break that.Assistant
Selecting the whole
usestill extracts it correctly. Let me test one more edge case: selection starting at the second statement inside a use callback, going to the end.Assistant
All edge cases work correctly. Let me also reproduce the exact issue scenario with a pipeline tail to be thorough.
Assistant
The pipeline tail case (closely mirroring the issue) works correctly. Let me clean up the temp test and run the full test suite once more.
Assistant
All 1537 tests pass. Let me make sure the code compiles cleanly with no warnings related to my changes.
Assistant
The build is clean. Let me check the CHANGELOG to see if I should add an entry, following the repo's conventions.
Assistant
Let me add a CHANGELOG entry under the "Language server" section, following the existing format.
Assistant
There's a "Bug fixes" section. Let me add my entry there. I'll add it at the end of the Bug fixes section (after the last entry, before the next section if any). Let me check what comes after line 144.
Assistant
Let me check if there's any test that validates the CHANGELOG format that I might need to be aware of.
Assistant
No tests reference CHANGELOG. Let me run the full language-server test suite once more to confirm everything passes after all changes.
Assistant
All tests pass. Let me verify the final diff and confirm no stray debug code or temp files remain.
Assistant
There are untracked snapshot files from my temp tests that I need to clean up.
Assistant
Only the intended files are modified. Let me do a final verification run of the full test suite after cleanup.
Assistant
Let me confirm
completely_withinis still used (so no unused import warning) and verify the final state.Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.