ISSUE DESCRIPTION "Extract function" incorrectly returns Nil when extracting from…
- User
ISSUE DESCRIPTION
"Extract function" incorrectly returns
Nilwhen extracting from anonymous functionWhen trying to extract a function from within an anonymous function, the extracted function always returns
Nil, even when incorrect.For example:
gleamfn wibble() { let wobble = fn() { echo "wibble" echo "wobble" // extracting this line } }is turned into
gleamfn wibble() { let wobble = fn() { echo "wibble" function() } } fn function() -> Nil { echo "wobble" Nil // this is incorrect! }I have a fix for it.
Interface
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.
Assistant
I'll start by exploring the repository structure to understand the codebase and find the relevant code for the "extract function" feature.
Assistant
I'll explore the repository structure first.
Assistant
The "extract function" feature is likely in the language server's code action. Let me look at that.
Assistant
The extract function code action seems to be elsewhere. Let me search for "extract_function" specifically.
Assistant
Let me look at the
ExtractFunctionstruct and its implementation.Assistant
Let me continue looking at the implementation, especially around how the function is built and how the return type is determined.
Assistant
This is about extracting whole anonymous functions. The issue is about extracting a statement from within an anonymous function. Let me look at the visitor code that handles statements and how it determines tail position.
Assistant
Now I see how tail position is determined using
last_statement_location, set invisit_typed_functionandvisit_typed_expr_block. The issue is about extracting a statement from within an anonymous function. Let me look at howTypedExpr::Fnis visited.Assistant
The
ExtractFunctionvisitor (starting at line 11254) doesn't seem to define avisit_typed_expr_fn. Let me check what visitors it defines and whether it inherits the default behavior.Assistant
ExtractFunctiondoes NOT definevisit_typed_expr_fn. So the default visitor is called when visiting an anonymous function. Let me look at the defaultvisit_typed_expr_fnto understand what it does with the body.Assistant
Now I understand the bug. The default
visit_typed_expr_fnvisits each statement in the body directly WITHOUT updatinglast_statement_location. So when extracting a statement from within an anonymous function, thelast_statement_locationstill holds the outer function's last statement, causing the inner statement to be incorrectly treated asNotTail.Let me look at the trait method signature for
visit_typed_expr_fn.Assistant
Now let me look at the existing tests for extract function to understand the test structure, then write a reproduction script.
Assistant
Let me look at the
assert_code_action!macro to understand how tests verify output.Assistant
Let me find the snapshot files for the extract function tests to understand the expected output format.
Assistant
Let me check whether
echois supported in this version of the compiler.Assistant
echois supported. Now let me add a temporary reproduction test to confirm the bug. Let me first check the EXTRACT_FUNCTION constant.Assistant
Let me add a temporary test to reproduce the issue. I'll insert it after the
extract_function_from_statementstest.Assistant
Let me check the available helper functions for selecting ranges to get the selection right.
Assistant
Let me fix my temporary test to use proper selection helpers. Let me first check
can_extract_statement.Assistant
Let me fix the temporary test to use a proper range selection.
Assistant
Now let me run the temporary test to confirm the bug.
Assistant
There's no rust-toolchain file and rustup has no default. Let me check the rustc version and try setting a default or using the toolchain directly.
Assistant
Now rustup has a default. Let me run the temporary test.
Assistant
The selection in my test was malformed (it matched the variable name
wobble). Let me look at the helper functionscompletely_within,overlaps, andposition_withinto craft a correct selection.Assistant
Let me check
RangeSelector::find_rangeto understand howfrom/tomap to the range.Assistant
Now let me update the temporary test with a correct selection (from the second
echoto the closing quote of"wobble").Assistant
Let me verify the test content is correct.
Assistant
Now let me run the test to confirm the bug.
Assistant
I've reproduced the bug exactly as described in the issue. The extracted function returns
Nilinstead ofString.The root cause:
ExtractFunctiondoes not overridevisit_typed_expr_fn, so when visiting an anonymous function's body, the default visitor visits statements directly without updatinglast_statement_location. This causes the last statement of an anonymous function body to be incorrectly treated asNotTail.Let me look at the
visit_typed_expr_blockoverride to mirror it forvisit_typed_expr_fn.Assistant
I'll add a
visit_typed_expr_fnoverride. Let me first check theVec1API to use the correct method (whetherlast()returnsOptionor a direct reference).Assistant
Interesting - at line 11260,
function.body.last()returns anOption(becausefunction.bodyis aVec<TypedStatement>for top-level functions). But forTypedExpr::Fn, thebodyis aVec1<TypedStatement>, andbody.last()returns&TypedStatementdirectly (line 10558, 2910, etc. usebody.last().location()without Option).Wait, let me re-check. Line 3093:
if let Some(last) = &fun.body.last()- this is forfun.bodywhich might be Vec1 butlast()returns Option here? Let me check what typefun.bodyis. Hmm.Actually, let me check the Vec1 crate.
Assistant
The vec1 crate isn't in the registry. Let me check the Cargo.lock or find where vec1 is.
Assistant
Vec1::last()returns a direct&Treference. Now let me check thatVec1,FunctionLiteralKind,TypedArg,TypeAstare all in scope in code_action.rs.Assistant
All types are in scope. Now let me add the
visit_typed_expr_fnoverride right aftervisit_typed_expr_blockin theExtractFunctionVisit impl.Assistant
Now let me verify the
TypeAstis accessible (the default trait method signature usesOption<TypeAst>). Let me check whether it's imported directly or needsast::.Assistant
TypeAstis referenced asast::TypeAstelsewhere. Let me check whether it's directly imported in the use statement.Assistant
TypeAstis not directly imported; it's accessed viaast::TypeAst. Let me fix my edit to useast::TypeAst.Assistant
Now let me run the temporary test to verify the fix produces the correct output (returning
Stringinstead ofNil).Assistant
The fix works correctly. The extracted function now returns
String(the type ofecho "wobble") instead of incorrectly returningNil.Now let me run all the existing extract_function tests to make sure I haven't broken anything.
Assistant
All 20 existing extract_function tests pass. Now let me test edge cases. Let me check if there's an existing test that extracts a whole anonymous function (which uses
extract_anonymous_function).Assistant
Let me look at the test around line 4302 which extracts a whole anonymous function to ensure my change doesn't break the
extract_anonymous_functionpath.Assistant
Let me search the snapshots to find tests that extract whole anonymous functions (which use the
extract_anonymous_functionpath) to verify they still match.Assistant
Whole-anonymous-function extraction tests still pass. Now let me test edge cases. Let me add temporary tests for: (1) extracting a non-last statement (should return
Nil), and (2) extracting multiple statements ending in the tail.Assistant
The tests "fail" only because there are no stored snapshots (they're new tests). The outputs are what matter:
- Non-last statement extraction: returns
Nil✓ (correct) - Last statement extraction: returns
String✓ (correct)
Let me see the multi-statement case output.
- Non-last statement extraction: returns
Assistant
The multi test failed due to a selection bug in my test (there's only one
"wobble"string). Let me fix the selection.Assistant
The escape of the quotes in the python heredoc may have issues. Let me check the actual content of the multi test.
Assistant
Let me use sed to fix the multi test selection.
Assistant
All edge cases work correctly:
- Last statement extraction → returns
String✓ - Non-last statement extraction → returns
Nil✓ (correct, side-effect only) - Multiple statements ending in last → returns
String✓
Now let me clean up the temporary tests and snapshot files.
- Last statement extraction → returns
Assistant
Now let me remove the temporary tests from action.rs.
Assistant
The file ends at line 14728 (the closing
}of the last temp test) plus a newline. Let me check the exact end of the file.Assistant
The temp tests span from line 14675 (blank line before
#[test]) to the end of the file. Let me truncate the file to keep only lines up to 1474 (the}of the previous test) plus a trailing newline.Assistant
Let me re-grep to find the exact line numbers for the temp tests and the end of the previous real test.
Assistant
Let me check the lines around the boundary precisely.
Assistant
Let me check exactly what's on lines 14674-14676 and line 1474.
Assistant
I confused myself - line 1474 is an early line, while the temp tests are near the end (file is 14728 lines). The temp tests start at line 14676. Let me check git to see the original end of the file before my temp additions.
Assistant
The original file has 14674 lines ending with
}. Let me truncate my modified file to 14674 lines to exactly restore the original.Assistant
No diff for action.rs - it's restored to the original. Now let me verify the only changes are in code_action.rs.
Assistant
The diff is clean and only in code_action.rs. Let me build the language server to make sure it compiles cleanly, then run the extract function tests once more.
Assistant
All 24 tests pass. Let me run the broader action test suite to ensure nothing else broke (e.g., ExtractVariable which also has visitor code).
Assistant
All 871 action tests pass. Let me run the entire language-server test suite to be thorough.
Assistant
All 1514 language-server tests pass. Let me do a final review of the change and confirm the working tree is clean except for the intended fix.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.