Good, I can see the expected behavior. The selection from let c to * d extracts only those statements, not let a or let b. This is working correctly.
Now let me think about the bug more carefully. The issue is specifically with use expressions. Let me create a test case that reproduces the issue to understand it better.
The key difference between the working test case and the reported issue is:
- The working test case has simple
let assignments
- The reported issue has
use expressions before the selection
Let me think about what's different when there are use expressions before the selection.
When we visit a use expression, we also visit its call expression through ast::visit::visit_typed_statement. And the call expression is the desugared call, which includes a lambda with the body.
So when we visit the first use statement:
- We visit the
use statement
can_extract_statement returns false (no overlap)
- We call
ast::visit::visit_typed_statement, which calls visit_typed_use
visit_typed_use visits use_.call
use_.call is a Call expression with a lambda argument
- When we visit the
Call expression, we check can_extract_expression
Wait, let me look at what happens when we visit a Call expression. The Call expression is visited through visit_typed_expr.
fn visit_typed_expr(&mut self, expression: &'ast TypedExpr) {
if self.function.is_none() {
if self.can_extract_expression(expression) {
self.function = Some(ExtractedFunction::new(ExtractedValue::Expression(
expression,
)));
}
}
// ...
ast::visit::visit_typed_expr(self, expression);
// ...
}
For the Call expression (which is use_.call), we check can_extract_expression:
fn can_extract_expression(&self, expression: &TypedExpr) -> bool {
let expression_range = self.edits.src_span_to_lsp_range(expression.location());
let selected_range = self.params.range;
if !overlaps(expression_range, selected_range) {
return false;
}
match expression {
// ... for Call:
TypedExpr::Call { .. } => !completely_within(selected_range, expression_range),
}
}
The Call expression's location includes the lambda body! Because the call field is the desugared call, which includes the lambda.
So expression.location() for the Call expression would span from the start of the call to the end of the lambda body. And the selection overlaps with the lambda body (because the selected statements are inside the lambda).
So overlaps(expression_range, selected_range) returns true.
And completely_within(selected_range, expression_range) checks if the selection is completely within the Call expression's range.
The Call expression's range spans from the start of result.try( to the end of the lambda body. The selection starts from a comment before let toml_path and ends at a comment after the pipeline.
Now, is the selection completely within the Call expression's range?
The selection starts from a comment BEFORE let toml_path. And let toml_path is inside the lambda body. So the selection's start is inside the lambda body.
But wait, the selection might start from a position that's BEFORE the lambda body. Let me think about this.
The first use statement is:
use priv <- result.try(
application.priv_directory("gleeps")
|> result.replace_error(FailedToFindPrivDirectory),
)
The desugared call would be:
result.try(
application.priv_directory("gleeps")
|> result.replace_error(FailedToFindPrivDirectory),
fn(priv) {
// rest of the function body
}
)
The Call expression's location would span from result.try( to the end of the lambda body (which is the end of the function).
Now, the selection starts from // replace $PROJECT_NAME placeholder in the gleam.toml, which is inside the lambda body. So the selection is completely within the Call expression's range!
So completely_within(selected_range, expression_range) returns true, and !completely_within returns false. So can_extract_expression returns false for the Call expression.
Good, so the Call expression is not extracted. But we continue visiting its children...
When we visit the Call expression's arguments, we visit the lambda (which is a Fn expression). And when we visit the Fn expression:
fn visit_typed_expr(&mut self, expression: &'ast TypedExpr) {
if self.function.is_none() {
if self.can_extract_expression(expression) {
self.function = Some(ExtractedFunction::new(ExtractedValue::Expression(
expression,
)));
}
}
// If the expression is a function, then the last statement location
// needs to be updated accordingly
let last_statement_location = self.last_statement_location;
if let TypedExpr::Fn { body, .. } = expression {
self.last_statement_location = Some(body.last().location());
}
ast::visit::visit_typed_expr(self, expression);
self.last_statement_location = last_statement_location;
}
For the Fn expression, we check can_extract_expression:
The Fn expression's location includes the lambda body. And the selection overlaps with the lambda body. So overlaps returns true.
And completely_within(selected_range, expression_range) checks if the selection is completely within the Fn expression's range.
The Fn expression's range is the lambda's range, which includes the lambda body. And the selection is within the lambda body. So completely_within returns true, and !completely_within returns false.
So can_extract_expression returns false for the Fn expression.
But then, we update last_statement_location:
if let TypedExpr::Fn { body, .. } = expression {
self.last_statement_location = Some(body.last().location());
}
This sets last_statement_location to the last statement in the lambda body. And the lambda body includes all statements from the second use statement to the pipeline.
So last_statement_location is set to the pipeline's location.
And then we visit the Fn expression's body, which is a block of statements.
When we visit the block, visit_typed_expr_block is called:
fn visit_typed_expr_block(
&mut self,
location: &'ast SrcSpan,
statements: &'ast [TypedStatement],
) {
let last_statement_location = self.last_statement_location;
self.last_statement_location = statements.last().map(|last| last.location());
ast::visit::visit_typed_expr_block(self, location, statements);
self.last_statement_location = last_statement_location;
}
Wait, this also updates last_statement_location to the last statement in the block. So while we're visiting the block, last_statement_location is the pipeline's location.
And then, for each statement in the block, visit_typed_statement is called.
OK so this all seems correct. The issue must be somewhere else.
Wait, I just realized something. The function body in the typed AST might NOT be a flat list of statements. Instead, it might be a single block that contains all statements, including use statements.
And each use statement's body is the REST of the statements in that block. So the AST structure might be:
Function {
body: [
Use {
call: Call {
args: [..., Fn {
body: [
Use {
call: Call {
args: [..., Fn {
body: [
Assignment(let toml_path = ...),
Use { ... },
Assignment(let gleam_toml = ...),
Expression(pipeline)
]
}}
},
...
},
...
]
}}
},
...
}
]
}
So function.body is a list with a single Use statement. And the rest of the statements are nested inside the Use statement's call expression.
If this is the case, then when we visit the function body, we only visit the first Use statement. And the rest of the statements are visited through the Use statement's call expression.
And function.body.last() would be the first Use statement!
So self.last_statement_location = function.body.last().map(|last| last.location()); would set last_statement_location to the location of the first Use statement, not the pipeline!
Wait, but that would cause issues with tail position detection. The pipeline would not be detected as tail position.
Actually, let me look at this more carefully. The visit_typed_function function sets:
self.last_statement_location = function.body.last().map(|last| last.location());
And then it calls ast::visit::visit_typed_function(self, function).
ast::visit::visit_typed_function would visit the function body, which is a list of statements. If the function body has only the first Use statement, then we only visit that statement.
But when we visit the Use statement, we also visit its call expression, which includes the lambda body. And when we visit the lambda body, we visit the statements inside it.
And visit_typed_expr_block updates last_statement_location to the last statement in the block.
So while we're visiting the lambda body, last_statement_location is the last statement in the lambda body (which includes the second Use statement and the rest).
But wait, the lambda body of the first Use statement includes the second Use statement, which has its own lambda body. So the last statement in the first Use statement's lambda body is... the second Use statement? Or the last statement in the second Use statement's lambda body?
Actually, looking at the structure:
Function {
body: [
Use1 {
call: Call1 {
args: [..., Fn1 {
body: [
Use2 {
call: Call2 {
args: [..., Fn2 {
body: [
Assignment1,
Use3,
Assignment2,
Expression(pipeline)
]
}}
},
...
}
]
}}
},
...
}
]
}
The body of Fn1 is [Use2]. So statements.last() is Use2. And last_statement_location would be Use2's location.
But the pipeline is inside Fn2's body, not Fn1's body. So while we're visiting Fn1's body, last_statement_location would be Use2's location, not the pipeline's location.
Hmm, but that's not right either. The tail position is determined by whether a statement is the last in its containing block. And the pipeline is the last statement in Fn2's body, so it should be in tail position within Fn2's body.
OK so the tail position detection might work correctly within each lambda body.
But the issue is that the extraction location spans the entire function body. Let me think about why.
Actually, I think I need to focus on the specific issue. The user says that when selecting from a comment to another comment (which spans statements 3-6), the entire function body (statements 1-6) is extracted.
The extraction is based on the location field of ExtractedFunction::value. If the location spans from statement 1 to statement 6, then the entire function body would be extracted.
So the question is: why does the location span from statement 1?
One possibility: when we set self.function, we use the location of the first Use statement's call expression, which spans the entire rest of the function.
But wait, when do we set self.function? We set it when we encounter a statement or expression that overlaps with the selection.
When we visit the function body:
- We visit statement 1 (Use1).
can_extract_statement returns false (statement 1's location doesn't overlap with selection).
- We call
ast::visit::visit_typed_statement, which visits use_.call.
use_.call is a Call expression. can_extract_expression is called.
- The Call expression's location includes the lambda body, which includes the selection.
overlaps returns true.
completely_within checks if the selection is completely within the Call expression.
Now, the selection starts from a comment BEFORE let toml_path. And let toml_path is inside Fn2's body, which is inside Fn1's body.
The Call expression's location spans from the start of Call1 to the end of Fn1's body. And Fn1's body is [Use2].
So the Call expression's location spans from result.try( to the end of Use2.
And the selection starts from a comment AFTER Use2. So the selection is NOT within the Call expression's location!
Wait, but Use2's location might span more than I think. Let me re-read the Use struct's location documentation:
This is the location of the whole use line, starting from the use keyword and ending with the function call on the right hand side of <-.
So Use2's location spans from use to the end of result.try(...) (before the lambda). And the selection starts after Use2's closing ).
So the Call expression's location (which spans from result.try( to the end of Use2)` would NOT include the selection.
Wait, but the Call expression's location should include the lambda body! Because the Call expression is the desugared call, which includes the lambda.
Let me think about this more carefully. The call field of the Use struct is the desugared call:
result.try(..., fn(priv) {
Use2
})
So call.location() would span from result.try( to the end of the lambda body (which is Use2).
But Use2 is a single statement (the second Use statement), not the entire rest of the function body. The second Use statement has its own call expression with its own lambda body.
So the first Use statement's call expression's lambda body is [Use2], which is a single statement. And the second Use statement's call expression's lambda body is [Assignment1, Use3, Assignment2, Expression].
So the first Use statement's call expression's location spans from result.try( to the end of Use2. And Use2's location is the use line use _ <- result.try(...).
So the first Use statement's call expression's location spans from result.try( to the closing ) of Use2's call.
And the selection starts after the closing ) of Use2's call. So the selection is NOT within the first Use statement's call expression's location.
So overlaps would return false, and can_extract_expression would return false for the first Use statement's call expression.
Hmm, so that's not the issue either.
Wait, let me re-think this. I might have the wrong understanding of the AST structure.
Actually, I think the AST structure might be different. Let me think about how Gleam's compiler represents use expressions.
In Gleam, when you have:
fn foo() {
use a <- expr1
use b <- expr2
let c = 1
}
This is desugared to:
fn foo() {
expr1(fn(a) {
expr2(fn(b) {
let c = 1
c
})
})
}
But in the typed AST, the function body might still be represented as a list of statements:
body: [
Use1 { call: Call1, ... },
Use2 { call: Call2, ... },
Assignment(let c = 1)
]
And each Use statement's call field is the desugared call, which includes a lambda with the body.
But what is the body of the lambda? Is it the rest of the function body (all subsequent statements), or just the next statement?
I think it's the rest of the function body. So for Use1, the lambda body would be [Use2, Assignment]. And for Use2, the lambda body would be [Assignment].
If that's the case, then the first Use statement's call expression's location would span from result.try( to the end of the function body (the last statement).
And the selection (which is within the function body) would be completely within the call expression's location.
So completely_within would return true, and can_extract_expression would return false for the Call expression.
OK so that's still not the issue.
Hmm, let me think about this differently. Maybe the issue is not with expressions, but with statements.
When we visit the function body, we visit each statement. But if the function body has only the first Use statement (because the rest are nested inside), then we only visit the first Use statement.
And can_extract_statement returns false for the first Use statement.
But then, we call ast::visit::visit_typed_statement, which visits use_.call. And use_.call includes the lambda body.
And when we visit the lambda body, we visit the statements inside it. And for those statements, we check can_extract_statement.
For statement 3 (let toml_path), can_extract_statement returns true. So we set self.function to Statements.
But wait, what is statement.location() for statement 3? It's the location of let toml_path = ....
And when we merge subsequent statements, we use statement.location() for each of them.
So the extraction location should be the merged span of statements 3-6, not the entire function body.
Unless... the issue is that we're not correctly identifying statements 1 and 2 as NOT overlapping with the selection.
Actually, let me re-think this. The issue might be that when we visit statements through the lambda body, we're visiting the same AST nodes as the top-level statements. But the top-level statements might not be visited at all (if the function body only has the first Use statement).
Wait, but the test cases show that we can extract individual statements from a function. So the function body must have all statements, not just the first Use statement.
Let me re-think the AST structure. I think the function body is a flat list of all statements:
body: [
Use1,
Use2,
Assignment(let toml_path = ...),
Use3,
Assignment(let gleam_toml = ...),
Expression(pipeline)
]
And each Use statement's call field is the desugared call, which includes a lambda with the body.
But what is the body of the lambda? I think it's a reference to the subsequent statements in the function body.
So Use1.call would be:
Call {
fun: result.try,
args: [
...,
Fn {
body: block of statements from Use2 to Expression(pipeline)
}
]
}
And the body of the Fn expression is a block that contains all subsequent statements.
But these statements are the same AST nodes as the ones in the function body. So they're not duplicated; they're just referenced from multiple places.
If this is the case, then when we visit the function body, we visit all 6 statements. And when we visit Use1.call, we also visit all statements from 2-6 through the lambda body.
So each statement is visited twice: once as a top-level statement, and once through the lambda body of Use1.
But the extraction logic only sets self.function once (for the first overlapping statement), and merges subsequent overlapping statements.
So the extraction location should be correct.
OK I'm really stuck. Let me try to reproduce the issue by looking at the test cases more carefully.
Actually, let me look at the test case extract_function_partially_selected more carefully. This test case selects from a = to c =, which spans let a, let b, and let c. And the expected output extracts those three statements.
The key difference is that this test case doesn't have any use expressions. So maybe the issue is specific to use expressions.
Let me create a test case that has use expressions before the selection and see if I can reproduce the issue.
Actually, let me look at the code more carefully. I think the issue might be with how can_extract_statement works for Use statements.
Looking at the code:
ast::Statement::Use(_) | ast::Statement::Assert(_) => {
!completely_within(selected_range, statement_range)
}
This returns true if the selection is NOT completely within the Use statement's range. But this is only checked if overlaps(statement_range, selected_range) is true.
Now, what is the Use statement's range? It's statement.location(), which is the location field of the Use struct.
But wait, I just realized something. The statement.location() for a Use statement is the location field, which is:
This is the location of the whole use line, starting from the use keyword and ending with the function call on the right hand side of <-.
But what if this location includes the lambda body? Let me check by looking at how the Use struct is created.
Actually, I think the location field is set when parsing the source code, before type checking. So it would be the location of the use line in the source code, not including the lambda body (which is added during desugaring).
So statement.location() for a Use statement would NOT include the lambda body. It would just be the use line.
OK so I think can_extract_statement should return false for Use statements that don't overlap with the selection.
Hmm, let me try a different approach. Let me look at the can_extract_statement function and see if there's a bug there.
Actually, wait. I just realized something important. Let me re-read the visit_typed_statement function:
fn visit_typed_statement(&mut self, statement: &'ast TypedStatement) {
let statement_location = statement.location();
if self.can_extract_statement(statement) {
// ... update self.function ...
}
ast::visit::visit_typed_statement(self, statement);
}
The key is that ast::visit::visit_typed_statement is called AFTER we check can_extract_statement. This means we always visit the children of the statement.
For a Use statement, the children include use_.call. And when we visit use_.call, we visit the Call expression, which includes the lambda body.
But wait, what if the issue is with how we handle the ExtractedValue::Use case?
Looking at the code:
TypedStatement::Use(use_) => {
Some(ExtractedFunction::new(ExtractedValue::Use {
location: use_.call.location(),
type_: statement.type_(),
}))
}
When we first encounter a Use statement that overlaps with the selection, we set self.function to ExtractedValue::Use with location: use_.call.location().
And use_.call.location() is the location of the desugared call, which includes the lambda body. So this location spans from the start of the call to the end of the lambda body (which might be the end of the function).
So if the first Use statement that overlaps with the selection is Use3 (the one inside the selection), we would set self.function to ExtractedValue::Use with location: use3.call.location().
And use3.call.location() would span from the start of result.try( to the end of the lambda body (which is the rest of the function body).
So the extraction location would span from result.try( to the end of the function!
And when we extract, we would replace all the code at that location with the function call.
But wait, in the issue, the first statement that overlaps with the selection is let toml_path = ..., which is an Assignment, not a Use statement. So we would set self.function to ExtractedValue::Statements, not ExtractedValue::Use.
Unless... the visitor visits Use3 before let toml_path.
Let me think about the order of visiting. When we visit the function body, we visit statements in order:
- Use1
- Use2
- Assignment (let toml_path)
- Use3
- Assignment (let gleam_toml)
- Expression (pipeline)
For Use1, can_extract_statement returns false. We then visit use1.call, which includes the lambda body with statements 2-6.
In the lambda body, we visit Use2, Assignment, Use3, Assignment, Expression.
For Use2, can_extract_statement returns false. We then visit use2.call, which includes the lambda body with statements 3-6.
In the inner lambda body, we visit Assignment, Use3, Assignment, Expression.
For Assignment (let toml_path), can_extract_statement returns true. We set self.function to Statements.
Wait, but at this point, we're visiting through Use1's lambda body, then Use2's lambda body, then the inner statements. And the first statement that overlaps is let toml_path.
But then, we continue visiting through the inner lambda body. We visit Use3.
For Use3, can_extract_statement returns true (it overlaps with the selection). And self.function is already Statements. So we merge Use3's location.
Some(ExtractedFunction {
value: ExtractedValue::Statements { location, position: extracted_position },
..
}) => {
*location = location.merge(&statement_location);
*extracted_position = position;
}
We merge Use3's location into the extraction location. And Use3's location is the use line use gleam_toml <- result.try(...).
So the extraction location would be the merged span of let toml_path and use gleam_toml.
But wait, what is Use3's statement_location? It's statement.location(), which is the location field of the Use struct, not use_.call.location().
So Use3's statement_location is the use line, not including the lambda body.
OK so the extraction location should be correct. It should span from let toml_path to the pipeline.
Hmm, but the issue says the entire function body is extracted. So there must be something else going on.
Actually, wait. I just realized something. Let me re-read the code for handling Use statements in visit_typed_statement:
Some(ExtractedFunction {
value: ExtractedValue::Use { location, .. },
..
}) if location.contains_span(statement_location) => {}
// Otherwise it means we're extracting multiple statements
// _including_ some use expression, we fallback to extracting
// multiple statements
Some(ExtractedFunction {
value: value @ ExtractedValue::Use { .. },
..
}) => {
*value = ExtractedValue::Statements {
location: value.location().merge(&statement_location),
position,
};
}
The first case checks if the statement is within the Use's call location (location.contains_span(statement_location)). If so, we don't change anything.
The second case converts from Use to Statements and merges the location.
But what if self.function is Statements and we encounter a Use statement? Looking at the code:
Some(ExtractedFunction {
value:
ExtractedValue::Statements {
location,
position: extracted_position,
},
..
}) => {
*location = location.merge(&statement_location);
*extracted_position = position;
}
We merge the Use statement's statement_location into the extraction location. And statement_location is statement.location(), which is the Use statement's location field.
So we merge the Use statement's use line, not its call location. This should be correct.
But wait, there's another case. What if we first set self.function to ExtractedValue::Use (for Use3), and then we encounter another statement?
For example, if Use3 is visited before let toml_path, and Use3 overlaps with the selection, we would set self.function to ExtractedValue::Use.
But let toml_path is visited before Use3 (because it's earlier in the function body). So self.function should be set to Statements first.
Unless... the visitor visits Use3 before let toml_path through the lambda body of Use1 or Use2.
Actually, no. The visitor visits statements in order within each lambda body. So within Use2's lambda body, we visit let toml_path before Use3.
OK so I still don't see how the entire function body would be extracted.
Let me try yet another approach. Let me look at the visit_typed_expr function and see if there's a bug with how expressions are handled.
fn visit_typed_expr(&mut self, expression: &'ast TypedExpr) {
if self.function.is_none() {
if self.can_extract_expression(expression) {
self.function = Some(ExtractedFunction::new(ExtractedValue::Expression(
expression,
)));
}
}
let last_statement_location = self.last_statement_location;
if let TypedExpr::Fn { body, .. } = expression {
self.last_statement_location = Some(body.last().location());
}
ast::visit::visit_typed_expr(self, expression);
self.last_statement_location = last_statement_location;
}
I see that when we visit a Fn expression, we update last_statement_location to the last statement in the lambda body.
But what if we're visiting the Fn expression of the first Use statement, and the lambda body includes all subsequent statements? Then last_statement_location would be set to the pipeline's location.
And then, when we visit statements in the lambda body, we check is_in_tail_position by comparing with last_statement_location.
If a statement's location equals last_statement_location, it's in tail position.
So the pipeline would be detected as tail position. And the extraction position would be StatementPosition::Tail.
But this is correct behavior. The pipeline IS in tail position.
OK let me try one more thing. Let me look at how the extraction handles ExtractedValue::Use.
When self.function is ExtractedValue::Use:
ExtractedValue::Use { location, type_ } => self.extract_code_in_tail_position(
location,
location,
type_,
extracted.parameters,
end,
),
We call extract_code_in_tail_position with location as both the replacement location and the code location.
And location is use_.call.location(), which spans from the call to the end of the lambda body.
So if self.function is ExtractedValue::Use for the first Use statement, the extraction location would span the entire function body!
But when would self.function be set to ExtractedValue::Use for the first Use statement?
Only if can_extract_statement returns true for the first Use statement. And that only happens if the selection overlaps with the Use statement.
But in the issue, the selection starts after the first two Use statements. So can_extract_statement should return false.
Unless... the first Use statement's location includes more than I think.
Actually, I wonder if the issue is with how the location field of the Use struct is set. What if it includes the entire lambda body?
Let me check by looking at how the Use struct is created during parsing or type checking.
Actually, I think I should look at the location field more carefully. The documentation says:
This is the location of the whole use line, starting from the use keyword and ending with the function call on the right hand side of <-.
"ending with the function call on the right hand side of <-". This is the ORIGINAL function call in the source code, before desugaring.
But what if the type checker updates this location to include the lambda body?
Let me check if the location field is updated during type checking.
Actually, I think I need to look at the code that creates the typed Use struct.
Let me search for where TypedUse is created.
Hmm, this is getting complicated. Let me try a different approach. Let me run the existing tests to see if they pass, and then create a test case that reproduces the issue.
Actually wait, I just had an insight. Let me re-read the issue description:
The user says:
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)
}
The extracted function is called with function(target, user_id). This means the extraction identified target and user_id as parameters.
But if the entire function body was extracted, then ALL variables defined in the function would be used, including priv (from the first use statement). But the extracted function only takes target and user_id.
So maybe the extraction didn't actually include the first two use statements in the extracted code. Maybe the extraction location was correct, but the REPLACEMENT was wrong.
Let me re-read the issue:
It will extract the entire function content into a new function leaving:
fn prepare_project_structure(...) {
function(target, user_id)
}
So the function body is replaced with function(target, user_id). And the extracted function contains... what? The issue says "the entire function content", which might mean the extracted function contains all the code.
But the expected output shows:
fn prepare_project_structure(...) {
// get the priv dir
use priv <- result.try(...)
// copy the base project
use _ <- result.try(...)
// replace $PROJECT_NAME
function(target, user_id)
}
fn function(target, user_id) -> Result(Nil, SubmitError) {
let toml_path = ...
use gleam_toml <- result.try(...)
let gleam_toml = ...
simplifile.write(toml_path, gleam_toml)
|> result.replace_error(...)
}
So the expected behavior is:
- The first two use statements remain in the original function
- The selected portion (from
let toml_path to the pipeline) is extracted into a new function
- The selected portion in the original function is replaced with
function(target, user_id)
But the actual behavior is:
- The ENTIRE function body is replaced with
function(target, user_id)
- The extracted function contains ALL the code (from
use priv to the pipeline)
Wait, but the extracted function is called with function(target, user_id), which only has target and user_id as parameters. If the extracted function included the first two use statements, it would also need priv as a parameter (since priv is used in the second use statement).
Unless... priv is not a parameter because it's defined inside the extracted function (by the first use statement).
Hmm, but if the extracted function includes use priv <- result.try(...), then priv is defined inside the function, not outside. So it wouldn't be a parameter.
OK so the extracted function would be:
fn function(target: TargetPath, user_id: uuid.Uuid) -> Result(Nil, SubmitError) {
use priv <- result.try(...)
use _ <- result.try(...)
let toml_path = ...
use gleam_toml <- result.try(...)
let gleam_toml = ...
simplifile.write(toml_path, gleam_toml)
|> result.replace_error(...)
}
And the original function would be:
fn prepare_project_structure(target, user_id) -> Result(Nil, SubmitError) {
function(target, user_id)
}
So the issue is that the first two use statements are included in the extracted function, even though they weren't selected.
Now, how does the extraction determine what code to include? It uses the location field.
If the location spans from the first use statement to the pipeline, then all the code would be extracted.
So the question is: why does the location span from the first use statement?
I think the issue might be with how the location is built when we encounter a Use statement inside the selection.
When we visit Use3 (the one inside the selection), can_extract_statement returns true. And self.function is already Statements. So we merge Use3's location:
*location = location.merge(&statement_location);
Where statement_location is statement.location(), which is Use3's location field.
But wait, what if Use3's location field is NOT the use line, but something else?
Actually, let me re-read the documentation:
This is the location of the whole use line, starting from the use keyword and ending with the function call on the right hand side of <-.
So it's the use line, from use to the end of the call on the right-hand side. This should be just the use line, not including the lambda body.
But what if the "function call on the right hand side of <-" is the DESUGARED call, which includes the lambda?
Hmm, the documentation says "the function call on the right hand side of <-". In the source code, the right-hand side of <- is result.try(...), which doesn't include the lambda. The lambda is added during desugaring.
So I think the location field should be just the use line, not including the lambda body.
OK let me try yet another approach. Let me look at the right_hand_side_location field of the Use struct:
/// This is the location of the expression on the right hand side of the use
/// arrow.
///
/// ```gleam
/// use a <- result.try(result)
/// ^^^^^^^^^^^^^^^^^^
/// ```
///
pub right_hand_side_location: SrcSpan,
This is specifically the location of the expression on the right-hand side of <-. So it's just result.try(result), not including the lambda.
And the location field is:
This is the location of the whole use line, starting from the use keyword and ending with the function call on the right hand side of <-.
So location spans from use to the end of right_hand_side_location. This should be the use line, not including the lambda body.
OK so I think the location field is correct. It doesn't include the lambda body.
But then, why is the entire function body being extracted?
Let me think about this more. When we merge locations, we use location.merge(&statement_location). And statement_location is statement.location(), which is the location field.
So the merged location should be the union of all overlapping statements' location fields. This should be from let toml_path to the pipeline.
Unless... there's a bug in how the extraction handles ExtractedValue::Use.
Wait, let me re-read the code:
match &mut self.function {
None => {
self.function = match statement {
// ...
TypedStatement::Use(use_) => {
Some(ExtractedFunction::new(ExtractedValue::Use {
location: use_.call.location(),
type_: statement.type_(),
}))
}
}
}
// ...
}
When we first encounter a Use statement that overlaps with the selection, we set self.function to ExtractedValue::Use with location: use_.call.location().
And use_.call.location() is the location of the desugared call, which includes the lambda body!
So if the FIRST statement that overlaps with the selection is a Use statement, the extraction location would span from the call to the end of the lambda body (which might be the end of the function).
In the issue, the selection includes Use3 (use gleam_toml <- result.try(...)). So Use3 overlaps with the selection.
But the first statement that overlaps with the selection is let toml_path, which is an Assignment. So self.function would be set to Statements first.
Unless... the visitor visits Use3 before let toml_path.
Let me think about the order of visiting.
When we visit the function body, we visit statements in order:
- Use1
- Use2
- Assignment (let toml_path)
- Use3
- Assignment (let gleam_toml)
- Expression (pipeline)
For Use1, can_extract_statement returns false. We then visit use1.call, which includes the lambda body with statements 2-6.
In the lambda body, we visit:
- Use2:
can_extract_statement returns false. Visit use2.call, which includes the lambda body with statements 3-6.
- In the inner lambda body, we visit:
- Assignment (let toml_path):
can_extract_statement returns true. Set self.function to Statements.
- Use3:
can_extract_statement returns true. Merge Use3's location.
- Assignment (let gleam_toml):
can_extract_statement returns true. Merge.
- Expression (pipeline):
can_extract_statement returns true. Merge.
So far so good. The extraction location should be from let toml_path to the pipeline.
But then, after exiting the inner lambda body, we exit the outer lambda body. And then we continue visiting the function body.
For Use2, can_extract_statement returns false (we already visited it through the lambda body, but its location doesn't overlap).
For Assignment (let toml_path), can_extract_statement returns true. And self.function is already Statements. So we merge.
For Use3, can_extract_statement returns true. Merge.
For Assignment (let gleam_toml), can_extract_statement returns true. Merge.
For Expression (pipeline), can_extract_statement returns true. Merge.
So the extraction location should still be from let toml_path to the pipeline.
Hmm, but wait. There's something I might have missed. Let me look at the code for merging Use statements:
Some(ExtractedFunction {
value: ExtractedValue::Use { location, .. },
..
}) if location.contains_span(statement_location) => {}
Some(ExtractedFunction {
value: value @ ExtractedValue::Use { .. },
..
}) => {
*value = ExtractedValue::Statements {
location: value.location().merge(&statement_location),
position,
};
}
When self.function is Use and we encounter another statement, we convert to Statements and merge.
But value.location() for Use is use_.call.location(), which includes the lambda body!
So if self.function is Use for Use3, and we merge with another statement, the merged location would be:
value.location().merge(&statement_location)
Where value.location() is use3.call.location(), which spans from result.try( to the end of the lambda body.
And statement_location is the location of the next statement.
So the merged location would be from result.try( (of Use3's call) to the end of the lambda body.
But the lambda body of Use3's call might span the rest of the function!
So if self.function is set to Use for Use3, the extraction location would span from Use3's call to the end of the function, which might include more than expected.
But wait, in the issue, the first statement that overlaps with the selection is let toml_path, which is an Assignment. So self.function would be set to Statements first, not Use.
Unless... there's a case where Use3 is visited before let toml_path.
Actually, let me re-think the visitor order. When we visit the function body, we visit statements in order. But when we visit a Use statement, we also visit its call expression, which includes the lambda body.
So the visitor order is:
- Visit Use1 (top-level)
a.
can_extract_statement returns false
b. Visit use1.call (Call expression)
- Visit the Call's arguments, including the lambda
- Visit the lambda (Fn expression)
- Update
last_statement_location to the last statement in the lambda body
- Visit the lambda body (block)
- Visit Use2
a.
can_extract_statement returns false
b. Visit use2.call
- Visit the Call's arguments, including the lambda
- Visit the lambda (Fn expression)
- Update
last_statement_location
- Visit the lambda body (block)
- Visit Assignment (let toml_path)
can_extract_statement returns true
- Set
self.function to Statements
- Visit Use3
can_extract_statement returns true
- Merge Use3's location (Use3's
statement_location)
- Visit Assignment (let gleam_toml)
can_extract_statement returns true
- Merge
- Visit Expression (pipeline)
can_extract_statement returns true
- Merge
- Visit Use2 (top-level)
a.
can_extract_statement returns false
b. Visit use2.call (already visited, but visited again)
...
- Visit Assignment (let toml_path) (top-level)
a.
can_extract_statement returns true
b. Merge
- Visit Use3 (top-level)
a.
can_extract_statement returns true
b. Merge Use3's location
OK so the order of visiting Use3 through the lambda body and as a top-level statement is:
- Visit Use3 through Use2's lambda body (step 1.b...): merge Use3's
statement_location
- Visit Use3 as top-level statement (step 4): merge Use3's
statement_location
Both times, we merge statement_location, which is Use3's location field (the use line).
So the extraction location should be the merged span of let toml_path, Use3, let gleam_toml, and the pipeline.
This should be correct!
Hmm, but the issue says the entire function body is extracted. Let me think about what could cause this.
Actually, wait. Let me re-read the merging code:
Some(ExtractedFunction {
value:
ExtractedValue::Statements {
location,
position: extracted_position,
},
..
}) => {
*location = location.merge(&statement_location);
*extracted_position = position;
}
We merge statement_location into location. And statement_location is statement.location().
For Use3, statement.location() is the location field of the Use struct, which is the use line.
So we're merging the use line, not the call expression's location.
But wait, what if self.function is Use instead of Statements?
Looking at the code:
Some(ExtractedFunction {
value: value @ ExtractedValue::Use { .. },
..
}) => {
*value = ExtractedValue::Statements {
location: value.location().merge(&statement_location),
position,
};
}
When self.function is Use and we encounter another statement, we convert to Statements and merge.
And value.location() for Use is use_.call.location(), which includes the lambda body!
So if self.function is set to Use for some Use statement, and then we merge with another statement, the merged location would include use_.call.location(), which might span a large portion of the function.
But in the issue, self.function is set to Statements first (for let toml_path), not Use.
Unless... the visitor visits Use3 before let toml_path in some other way.
Actually, wait. Let me re-think this. The visitor visits Use1, then visits use1.call. And use1.call is a Call expression. When we visit a Call expression, visit_typed_expr is called:
fn visit_typed_expr(&mut self, expression: &'ast TypedExpr) {
if self.function.is_none() {
if self.can_extract_expression(expression) {
self.function = Some(ExtractedFunction::new(ExtractedValue::Expression(
expression,
)));
}
}
// ...
}
For the Call expression (use1.call), we check can_extract_expression. And the Call expression's location includes the lambda body.
Now, the selection starts from a comment before let toml_path. And let toml_path is inside Use2's lambda body, which is inside Use1's lambda body.
So the selection is inside Use1's lambda body. And Use1's Call expression's location includes the lambda body.
So overlaps(expression_range, selected_range) would return true (the Call expression's location includes the selection).
And completely_within(selected_range, expression_range) checks if the selection is completely within the Call expression's range.
The Call expression's range spans from result.try( (of Use1) to the end of Use1's lambda body. And Use1's lambda body is [Use2].
So the Call expression's range spans from result.try( (of Use1) to the end of Use2.
And the selection starts after Use2. So the selection is NOT within the Call expression's range.
So completely_within returns false, and !completely_within returns true.
So can_extract_expression returns TRUE for the Call expression of Use1!
And we set self.function to ExtractedValue::Expression(Call).
And the Call expression's location spans from result.try( (of Use1) to the end of Use2.
Hmm, but this doesn't explain why the entire function body is extracted. The Call expression's location only spans to the end of Use2, not the entire function.
Wait, but what is "the end of Use2"? Use2's location is the use line, which ends at the closing ) of Use2's call. But the Call expression of Use1 includes the lambda body, which is [Use2].
So the Call expression's location would span from result.try( (of Use1) to the end of the lambda body. And the lambda body is [Use2].
But what is the end of the lambda body? It's the end of Use2, which is Use2's location.
And Use2's location is the use line, which ends at the closing ) of result.try(...).
So the Call expression's location spans from result.try( (of Use1) to the closing ) of Use2's call.
And the selection starts after the closing ) of Use2's call. So the selection is NOT within the Call expression's range.
So completely_within returns false, and can_extract_expression returns true.
So we set self.function to ExtractedValue::Expression(Call), where Call is Use1's call expression.
And the Call expression's location spans from Use1's call to Use2's closing ).
Now, when we extract, we would replace the code at this location with the function call.
But the issue says the entire function body is replaced. So either:
- The Call expression's location is wider than I think, or
- The extraction handles
Expression differently.
Let me look at how Expression is extracted:
ExtractedValue::Expression(expression) => {
let expression_type = if let TypedExpr::Fn {
type_,
kind: FunctionLiteralKind::Use { .. },
..
} = expression
{
type_.fn_types().expect("use callback to be a function").1
} else {
expression.type_()
};
self.extract_code_in_tail_position(
expression.location(),
expression.location(),
expression_type,
extracted.parameters,
end,
)
}
We call extract_code_in_tail_position with expression.location() as both the replacement location and the code location.
And expression is the Call expression (Use1's call). So expression.location() is the Call expression's location.
If the Call expression's location spans from Use1's call to Use2's closing ), then the replacement would be from Use1's call to Use2's closing ).
But the issue says the entire function body is replaced. So either:
- The Call expression's location spans the entire function body, or
- Something else is going on.
Actually, wait. Let me re-think the AST structure. I said the lambda body of Use1 is [Use2]. But what if the lambda body of Use1 is [Use2, Assignment, Use3, Assignment, Expression]?
In other words, what if each Use statement's lambda body includes ALL subsequent statements, not just the next Use statement?
If that's the case, then the Call expression's location would span from result.try( (of Use1) to the end of the function body (the pipeline).
And the selection (which is within the function body) would be completely within the Call expression's range.
So completely_within would return true, and can_extract_expression would return false.
Hmm, but that doesn't match with what I said earlier. Let me re-think.
Actually, I think the lambda body of each Use statement includes ALL subsequent statements in the function body, not just the next Use statement.
For example:
fn foo() {
use a <- expr1
use b <- expr2
let c = 1
}
Is desugared to:
fn foo() {
expr1(fn(a) {
use b <- expr2
let c = 1
})
}
And use b <- expr2 is further desugared to:
fn foo() {
expr1(fn(a) {
expr2(fn(b) {
let c = 1
c
})
})
}
But in the typed AST, the Use statement's call field is the desugared call. So for Use1, the call is:
expr1(fn(a) {
expr2(fn(b) {
let c = 1
c
})
})
Wait, but that includes the desugaring of Use2 as well. So the lambda body of Use1's call is the desugared form of the rest of the function body.
But what is the "rest of the function body"? Is it the raw statements ([Use2, Assignment]), or the fully desugared form ([Call2])?
I think it's the raw statements. So the lambda body of Use1's call is [Use2, Assignment], not [Call2].
Hmm, but then how does the type checker know the types? It must visit the statements and type-check them.
Actually, I think the AST structure might be different. Let me think about how the compiler works.
In Gleam, the parser produces an untyped AST. The type checker then produces a typed AST.
During parsing, a Use statement is represented as a Use struct with the call expression on the right-hand side (before desugaring).
During type checking, the Use statement is desugared, and the call field is set to the desugared call.
But the location field of the Use struct is set during parsing, and it's the location of the use line in the source code.
So in the typed AST, the Use struct has:
location: the use line in the source code
call: the desugared call (which includes a lambda with the body)
And the lambda body of the desugared call includes... what exactly?
I think the lambda body is constructed by the type checker. It takes the subsequent statements in the function body and wraps them in a lambda.
But the key question is: does the lambda body include all subsequent statements, or just the next statement?
I think it includes all subsequent statements. Because in the desugaring, the lambda body is the rest of the function body.
For example:
fn foo() {
use a <- expr1
use b <- expr2
let c = 1
}
The desugaring of Use1 would be:
expr1(fn(a) {
use b <- expr2
let c = 1
})
Wait, but this includes Use2 in the lambda body. And Use2 is also a Use statement. So the lambda body has [Use2, Assignment].
But then, how is Use2's call expression constructed? It would be:
expr2(fn(b) {
let c = 1
})
And the lambda body of Use2's call is [Assignment].
So in the typed AST, the function body is:
body: [
Use1 {
call: Call1 {
args: [..., Fn1 {
body: [Use2, Assignment]
}]
},
location: ...
},
Use2 {
call: Call2 {
args: [..., Fn2 {
body: [Assignment]
}]
},
location: ...
},
Assignment
]
Wait, but this means the function body has 3 statements: Use1, Use2, Assignment. And Use1's lambda body is [Use2, Assignment], and Use2's lambda body is [Assignment].
But then, the statements in the lambda bodies are the same AST nodes as the ones in the function body. So Use2 in Use1's lambda body is the same as Use2 in the function body.
OK so with this understanding, let me re-think the visitor order.
When we visit the function body, we visit Use1, Use2, Assignment (in order).
For Use1:
can_extract_statement returns false.
- We visit
use1.call (Call1).
- Call1's location spans from
expr1( to the end of Fn1's body.
- Fn1's body is
[Use2, Assignment].
- The end of Fn1's body is the end of Assignment.
So Call1's location spans from Use1's call to the end of Assignment (the last statement in the function body).
And the selection (which is within the function body) is completely within Call1's location.
So completely_within(selected_range, expression_range) returns true, and can_extract_expression returns false for Call1.
Good, so Call1 is not extracted.
But wait, what about Call2? Call2 is Use2's call expression. And Call2's location spans from Use2's call to the end of Fn2's body.
Fn2's body is [Assignment]. So Call2's location spans from Use2's call to the end of Assignment.
And the selection is partially within Call2's location (the selection is from let toml_path to the pipeline).
Hmm, but in the issue's code, the Assignment is let toml_path, and the pipeline is the last expression. So Fn2's body would be [Assignment, Use3, Assignment2, Expression].
Wait, let me re-think. In the issue's code:
fn prepare_project_structure(target, user_id) -> Result(Nil, SubmitError) {
use priv <- result.try(...) // Use1
use _ <- result.try(...) // Use2
let toml_path = ... // Assignment1
use gleam_toml <- result.try(...) // Use3
let gleam_toml = ... // Assignment2
simplifile.write(toml_path, gleam_toml) |> result.replace_error(...) // Expression
}
The function body is:
body: [
Use1,
Use2,
Assignment1,
Use3,
Assignment2,
Expression
]
And each Use statement's lambda body includes all subsequent statements:
- Use1's lambda body: [Use2, Assignment1, Use3, Assignment2, Expression]
- Use2's lambda body: [Assignment1, Use3, Assignment2, Expression]
- Use3's lambda body: [Assignment2, Expression]
Now, when we visit Use1:
can_extract_statement returns false.
- We visit
use1.call (Call1).
- Call1's location spans from
result.try( (of Use1) to the end of Expression.
And the selection is from let toml_path (Assignment1) to Expression.
So the selection is completely within Call1's location (which spans from Use1's call to Expression).
So completely_within(selected_range, expression_range) returns true, and can_extract_expression returns false for Call1.
Good, so Call1 is not extracted.
Similarly, when we visit Use2:
can_extract_statement returns false.
- We visit
use2.call (Call2).
- Call2's location spans from
result.try( (of Use2) to the end of Expression.
And the selection is from Assignment1 to Expression. Assignment1 is inside Call2's lambda body (because Use2's lambda body is [Assignment1, Use3, Assignment2, Expression]).
So the selection is completely within Call2's location.
So completely_within returns true, and can_extract_expression returns false for Call2.
Good.
When we visit Assignment1:
can_extract_statement returns true.
- We set
self.function to Statements with Assignment1's location.
Good.
When we visit Use3:
can_extract_statement returns true.
self.function is already Statements. So we merge Use3's location.
But wait, we also visit Use3 through the lambda bodies of Use1 and Use2. Let me trace through that.
When we visit Use1, we visit Call1, which includes Fn1. Fn1's body is [Use2, Assignment1, Use3, Assignment2, Expression].
When we visit Fn1's body, we visit Use2. And Use2's can_extract_statement returns false. Then we visit Call2.
Call2 includes Fn2. Fn2's body is [Assignment1, Use3, Assignment2, Expression].
When we visit Fn2's body, we visit Assignment1. And Assignment1's can_extract_statement returns true. So we set self.function to Statements.
Then we visit Use3. And Use3's can_extract_statement returns true. So we merge Use3's location.
OK so far so good. The extraction location is from Assignment1 to... well, we haven't visited all statements yet.
But wait, we're inside Fn2's body, which is [Assignment1, Use3, Assignment2, Expression]. So after Assignment1 and Use3, we visit Assignment2 and Expression.
For Assignment2: can_extract_statement returns true. Merge.
For Expression: can_extract_statement returns true. Merge.
So the extraction location is from Assignment1 to Expression. This is correct!
But then, after visiting Fn2's body, we go back to Fn1's body. And we continue visiting the remaining statements in Fn1's body: Use3, Assignment2, Expression.
But wait, we already visited Use3, Assignment2, and Expression through Fn2's body. So when we visit them again through Fn1's body, self.function is already set.
For Use3: can_extract_statement returns true. Merge.
For Assignment2: can_extract_statement returns true. Merge.
For Expression: can_extract_statement returns true. Merge.
But the locations are the same, so the extraction location doesn't change.
OK so the extraction location should be from Assignment1 to Expression. This is correct!
Hmm, but the issue says the entire function body is extracted. So there must be something else going on.
Wait, let me re-think. I said that when we visit Call1 (Use1's call), can_extract_expression returns false because the selection is completely within Call1's location.
But what about when we visit Fn1 (the lambda in Call1)? Let me check.
Fn1 is a TypedExpr::Fn expression. When we visit Fn1, visit_typed_expr is called:
fn visit_typed_expr(&mut self, expression: &'ast TypedExpr) {
if self.function.is_none() {
if self.can_extract_expression(expression) {
self.function = Some(ExtractedFunction::new(ExtractedValue::Expression(
expression,
)));
}
}
let last_statement_location = self.last_statement_location;
if let TypedExpr::Fn { body, .. } = expression {
self.last_statement_location = Some(body.last().location());
}
ast::visit::visit_typed_expr(self, expression);
self.last_statement_location = last_statement_location;
}
For Fn1, we check can_extract_expression. Fn1's location includes the lambda body. And the lambda body is [Use2, Assignment1, Use3, Assignment2, Expression].
So Fn1's location spans from fn(priv) { to } (the end of the lambda body).
And the selection is from Assignment1 to Expression. So the selection is completely within Fn1's location.
So completely_within returns true, and can_extract_expression returns false for Fn1.
Good, so Fn1 is not extracted.
But wait, Fn1's body is [Use2, Assignment1, Use3, Assignment2, Expression]. And body.last().location() is Expression's location.
So last_statement_location is set to Expression's location.
And then we visit Fn1's children, which includes the body. And the body is a block of statements.
When we visit the block, visit_typed_expr_block is called:
fn visit_typed_expr_block(
&mut self,
location: &'ast SrcSpan,
statements: &'ast [TypedStatement],
) {
let last_statement_location = self.last_statement_location;
self.last_statement_location = statements.last().map(|last| last.location());
ast::visit::visit_typed_expr_block(self, location, statements);
self.last_statement_location = last_statement_location;
}
So last_statement_location is updated to statements.last().location(), which is Expression's location.
And then we visit each statement in the block.
For Use2: can_extract_statement returns false. We visit Call2.
For Call2, can_extract_expression is called. Call2's location spans from result.try( (of Use2) to the end of Expression.
And the selection is from Assignment1 to Expression. So the selection is completely within Call2's location.
So completely_within returns true, and can_extract_expression returns false for Call2.
Good.
For Assignment1: can_extract_statement returns true. We set self.function to Statements.
For Use3: can_extract_statement returns true. We merge Use3's location.
For Assignment2: can_extract_statement returns true. We merge.
For Expression: can_extract_statement returns true. We merge.
So the extraction location is from Assignment1 to Expression. This is correct!
OK so based on my analysis, the extraction should work correctly. The extraction location should be from Assignment1 to Expression, which is the selected portion.
But the issue says the entire function body is extracted. So there must be something I'm missing.
Let me re-read the issue one more time...
Actually, wait. I just noticed something. The issue says the user is using "gleam 1.16.0 in neovim nightly". This might be a specific version of the language server.
But the code I'm looking at is the current code in the repository. Maybe the issue has already been fixed, or maybe the bug is in a different version.
Let me check if there are any related commits or issues.
Actually, let me look at the git log to see if there are any recent changes related to extract function.
Actually, I should just focus on finding and fixing the bug. Let me re-read the issue description and think about what could cause the entire function body to be extracted.
The issue says:
It will extract the entire function content into a new function leaving:
fn prepare_project_structure(...) {
function(target, user_id)
}
So the function body is replaced with function(target, user_id). This means the replacement location spans the entire function body.
And the replacement location is the location field of ExtractedFunction::value.
So the location must span the entire function body.
But based on my analysis, the location should be from Assignment1 to Expression.
Unless... there's a bug in how the location is determined.
Actually, let me look at the can_extract_expression function more carefully. I've been assuming that completely_within returns true for the Call expression, because the selection is completely within the Call expression's range.
But what if completely_within returns false? Then can_extract_expression would return true, and we would extract the Call expression.
Let me re-check the completely_within function:
pub fn completely_within(a: Range, b: Range) -> bool {
a.start > b.start && a.start < b.end && a.end > b.start && a.end < b.end
}
This returns true if:
- a.start > b.start (a starts after b)
- a.start < b.end (a starts before b ends)
- a.end > b.start (a ends after b starts)
- a.end < b.end (a ends before b ends)
So a must be strictly within b (not touching the boundaries).
Now, for the Call expression of Use1:
- b.start = start of
result.try( (of Use1)
- b.end = end of Expression (the last statement)
And for the selection:
- a.start = start of the selection (before Assignment1)
- a.end = end of the selection (after Expression)
Now, is a.end < b.end? The selection ends after Expression (at a comment). And b.end is the end of Expression.
If the selection's end is AFTER Expression's end, then a.end > b.end, and completely_within returns false.
In that case, can_extract_expression would return true for the Call expression!
And we would set self.function to ExtractedValue::Expression(Call), where Call is Use1's call expression.
And Call's location spans from Use1's call to Expression.
So the extraction location would span from Use1's call to Expression!
And that would include Use1, Use2, Assignment1, Use3, Assignment2, and Expression.
Wait, but Use1's call expression's location starts at result.try( (of Use1), not at the use keyword. So the extraction would replace from result.try( to Expression.
But the issue says the entire function body is replaced. So maybe the extraction location is even wider.
Actually, let me re-think. If self.function is ExtractedValue::Expression(Call), then the extraction uses Call's location to replace the code.
Call's location is the Call expression's location, which spans from the start of the call to the end of the call (including the lambda body).
For Use1's call, this spans from result.try( to the end of Expression.
So the replacement would be from result.try( to Expression.
But the issue says the entire function body is replaced. So either:
- The Call expression's location starts earlier (at the
use keyword), or
- There's a different extraction path.
Hmm, actually, looking at the issue more carefully, the output is:
fn prepare_project_structure(...) {
function(target, user_id)
}
This means the function body is just function(target, user_id). So the replacement replaced everything from the opening { to the closing } of the function body.
But the Call expression's location should be from result.try( to Expression, not from { to }.
Unless... the extraction replaces more than just the Call expression's location.
Actually, wait. Let me re-read the extract_code_in_tail_position function:
fn extract_code_in_tail_position(
&mut self,
location: SrcSpan,
code_location: SrcSpan,
type_: Arc<Type>,
parameters: Vec<(EcoString, Arc<Type>)>,
function_end: u32,
) {
let expression_code = code_at(self.module, code_location);
// ...
self.edits.replace(location, call);
// ...
}
It replaces the code at location with the function call. So if location spans from result.try( to Expression, the replacement would be from result.try( to Expression.
But the issue says the entire function body is replaced. So either:
location spans the entire function body, or
- There's something else going on.
Hmm, let me think about this. The Call expression's location is set by the compiler. And the Call expression includes the lambda body.
The lambda body is a Block expression. And the Block expression's location spans from { to }.
So the Call expression's location would span from result.try( to } (the end of the lambda body's block).
But what is the lambda body's block? It's the block that contains [Use2, Assignment1, Use3, Assignment2, Expression].
And the block's location spans from the first statement to the last statement (or from { to } if there's an explicit block).
Wait, but in Gleam, function bodies are implicit blocks. The lambda body is also an implicit block.
So the lambda body's location might span from the first statement (Use2) to the last statement (Expression).
And the Call expression's location would span from result.try( to the end of Expression.
So the replacement would be from result.try( (of Use1) to the end of Expression.
But the issue says the entire function body is replaced. So there must be something else.
Actually, wait. Let me re-read the issue output:
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)
}
Hmm, maybe "the entire function content" just means all the code inside the function, not literally from { to }. The replacement might be from the first statement to the last statement.
So if the extraction location spans from result.try( (of Use1) to Expression, the replacement would remove all the code from Use1's call to Expression.
And the remaining code would be:
fn prepare_project_structure(target, user_id) -> Result(Nil, SubmitError) {
use priv <-
function(target, user_id)
}
Wait, that doesn't match the issue output. The issue output shows the function body is just function(target, user_id).
Hmm, but the issue might be simplifying the output. Let me focus on the core issue.
The key insight is: if completely_within returns false for the Call expression, we extract the Call expression, and the extraction location spans from Use1's call to Expression.
This would include Use1's call, which spans most of the function body. And the replacement would remove most of the function body.
So the bug is that completely_within returns false when it should return true.
Let me re-check the condition:
pub fn completely_within(a: Range, b: Range) -> bool {
a.start > b.start && a.start < b.end && a.end > b.start && a.end < b.end
}
For the selection to be completely within the Call expression's range:
- a.start > b.start: The selection starts after the Call expression.
- a.start < b.end: The selection starts before the Call expression ends.
- a.end > b.start: The selection ends after the Call expression starts.
- a.end < b.end: The selection ends before the Call expression ends.
Now, the Call expression's range:
- b.start: Start of
result.try( (of Use1)
- b.end: End of the lambda body (which is the end of Expression, or the end of the block containing Expression)
And the selection:
- a.start: Start of the selection (before Assignment1, at a comment)
- a.end: End of the selection (after Expression, at a comment)
Now:
- a.start > b.start: Is the selection's start after
result.try(? Yes, because the selection starts at Assignment1, which is after Use1's call.
- a.start < b.end: Is the selection's start before the lambda body ends? Yes, because Assignment1 is inside the lambda body.
- a.end > b.start: Is the selection's end after
result.try(? Yes, because Expression is after Use1's call.
- a.end < b.end: Is the selection's end before the lambda body ends?
This is the key condition. The selection's end is after Expression (at a comment). And the lambda body's end is... what?
If the lambda body's end is the end of Expression, and the selection's end is after Expression (at a comment), then a.end > b.end, and completely_within returns false.
But if the lambda body's end includes the comment (or is after the comment), then a.end < b.end, and completely_within returns true.
Hmm, but the lambda body is a block of statements. And the block's location should be the union of all statements' locations. So the block's end should be the end of the last statement (Expression).
And the selection's end is after Expression (at a comment). So a.end > b.end, and completely_within returns false.
So can_extract_expression returns true for the Call expression, and we extract it!
I think this is the bug! The selection's end is after the Call expression's end (because the selection extends to a comment after the last statement), so completely_within returns false, and the Call expression is extracted.
But the Call expression's location spans from Use1's call to the end of Expression. So the extraction would replace most of the function body.
Now, how do we fix this?
The issue is that the selection's end is slightly after the Call expression's end, causing completely_within to return false. But the user intended to select only the code from Assignment1 to Expression.
One fix would be to use within instead of completely_within for the Call expression check. But within allows touching the boundaries, which might cause other issues.
Actually, looking at the code more carefully, the issue is with how can_extract_expression works for Call expressions. It uses !completely_within(selected_range, expression_range) to determine if the expression should be extracted.
But for a Call expression that includes a lambda body (like a Use statement's call), the expression's range is very large (it includes all subsequent statements). And if the selection extends slightly beyond the expression's end (to a comment), completely_within returns false, and the expression is extracted.
This is incorrect behavior. The Call expression should not be extracted just because the selection extends slightly beyond its end.
I think the fix should be to not extract a Call expression that includes a lambda body (i.e., a Use statement's call) when the selection is mostly within the expression.
Actually, looking at the code, the issue might be more fundamental. The problem is that when we visit a Use statement's call expression, the call expression's range includes the lambda body, which includes all subsequent statements. And if the selection overlaps with the lambda body, we might extract the Call expression.
But we don't want to extract the Call expression; we want to extract the statements within the selection.
I think the fix should be to not extract Call expressions that are Use statement calls (i.e., Call expressions that have a lambda argument with a body).
Actually, let me look at the can_extract_expression function more carefully:
fn can_extract_expression(&self, expression: &TypedExpr) -> bool {
let expression_range = self.edits.src_span_to_lsp_range(expression.location());
let selected_range = self.params.range;
if !overlaps(expression_range, selected_range) {
return false;
}
match expression {
TypedExpr::Pipeline { first_value, finally, .. } => {
// special handling for pipelines
}
TypedExpr::Int { .. }
| TypedExpr::Float { .. }
| TypedExpr::String { .. }
| TypedExpr::Block { .. }
| TypedExpr::Var { .. }
| TypedExpr::Fn { .. }
| TypedExpr::List { .. }
| TypedExpr::Call { .. }
| ... => !completely_within(selected_range, expression_range),
}
}
For a Call expression, we return !completely_within(selected_range, expression_range). This means we extract the Call expression if the selection is NOT completely within the Call expression.
But for a Call expression that includes a lambda body (like a Use statement's call), the expression's range is very large. And if the selection is within the expression but extends slightly beyond its end, completely_within returns false, and we extract the expression.
I think the fix should be to add a special case for Call expressions that have a lambda argument (i.e., Use statement calls). We should not extract these Call expressions.
Actually, looking at the TypedExpr::Call variant, I need to check if any of its arguments is a lambda (Fn expression). If so, it might be a Use statement's call.
But wait, not all Call expressions with lambda arguments are Use statements. The user might pass a lambda to a regular function.
Hmm, but in the context of the visit_typed_expr function, if we're visiting a Call expression that's part of a Use statement's call field, it would be a Use statement's call.
Actually, looking at the visitor code, we visit Use statements' call expressions through visit_typed_use:
pub fn visit_typed_use<'a, V>(v: &mut V, use_: &'a TypedUse)
where
V: Visit<'a> + ?sized,
{
v.visit_typed_expr(&use_.call);
}
So when we visit use_.call, we call visit_typed_expr for the Call expression. And visit_typed_expr checks can_extract_expression.
So the Call expression is visited as a regular expression, and we don't know that it's a Use statement's call.
I think the fix should be to check if the Call expression has a lambda argument that is a Use callback. If so, we should not extract the Call expression.
Actually, looking at the TypedExpr::Fn variant, there's a FunctionLiteralKind that distinguishes between regular anonymous functions and Use callbacks:
pub enum FunctionLiteralKind {
Capture,
Use { location: SrcSpan },
Anonymous,
}
So if a Call expression has an argument that is a Fn with FunctionLiteralKind::Use, it's a Use statement's call.
Let me check if we can detect this in can_extract_expression.
Actually, I think a simpler fix would be to just not extract Call expressions that have a Fn argument with FunctionLiteralKind::Use. We can check the arguments of the Call expression.
But actually, looking at the issue more carefully, I think the problem is different. The issue is that the selection extends beyond the Call expression's end, causing completely_within to return false.
If the selection's end was within the Call expression's end, completely_within would return true, and the Call expression would not be extracted.
So the fix might be to handle the case where the selection extends slightly beyond the expression's end.
Actually, I think the issue is that completely_within requires the selection to be strictly within the expression (not touching the boundaries). If the selection touches the boundary (or extends slightly beyond), completely_within returns false.
Let me re-read the completely_within function:
pub fn completely_within(a: Range, b: Range) -> bool {
a.start > b.start && a.start < b.end && a.end > b.start && a.end < b.end
}
The condition a.end < b.end requires the selection's end to be strictly before the expression's end. If they're equal, completely_within returns false.
So if the selection's end is equal to or greater than the expression's end, completely_within returns false, and we extract the expression.
I think the fix should be to use a less strict condition. Instead of a.end < b.end, we should use a.end <= b.end.
But wait, changing completely_within might affect other parts of the code that depend on its behavior.
Actually, let me re-read the completely_within documentation:
/// Returns true if the first range is completely within the second range.
/// The range cannot have any extreme in common to be considered completely
/// within another.
So completely_within is intentionally strict. It requires the range to NOT touch the boundaries.
But for the extract function feature, we might want a less strict condition. We want to check if the selection is "mostly within" the expression, allowing for slight extensions beyond the boundaries.
Actually, I think the issue is not with completely_within, but with how can_extract_expression handles Call expressions.
For a Call expression that includes a lambda body (like a Use statement's call), the expression's range is very large. And we don't want to extract this Call expression, because extracting it would extract the entire lambda body.
So the fix should be to not extract Call expressions that have a Use callback as an argument.
Let me look at how to detect this.
Actually, I think there's a simpler fix. The issue is that we're visiting the Call expression through visit_typed_use, which means the Call expression is a Use statement's call. And we don't want to extract Use statement calls.
But in visit_typed_expr, we don't know that the Call expression is a Use statement's call. We just see it as a regular Call expression.
One fix would be to add a flag to indicate that we're visiting a Use statement's call, and skip the extraction check in that case.
But that would require changing the visitor interface.
Another fix would be to check if the Call expression has a Use callback argument, and skip the extraction check in that case.
Let me think about this more. The Call expression is visited through visit_typed_use, which calls visit_typed_expr(&use_.call). So the Call expression is the call field of a Use statement.
And the call field is a desugared call, which has a Use callback as the last argument.
So we can check if the Call expression has a Use callback argument, and skip the extraction check.
Let me look at how to do this.
Actually, I think the fix should be in can_extract_expression. For a Call expression, we should check if any of its arguments is a Fn with FunctionLiteralKind::Use. If so, we should not extract the Call expression.
Let me implement this fix.
Actually wait, I realize I should verify my hypothesis first. Let me create a test case that reproduces the issue.
Let me run the existing tests first to make sure they pass.
Let me first understand the issue better by running the tests.
<tool_call>
<function=bash_terminal>
<parameter=command>
cd /gleam && cargo test --package gleam-language-server extract_function_partially_selected 2>&1 | tail -20
</tool_call>