Skip to content
TheChatArchiveThe Chat Archive
MiniMaxminimax/minimax-m3· unknownHugging Face ibragim-bad/swe_rebench_07_2026_trajectories

ISSUE DESCRIPTION "Extract function" incorrectly returns Nil when extracting from…

  1. User

    ISSUE DESCRIPTION

    "Extract function" incorrectly returns Nil when extracting from anonymous function

    When trying to extract a function from within an anonymous function, the extracted function always returns Nil, even when incorrect.

    For example:

    fn wibble() {
      let wobble = fn() {
        echo "wibble"
        echo "wobble" // extracting this line
      }
    }
    

    is turned into

    fn 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 using git reset --hard command. Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later. Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands. However you don't need to use git add or git commit before submitting your changes. In fact, submit only submits currently unstaged changes because it uses git diff to 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-$

  2. MiniMax Assistant

    Let me start by exploring the repository structure to understand what we're working with.

  3. MiniMax Assistant

    This is the Gleam compiler repository. Let me explore further to find the relevant code for the "Extract function" feature

  4. MiniMax Assistant

    Let me explore the ExtractFunction code to understand it better

  5. MiniMax Assistant

    Now let me look at the test file for extract function to understand the existing test format:

  6. MiniMax Assistant

    me look at the existing snapshot tests for this feature to understand the test framework better:

  7. MiniMax Assistant

    Let me look more carefully at the extract_anonymous_function_body function and trace through the code path:

  8. MiniMax Assistant

    Let me check git log to see if there's any branch or PR for this:

  9. MiniMax Assistant

    Let me set up the build environment first to verify the issue and test my fix:

  10. MiniMax Assistant

    write a temporary test to reproduce the issue:

  11. MiniMax Assistant

    first build the project to verify my fix:

  12. MiniMax Assistant

    Good, the project compiles. Let me now run the existing tests to see if they pass.

  13. MiniMax Assistant

    Now let me look at the issue closely. Let me search for the visitor and trace through:

  14. MiniMax Assistant

    Now I understand the bug. Let me look at the visitor for TypedExpr::Fn:

  15. MiniMax Assistant

    Let me write a test script to reproduce the issue first:

  16. MiniMax Assistant

    Now let me write a temporary test that simulates the issue. I'll first add a test that reproduces the issue, then I'll fix the code.

    Actually, let me think about this more carefully. Let me look at the structure of the body in the AST. The body of the Fn is a Vec1<TypedStatement>. So when visit_typed_expr_fn is called, it iterates over body statements and calls visit_typed_statement on each. So last_statement_location is not updated.

    Let me look at the visit_typed_function more carefully:

    fn visit_typed_function(&mut self, function: &'ast TypedFunction) {
        let range = self.edits.src_span_to_lsp_range(function.full_location());
    
        if within(self.params.range, range) {
            self.function_end_position = Some(function.end_position);
            self.last_statement_location = function.body.last().map(|last| last.location());
    
            ast::visit::visit_typed_function(self, function);
        }
    }
    

    So when visiting a function, last_statement_location is set to the last statement of the function's body. Then visit_typed_function visits the function which visits the body block (via visit_typed_expr_block) which then saves and sets last_statement_location again. So this works correctly.

    But for visit_typed_expr_fn, there's no such override. The default behavior is to iterate over the body statements directly without setting last_statement_location.

    So the fix is to override visit_typed_expr_fn in ExtractFunction to properly track the last statement location.

    Let me write the fix:

    fn visit_typed_expr_fn(
        &mut self,
        location: &'ast SrcSpan,
        type_: &'ast Arc<Type>,
        kind: &'ast FunctionLiteralKind,
        arguments: &'ast [TypedArg],
        body: &'ast Vec1<TypedStatement>,
        return_annotation: &'ast Option<ast::TypeAst>,
    ) {
        let range = self.edits.src_span_to_lsp_range(*location);
    
        if within(self.params.range, range) {
            let last_statement_location = self.last_statement_location;
            self.last_statement_location = body.last().location().into_option();
    
            // ... also need to handle the case where the entire Fn is selected
            // i.e., check if can_extract_expression on the Fn
            // But wait, that's done by visit_typed_expr which is called before this.
            
            ast::visit::visit_typed_expr_fn(self, location, type_, kind, arguments, body, return_annotation);
    
            self.last_statement_location = last_statement_location;
        }
    }
    

    Wait, but we need to also handle the case where the entire Fn expression is selected. Let me check.

    Actually, visit_typed_expr is called before visit_typed_expr_fn. So if the entire Fn expression is selected, visit_typed_expr would set self.function first. Then when we visit children, the visit_typed_expr_fn is called, but since self.function.is_some(), we wouldn't update last_statement_location for the Fn body (we don't want to mess with that since we're extracting the entire Fn).

    Hmm, but actually, the visit_typed_expr_fn is called for each Fn expression regardless of whether we're extracting it. So we need to be careful here.

    Let me look at the flow:

    1. visit_typed_function(wibble):

      • last_statement_location = Assignment.location() (the last statement of wibble)
      • Visit body
    2. visit_typed_expr_block(wibble's body):

      • Save last_statement_location (= Assignment.location())
      • last_statement_location = Assignment.location() (same since only one statement)
      • Visit statements
    3. visit_typed_statement(Assignment):

      • can_extract_statement returns false (not selected)
      • Visit children (the right-hand side, which is the Fn expression)
    4. visit_typed_expr(Fn):

      • If the entire Fn is selected, can_extract_expression returns true and we set self.function
      • Otherwise, visit children
    5. visit_typed_expr_fn(Fn):

      • Visit arguments
      • Visit body statements
    6. visit_typed_statement(Echo("wibble")):

      • can_extract_statement returns false
      • Visit children
    7. visit_typed_statement(Echo("wobble")):

      • can_extract_statement returns true
      • is_in_tail_position = last_statement_location == statement_location
      • last_statement_location is still Assignment.location() (NOT Echo("wobble").location())
      • So is_in_tail_position is false
      • BUG!

    OK so the fix is to properly track last_statement_location when entering a function body. Let me also think about the case where the entire Fn expression is selected. In that case, self.function is set by visit_typed_expr, and we don't want to mess with last_statement_location for the Fn body because we're not extracting individual statements.

    Actually wait, in the case where the entire Fn is selected, the body of the Fn is not extracted - only the whole Fn expression. So we should not be tracking last_statement_location for the Fn body.

    Actually, let me re-read the existing code for visit_typed_function:

    fn visit_typed_function(&mut self, function: &'ast TypedFunction) {
        let range = self.edits.src_span_to_lsp_range(function.full_location());
    
        if within(self.params.range, range) {
            self.function_end_position = Some(function.end_position);
            self.last_statement_location = function.body.last().map(|last| last.location());
    
            ast::visit::visit_typed_function(self, function);
        }
    }
    

    So this sets last_statement_location even when the entire function is selected. Then visit_typed_expr_block is called for the body, which saves and re-sets last_statement_location. Then visit_typed_statement is called for each statement. Each statement check can_extract_statement. For top-level statements in the function body, if the entire function is selected, can_extract_statement should return true for all statements (since they're all overlapping with the selection). But the existing code at the top of visit_typed_statement checks self.can_extract_statement. Let me re-read:

    fn visit_typed_statement(&mut self, statement: &'ast TypedStatement) {
        let statement_location = statement.location();
    
        if self.can_extract_statement(statement) {
            // ...
        }
        ast::visit::visit_typed_statement(self, statement);
    }
    

    So if the entire function is selected and visit_typed_function is called, all statements inside would have can_extract_statement return true. But the selection starts with the FIRST statement and ends with the LAST statement (probably). Hmm, this is getting complex.

    Let me focus on the bug. The fix is to ensure that last_statement_location is updated when entering the body of a Fn expression.

    Let me write the fix:

    fn visit_typed_expr_fn(
        &mut self,
        location: &'ast SrcSpan,
        type_: &'ast Arc<Type>,
        kind: &'ast FunctionLiteralKind,
        arguments: &'ast [TypedArg],
        body: &'ast Vec1<TypedStatement>,
        return_annotation: &'ast Option<ast::TypeAst>,
    ) {
        let last_statement_location = self.last_statement_location;
        self.last_statement_location = body.last().location().into_option();
    
        ast::visit::visit_typed_expr_fn(self, location, type_, kind, arguments, body, return_annotation);
    
        self.last_statement_location = last_statement_location;
    }
    

    Wait, but we also need to handle the function_end_position. Looking at the visit_typed_function:

    fn visit_typed_function(&mut self, function: &'ast TypedFunction) {
        let range = self.edits.src_span_to_lsp_range(function.full_location());
    
        if within(self.params.range, range) {
            self.function_end_position = Some(function.end_position);
            // ...
        }
    }
    

    For an anonymous function (Fn expression), we should set function_end_position too, so that the extracted function can be inserted at the right location.

    Wait, let me look at what function_end_position is used for. Let me search:

  17. MiniMax Assistant

    So TypedExpr::Fn doesn't have an end_position field directly. It has a location (SrcSpan) which has a start and end. Let me look at how function_end_position is used in extract_anonymous_function:

  18. MiniMax Assistant

    Let me first try to add a test to reproduce the issue, then I'll fix the code.

  19. MiniMax Assistant

    Let me look at the visit module more carefully to understand how visit_typed_expr_fn is called and trace through the bug:

  20. MiniMax Assistant

    Let me think about how the body Vec1 last item works:

  21. MiniMax Assistant

    let me look at the existing visit functions to understand what state needs to be tracked when visiting an anonymous function:

  22. MiniMax Assistant

    Now I understand the bug. The fix is to override visit_typed_expr_fn in the ExtractFunction struct to properly track the last_statement_location when entering a function body.

    Let me write a temporary test script to confirm the bug:

  23. MiniMax Assistant

    Let me check if there's a way to invoke the language server's extract function logic directly:

  24. MiniMax Assistant

    Let me look at the code_actions function:

  25. MiniMax Assistant

    Let me add a test to reproduce the issue:

  26. MiniMax Assistant

    Let me add the test temporarily:

  27. MiniMax Assistant

    I reproduced the bug. The result is:

    fn function() -> Nil {
      echo "wobble"
      Nil // this is incorrect!
    }
    

    The extra Nil at the end is the bug. Now let me apply the fix.

  28. MiniMax Assistant

    let me look at the Vec1 import:

  29. MiniMax Assistant

    Now let me apply the fix. I'll modify the ExtractFunction to override visit_typed_expr_fn to track the last_statement_location:

  30. MiniMax Assistant

    Let me check what type body.last().location() returns:

  31. MiniMax Assistant

    Good. Now I can apply the fix. Let me look at where the visit_typed_expr_fn is called and make the change.

    Wait, looking at the visit_typed_function:

    fn visit_typed_function(&mut self, function: &'ast TypedFunction) {
        let range = self.edits.src_span_to_lsp_range(function.full_location());
    
        if within(self.params.range, range) {
            self.function_end_position = Some(function.end_position);
            self.last_statement_location = function.body.last().map(|last| last.location());
    
            ast::visit::visit_typed_function(self, function);
        }
    }
    

    This uses function.body.last().map(|last| last.location()) which returns Option<SrcSpan>. So last_statement_location is Option<SrcSpan>.

    For Vec1, .last() returns &T, so body.last().location() would be SrcSpan (not Option<SrcSpan>). But we need Option<SrcSpan>. So I need to use Some(body.last().location()).

    Wait, let me check:

  32. MiniMax Assistant

    , last() on Vec1 returns &T. So body.last().location() returns SrcSpan. I need to wrap it in Some(...).

    Now let me apply the fix:

  33. MiniMax Assistant

    edit broke the file. Let me fix it:

  34. MiniMax Assistant

    let me add the fix carefully. I'll insert the new function right after visit_typed_expr_block:

  35. MiniMax Assistant

    The edit accidentally removed the original visit_typed_expr_block function. Let me restore and try again:

  36. MiniMax Assistant

    Now let me build the project to make sure my fix compiles:

  37. MiniMax Assistant

    I had restored the test file. Let me re-add the test to verify the fix:

  38. MiniMax Assistant

    Let me restore the test file and use a different approach:

  39. MiniMax Assistant

    There's a duplicate #[test] because the test_to_add.rs file has #[test] but the test was already there. Let me check if there was already a #[test] and if it's getting duplicated.

    Wait, looking at the original file structure, it seems the test code starts with #[test] and there's a } before fn extract_function_partially_selected(). Let me check again

  40. MiniMax Assistant

    a duplicate #[test] line. Let me fix that:

  41. MiniMax Assistant

    Now let me run the test to verify the fix:

  42. MiniMax Assistant

    The fix works! Now let me run all the existing extract function tests to make sure I didn't break anything:

  43. MiniMax Assistant

    Let me verify the return type of echo:

  44. MiniMax Assistant

    Let me check what echo returns in Gleam:

  45. MiniMax Assistant

    Now let me also think about the edge case where extracting the FIRST statement from inside an anonymous function:

  46. MiniMax Assistant

    I see, there's no #[test] before extract_function_partially_selected now. Let me add it back

  47. MiniMax Assistant

    Now let me run the edge case tests:

  48. MiniMax Assistant

    three edge cases are working correctly. Let me also check the CHANGELOG to understand the expected behavior better:

  49. MiniMax Assistant

    Let me run all the existing tests to make sure my fix doesn't break anything:

  50. MiniMax Assistant

    1514 tests pass. Let me also run the compiler-core tests:

  51. MiniMax Assistant

    All 3880 tests pass. Let me also add the temporary test back to verify the fix is working correctly with the original issue case:

  52. MiniMax Assistant

    Now let me run the temp test to see the output:

  53. MiniMax Assistant

    Let me look at the code for case where the entire anonymous function is being extracted:

  54. MiniMax Assistant

    Let me run the existing tests for extracting entire anonymous functions to make sure my fix doesn't break those:

  55. MiniMax Assistant

    let me remove the temporary test and confirm the fix:

  56. MiniMax Assistant

    Now let me run all the tests to confirm everything is working:

  57. MiniMax Assistant

    1514 tests pass. Let me check the diff to make sure my changes are correct:

  58. MiniMax Assistant

    The diff shows my fix. Let me also update the CHANGELOG to document the fix:

  59. MiniMax Assistant

    Hmm, the changelog wasn't updated. Let me check why.

    Oh, the issue is that the content doesn't match. Let me check the exact

  60. MiniMax Assistant

    CHANGELOG is updated. Let me verify the diff:

  61. MiniMax Assistant

    Let me run the full test suite one more time to make sure nothing is broken:

  62. MiniMax Assistant

    failures are unrelated - they're due to missing escript program on Linux. Let me run the relevant tests:

  63. MiniMax Assistant

    Let me also think about use statements inside anonymous functions:

  64. MiniMax Assistant

    Let me check the Statement::Use type to see how it works

  65. MiniMax Assistant

    Let me also write a few more edge case tests to make sure the fix is robust:

  66. MiniMax Assistant

    edge cases pass. Let me remove the temporary tests:

  67. MiniMax Assistant

    , no temp tests left. Let me run the full test suite to make sure everything still passes:

  68. MiniMax Assistant

    me clean up the temporary files:

  69. MiniMax Assistant

    Let me also check the changelog entry one more time:

  70. MiniMax Assistant

    Let me also verify the final state of my changes:

  71. MiniMax Assistant

    The diff looks clean. My changes are:

    1. Added a visit_typed_expr_fn override to the ExtractFunction struct that tracks the last_statement_location when visiting an anonymous function's body.
    2. Added a CHANGELOG entry documenting the fix.

    Let me also confirm the issue is correctly fixed by adding one more test scenario - the exact example from the issue:Let me also confirm the issue is correctly fixed by adding one more test scenario - the exact example from the issue:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[cat > /tmp/test_issue_scenario.rs << 'EOF' #[test] fn temp_test_issue_scenario() { // This is the exact scenario from the issue assert_code_action!( EXTRACT_FUNCTION, " fn wibble() { let wobble = fn() { echo "wibble" echo "wobble" } } ", find_position_of("echo "wobble"").select_until(find_position_of("echo "wobble"").under_last_char()) ); } EOF

    python3 << 'PYEOF' with open('/tmp/test_issue_scenario.rs', 'r') as f: test_to_add = f.read()

    with open('language-server/src/tests/action.rs', 'r') as f: content = f.read()

    target = 'fn extract_function_partially_selected() {' new_content = content.replace(target, test_to_add + '\n' + target, 1)

    new_content = new_content.replace('}\n\nfn extract_function_partially_selected() {', '}\n\n#[test]\nfn extract_function_partially_selected() {')

    with open('language-server/src/tests/action.rs', 'w') as f: f.write(new_content) print('Added test') PYEOF]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>

  72. MiniMax Assistant

    I need to invoke the tool properly. Let me try

  73. MiniMax Assistant

    The fix works perfectly. Let me remove the temporary test:

  74. MiniMax Assistant

    also clean up the temporary file:

  75. MiniMax Assistant

    fix is clean and minimal. Let me also check the changelog format to make sure it matches the existing style:

  76. MiniMax Assistant

    look at the git log to see if recent CHANGELOG entries follow any particular convention:

  77. MiniMax Assistant

    The changelog format seems fine. Let me look at the v1.17.md to see the conventions for individual bug fixes:

  78. MiniMax Assistant

    The convention seems to use "Bug Fixes" (capital F) and "Fixed a bug where ..." pattern. Let me update my changelog to match this convention:

  79. MiniMax Assistant

    CHANGELOG.md uses lowercase "Bug fixes" but the changelog/v1.17.md uses uppercase "Bug Fixes". Let me check if there are other patterns.

  80. MiniMax Assistant

    The recent commit removed a duplicate "Bug Fixes" heading. The current convention seems to be lowercase "Bug fixes" for the active changelog. My change is consistent with the existing format.

    Let me also do one more test - run a wider test to ensure nothing is broken:Let me also do one more test - run a wider test to ensure nothing is broken:]<]minimax[>[<tool_call> ]<]minimax[>[]<]minimax[>[cd /gleam && cargo test --workspace --lib --exclude test-commands --exclude compiler-cli --exclude test-output 2>&1 | grep "test result"]<]minimax[>[]<]minimax[>[ ]<]minimax[>[</tool_call>

  81. MiniMax Assistant

    Let me try the bash terminal command properly

  82. MiniMax Assistant

    5714 tests pass. My fix doesn't break any existing tests.

    Let me do a final summary of my changes:

  83. MiniMax Assistant

    me delete the .snap.new files generated by my temp tests:

  84. MiniMax Assistant

    my changes are clean. Let me show the final diff one more time:

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.