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 inspect the repository structure and locate the extract-function implementation and its tests, then reproduce the reported selection behavior before changing it.
- Assistant
rgis unavailable, so I’ll usegrep/findto identify the relevant language-server modules and test fixtures. - Assistant
I found the implementation and a substantial focused test suite. I’ll read the extraction range-selection logic and nearby tests, especially the existing partial-selection case, to understand why the range expands to the whole function.
- Assistant
The action’s output stage trusts a visitor-produced
ExtractedValue; the bug is likely in containment/overlap checks while visiting statements. I’ll locate allExtractFunctionvisitor methods and range helper predicates, then inspect snapshots to understand exact expected edits. - Assistant
I’ll inspect the visitor and extracted-value merging logic in full, including how top-level functions and nested statements are traversed.
- Assistant
The previous output was truncated at the critical methods. I’ll retrieve narrower ranges around
can_extract_expression, module function traversal, andvisit_typed_statement. - Assistant
A likely cause is Gleam’s typed AST representation of
use: a callback anonymous function contains all following statements. Even when the enclosingusestatement is correctly skipped because the selection lies inside its continuation, generic expression traversal may select that synthetic callback and thereby capture the whole continuation—or nested callbacks can expand it further. I’ll confirm helper semantics and inspect snapshots involving extraction insideusebodies. - Assistant
I’ll read the exact range predicates and search all extraction tests containing
use, since endpoint inclusivity can determine whether the synthetic callback is considered fully selected. - Assistant
The strict predicate fails when the selection shares the continuation’s end (the function’s closing tail), so a selection starting inside a synthetic
usecallback but ending at its final expression is treated as selecting that entire callback. That matches the report: each outerusecallback ends at the same tail, and the first such callback wins, expanding extraction back to the start of the function continuation. I’ll inspectFunctionLiteralKind::Usedefinitions/locations and related extraction formatting before choosing whether to special-case synthetic callbacks or adjust containment boundaries more generally. - Assistant
I’ll inspect how the type checker constructs the
usecallback’s source span. This will establish whether matching onFunctionLiteralKind::Useis safe and whether its span deliberately includes only the continuation statements. - Assistant
The callback span is exactly from the first statement after each
usethrough the sequence end. The reported selection therefore shares the callback’s end but not its start. I’ll inspect the resulting typed statement shape and visitor traversal to ensure skipping a partially selected synthetic callback still reaches and groups its body statements correctly. - Assistant
The typed
Usenode preserves both the sourceuselocation and a call spanning the rest of the sequence; the statement’slocation()choice is crucial. I’ll inspect that implementation and the source-span-to-LSP endpoint conversion to map the report exactly. - Assistant
I’ll broaden the search to generic AST implementations, since Rust type aliases can hide the concrete
Statementimplementation. - Assistant
I’ll read the generic statement methods and typed
Useexpression locations. - Assistant
The root cause is confirmed in
TypedStatement::location(): ausestatement spans from its own line through the final continuation expression. The extractor uses strict containment, so a selection inside that continuation that shares the tail endpoint is misclassified as selecting the outeruse. Foruse, selection intent should be determined by whether the selection reaches theusestatement’s start; if it starts later, traversal must continue into the callback body. I’ll separateUsefromAssertand implement that rule with an explanatory comment. - Assistant
The edit is formatted by construction and passes
git diff --check, but no Rust toolchain is configured. I’ll inspect the project’s CI/toolchain requirements and installed toolchains, then configure the matching toolchain so I can compile and test. - Assistant
CI uses stable Rust. I’ll install stable with
rustfmt, format the change, then run the focused language-server extraction tests. - Assistant
The toolchain downloaded successfully, but this environment’s rustup shim is looking under a mismatched home directory. I’ll inspect the Rust environment paths and invoke the installed binaries directly or set
RUSTUP_HOME/CARGO_HOMEcorrectly. - Assistant
I’ll bypass the broken
/usr/local/cargoshim by prepending the installed toolchain’sbindirectory, then format and run the focused test set. - Assistant
Dependencies are now available; the only failure was the package’s hyphenated name. I’ll rerun the focused extraction tests with the correct package identifier.
- Assistant
The existing focused suite passes. To verify the actual regression without modifying tests, I’ll use a temporary Gleam project and exercise the built language server over JSON-RPC. First I’ll identify the CLI package/binary and LSP invocation, then create a self-contained source equivalent with nested
usestatements. - Assistant
I’ll build the
gleambinary and create a temporary project whose function has the same nested-use AST shape. Then a small temporary Python client will initialize the LSP, open the document, request “Extract function” over the intended tail range, and print the returned edits. - Assistant
The binary built; only the CLI’s directory flag placement was wrong. I’ll validate the temporary project from its working directory, then send the LSP request with selection from
let toml_paththrough the finalgleam_toml. - Assistant
I’ll run a noninteractive temporary JSON-RPC client that handles LSP framing and server requests, then capture the returned workspace edit. This reproduces behavior through the same public path Neovim uses.
- Assistant
The public reproduction still shows the bug, revealing a second layer: after correctly skipping the
Usestatement, generic traversal visits its desugared call expression, whose span also covers the entire continuation, and selects that call before reaching callback statements. I’ll inspectvisit_typed_useandTypedUsecallback accessors, then make the extractor traverse only the continuation callback when selection starts after theuseline. - Assistant
The shell remained in the temporary project, so I’ll rerun the source inspection from the repository root.
- Assistant
The safe distinction is the original
use_.location, which covers only the writtenuseline. When the selection starts after that span, it is unambiguously in the continuation. I’ll overridevisit_typed_usefor that case: bypass the synthetic full-sequence call and function wrapper, visit the callback body statements directly, and preserve tail-position tracking. Selections on theuseline or its right-hand side will retain existing traversal. - Assistant
TypedUseis already imported directly, so I’ll use that established type name, compile, rerun the focused suite, rebuild the CLI, and repeat the exact JSON-RPC reproduction. - Assistant
The public LSP reproduction now replaces exactly lines 10–16 and leaves both preceding
usestatements intact, confirming the fix. I’ll run the complete language-server test suite (not only extraction tests), then inspect the final diff for scope, formatting, and accidental files. - Assistant
Final checklist:
- If an error was reported, I successfully reproduced it. I exercised
gleam lspvia JSON-RPC on a temporary project with nestedusestatements and a tail selection. Before the complete fix, the edit incorrectly replaced from the firstusethrough the function tail. - If an error was reported, I confirmed the fix resolves it. The same LSP request now replaces only the selected
let toml_paththrough the final expression, preserving both precedingusestatements and extracting only that tail. - I thought about edge cases. The fix distinguishes the written
usespan from its synthetic callback/call span, retains existing traversal for selections on theuseline or RHS, directly traverses continuation statements, handles nestedusecallbacks recursively, and preserves/restores tail-position state. - All 18 focused extract-function tests passed, followed by the complete suite: 1,537 passed, 0 failed. Formatting and also pass.
- If an error was reported, I successfully reproduced it. I exercised
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.