The user hasn't said anything new, they're just waiting for me to continue. Let me think about this more carefully.
Looking at the issue description again:
- User selects a portion of statements in a function
- Instead of extracting just those statements, the entire function body gets extracted
The problem is that when the selection extends to the end of the function body, the Block expression (which is the function body) is being matched instead of the individual statements.
The key is in can_extract_expression:
TypedExpr::Block { .. } => !completely_within(selected_range, expression_range)
When the selection ends at the boundary of the block, completely_within returns false, so can_extract_expression returns true, and the block is extracted.
But I can't just make blocks never extractable because there are legitimate cases where a block should be extracted (like when the user explicitly selects a block in a let x = { ... } statement).
The real issue is that for function body blocks (anonymous function bodies), we shouldn't be extracting the block itself - we should be extracting the statements inside. The function body is a special case.
Looking at the code flow:
visit_typed_function visits the function
- It then visits expressions/statements inside the function
- For the function body block,
visit_typed_expr_block is called
The issue is that visit_typed_expr might match the block before visit_typed_statement gets to match the individual statements.
Wait, let me trace through this more carefully. When visit_typed_function is called:
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);
}
}
It calls ast::visit::visit_typed_function(self, function) which will visit the function body. But how is the function body visited? Let me check...
The function body is a list of statements, and the visitor will iterate through them. But before that, there might be a block expression that wraps them.
Actually, looking at the AST, a function body is typically a list of TypedStatement, not a TypedExpr::Block. So the issue might be different.
Wait, let me re-read the issue description more carefully:
The user selects from a comment line (which is inside the function body) to the end of the function. The comment is:
// replace $PROJECT_NAME placeholder in the gleam.toml
This comment is followed by statements. The selection doesn't include the entire function body.
Let me think about what happens:
visit_typed_function is called - the function range includes the entire function
within(self.params.range, range) - is the selection within the function? Yes, the selection is inside the function body
ast::visit::visit_typed_function(self, function) - this visits the function
Now, visit_typed_function from the visit module would typically:
- Visit the arguments
- Visit the body statements
But wait, there might be a TypedExpr::Block that wraps the function body. Let me check how the visitor handles this...
Actually, I think the issue is that the can_extract_expression check for Block is wrong. When the selection starts inside a block and extends to its end, we don't want to extract the block itself - we want to extract the statements inside.
But as I noted before, there are cases where a block should be extractable. So the fix needs to be more nuanced.
Let me look at the within function:
pub fn within(a: Range, b: Range) -> bool {
position_within(a.start, b) && position_within(a.end, b)
}
This returns true if both start and end of a are within b (inclusive).
And completely_within:
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 is strictly inside b (not touching boundaries).
So if the selection starts inside the block and ends at the block's closing brace:
within(selection, block) = true (because end position is at the block end)
completely_within(selection, block) = false (because end touches the boundary)
The issue is that when completely_within returns false (because the selection touches the boundary), can_extract_expression returns !false = true, which marks the block as extractable.
The fix should be: for Block expressions, use within instead of completely_within. This way, if the selection is entirely within the block (even if it touches the boundary), we don't extract the block itself.
But wait, what if the user wants to extract a block expression like:
let x = {
// selection starts here
let a = 1
let b = 2
a + b
// selection ends here
}
In this case, the selection is completely within the block, and we DO want to extract the block's statements, not the block itself. So using within would be correct here too.
But what about:
let x = {
let a = 1
let b = 2
a + b
}
// selection includes the closing brace or extends beyond it
Hmm, but can the selection include the closing brace and still be meaningful? The block's location typically includes the braces. If the selection ends at the same position as the block's closing brace, within would still return true.
I think the correct fix is to change the Block case to use within instead of completely_within. Let me verify this logic:
For a Block expression:
- If the selection is entirely within the block (including touching the boundaries), we should NOT extract the block itself - we should traverse into its statements
- If the selection is NOT within the block, we can't extract it anyway (overlaps check catches this)
So !within(selected_range, expression_range) would be the correct check for blocks.
Wait, but within uses position_within which is inclusive of both boundaries. So if the selection starts at the opening brace and ends at the closing brace, within returns true, and !within returns false. Good, we don't extract the block.
If the selection starts inside the block and ends at the closing brace, within returns true (because both positions are within the block), and !within returns false. Good, we don't extract the block.
If the selection starts before the block or ends after the block, within returns false, and !within returns true. But in this case, the overlaps check at the beginning would have returned true, so we'd still try to extract the block. But wait, if the selection doesn't start within the block, it might still overlap with it. So the overlaps check would pass, and then we'd check !within, which would be true.
Hmm, but in the issue, the selection DOES start inside the block. So within should return true, and !within should return false. Good.
Let me also think about the failing tests. The tests that fail when I make blocks never extractable involve selecting a block expression. In those cases, the selection is within the block, and my false return prevented extraction.
But with !within, if the selection is within the block, we still return false, which is the same issue. So !within won't work either.
Wait, let me re-examine the failing tests:
-old snapshot
+new results
30 30 │ pub fn do_things(a, b) {
31 │- let result = function_5(a, b)
31 │+ let result = {
32 │+ function_5(a, b)
33 │+ }
The test selects a block expression let result = { ... }. The expected behavior is to extract the block's content and replace let result = { ... } with let result = function(...).
But with my change, the block is not extracted. Instead, the statements inside are extracted, but the block itself remains, resulting in let result = { function(...) }.
So the issue is more nuanced. When a block is explicitly selected (like a block expression in a let statement), we DO want to extract it. But when the selection is within a larger block (like the function body), we DON'T want to extract the larger block.
Hmm, how can we distinguish these cases?
One approach is to check if the block is the "top-level" block of a function (i.e., the function body). If so, we should never extract it. But if it's a nested block (like in a let statement), we should allow extraction.
Looking at the visitor, visit_typed_expr_block is called for all blocks, including function bodies. But function bodies are actually a list of statements, not a block expression. Let me check...
Actually, I think the function body is NOT a TypedExpr::Block. It's a Vec<TypedStatement>. The visit_typed_function method visits the function body statements directly:
ast::visit::visit_typed_function(self, function);
And visit_typed_function from the visit module would iterate over the body statements.
So the issue must be elsewhere. Let me re-read the issue description:
The user has:
fn prepare_project_structure(...) -> Result(Nil, SubmitError) {
// statement 1: use priv <- result.try(...)
// statement 2: use _ <- result.try(...)
// statement 3: let toml_path = ...
// statement 4: use gleam_toml <- result.try(...)
// statement 5: let gleam_toml = ...
// statement 6: simplifile.write(...)
}
And the user selects from statement 3 to statement 6. But the entire function body is extracted.
Wait, the selection starts at a comment line, not at a statement. So the selection includes the comment // replace $PROJECT_NAME... and then the statements from let toml_path = ... to the end.
Since comments are not part of the AST, the selection effectively starts inside statement 3 or just before it.
Let me think about what happens:
visit_typed_function is called
self.last_statement_location is set to the location of the last statement in the function body
ast::visit::visit_typed_function(self, function) visits all statements in the function body
Now, when visiting each statement, visit_typed_statement is called. For statement 1 (use priv <- ...), can_extract_statement is called:
overlaps(statement_range, selected_range) - does statement 1 overlap with the selection? The selection starts at the comment line, which is AFTER statement 2 but BEFORE statement 3. So statement 1 does NOT overlap.
- Returns
false
For statement 2 (use _ <- ...):
- Same as statement 1, returns
false
For statement 3 (let toml_path = ...):
overlaps(statement_range, selected_range) - YES, the selection starts at the comment line which is right before let toml_path
within(selected_range, value_range) - the selection goes all the way to the end of the function, so the value range is NOT within the selection
completely_within(selected_range, statement_range) - the selection goes beyond statement 3, so it's NOT completely within
- Returns
!false && !false = true
Now, since self.function is None, it creates a new extraction with ExtractedValue::Statements.
For statements 4, 5, 6:
- They also overlap with the selection
self.function is already Some(ExtractedValue::Statements { ... }), so the location is merged
This seems correct! So why is the entire function body being extracted?
Wait, maybe the issue is with expressions, not statements. Let me think about this differently.
Oh wait! I think I understand now. The issue might be that visit_typed_expr is called for an expression that wraps all the statements, like a block. But function bodies are NOT blocks - they're lists of statements.
Hmm, but what if the issue is with the Use statement? Let me look at the issue description again:
The user selects:
// 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
This selection includes a use statement. Looking at the visit_typed_statement code:
TypedStatement::Use(use_) => {
Some(ExtractedFunction::new(ExtractedValue::Use {
location: use_.call.location(),
type_: statement.type_(),
}))
}
For a Use statement, the location is set to use_.call.location(), which is the location of the result.try(...) call. This is different from the entire use statement.
And then when another statement is encountered:
Some(ExtractedFunction {
value: value @ ExtractedValue::Use { .. },
..
}) => {
*value = ExtractedValue::Statements {
location: value.location().merge(&statement_location),
position,
};
}
The extraction falls back to extracting multiple statements.
But wait, what if the issue is that when visiting the use statement, the can_extract_statement check returns true even though it's within a larger block? Let me check...
Actually, I think I need to look at this from a different angle. The issue says the entire function content is extracted. This means the visitor is matching something that covers the entire function body.
What if the issue is with visit_typed_expr matching an expression that covers all the statements? Let me check if there's such an expression...
Actually, looking at the Gleam code in the issue, the last statement is:
simplifile.write(toml_path, gleam_toml)
|> result.replace_error(FailedToWriteGleamToml)
This is a pipeline! Let me check how pipelines are handled in can_extract_expression:
TypedExpr::Pipeline {
first_value,
finally,
..
} => {
// We can extract a pipeline as a whole only if the selection
// spans all of its steps!
let first_step = self.edits.src_span_to_lsp_range(first_value.location);
let last_step = self.edits.src_span_to_lsp_range(finally.location());
position_within(selected_range.start, first_step)
&& position_within(selected_range.end, last_step)
}
This checks if the selection spans all pipeline steps. If the user only selects part of the pipeline, this returns false. So the pipeline itself is not extracted.
Hmm, but what about the function body block? Let me re-check...
Actually, I wonder if the issue is that when the selection goes to the end of the function body, the completely_within check for blocks fails, and the block is extracted.
Wait, but I showed earlier that the function body is NOT a block expression. It's a list of statements.
Let me think about this differently. What if there's a TypedExpr::Block somewhere that covers the selected statements? For example, could there be a block expression that wraps some of the statements?
Looking at the issue code:
fn prepare_project_structure(...) -> Result(Nil, SubmitError) {
use priv <- result.try(...)
use _ <- result.try(...)
let toml_path =
target.path
|> filepath.join("gleam.toml")
use gleam_toml <- result.try(...)
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)
}
I don't see any explicit block expressions here. The let assignments and use statements are all at the top level of the function body.
Wait, but the let expressions have their values as pipeline expressions:
let toml_path =
target.path
|> filepath.join("gleam.toml")
These are not blocks, they're pipelines.
OK so where could the Block expression be coming from?
Let me look at visit_typed_expr_block:
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;
}
This is called when visiting a block expression. But where would a block expression be in the function body?
OH WAIT! I think I see it now. The use statement in Gleam is actually a shorthand for a function call with a callback. The callback is a block expression! Let me check...
Actually, I'm not sure about this. Let me look at the AST structure for use statements.
Hmm, let me just test my theory by checking if the fix works. I'll change the Block case to use within instead of completely_within:
Actually, wait. Let me re-read the test failures:
31 │- let result = function_5(a, b)
31 │+ let result = {
32 │+ function_5(a, b)
33 │+ }
This shows that when the block is selected (in let result = { ... }), the expected behavior is to extract the block's content and replace it with a function call. But with my change, the block is not extracted, and instead the statements inside are extracted, leaving the block empty (well, with just the function call inside).
So the issue is:
- When a block expression is explicitly selected, we should extract it
- When the selection is within a block but doesn't fully select the block, we should extract the statements inside
The key difference is whether the block itself is selected or just its contents.
Hmm, but how can we tell the difference? The selection might start at the opening brace and end at the closing brace, in which case the block is fully selected.
Actually, I think the issue is more subtle. Let me look at can_extract_expression again:
if !overlaps(expression_range, selected_range) {
return false;
}
If the selection doesn't overlap with the expression, we return false. So for a block that's not selected at all, we won't extract it.
Then for blocks:
TypedExpr::Block { .. } => !completely_within(selected_range, expression_range)
This returns true if the selection is NOT completely within the block. So:
- If the selection is entirely inside the block (including touching the boundaries),
completely_within returns false (if touching boundaries) or true (if strictly inside). Either way, the return value is false or true.
- Wait, if the selection is strictly inside the block (not touching boundaries),
completely_within returns true, and !true = false. Good, we don't extract the block.
- If the selection touches the opening or closing brace,
completely_within returns false, and !false = true. We DO extract the block.
So the current behavior is:
- If the selection is strictly inside the block, don't extract the block (traverse into statements instead)
- If the selection touches the block boundaries, extract the block
And the issue is: when the selection extends to the end of the function body (which might be a block?), the block is extracted.
But wait, I said earlier that the function body is NOT a block. So where is the block coming from?
Let me check if there's a block expression that wraps the function body... Actually, in Gleam, the function body IS a list of statements, not a block. So there shouldn't be a TypedExpr::Block for the function body.
But the test failures show that when I make blocks never extractable, the block expressions in let statements are not extracted. So blocks ARE being used in the code.
Hmm, let me think about this differently. What if the issue is not with the block extraction but with how the Fn expression is handled?
Looking at the visitor code:
fn visit_typed_expr(&mut self, expression: &'ast TypedExpr) {
// If we have already determined what code we want to extract, we don't
// want to extract this instead.
if self.function.is_none() {
// If this expression is fully selected, we mark it as being extracted.
if self.can_extract_expression(expression) {
self.function = Some(ExtractedFunction::new(ExtractedValue::Expression(
expression,
)));
}
}
...
}
If self.function.is_none() and can_extract_expression returns true, we set self.function. But then when visit_typed_statement is called for statements inside the expression, we have this code:
Some(ExtractedFunction {
value: ExtractedValue::Expression(_),
..
}) => {}
So if an expression has already been marked for extraction, we don't update it when visiting statements inside. This means once an expression is selected, all statements inside are considered part of it.
Now, the issue is that an expression that covers the entire function body is being selected. What expression could that be?
Wait, I just realized something. Looking at 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);
}
}
It calls ast::visit::visit_typed_function(self, function). This visitor function will iterate over the function body and call visit_typed_statement for each statement.
But wait, what if one of the statements in the function body is a Use statement, and the Use statement has a block expression for its callback? In that case, the visitor would visit the block expression, and can_extract_expression might return true for it.
Let me check how Use statements are represented in the AST...
Actually, I think I'm overcomplicating this. Let me just run the tests and see what happens with a more targeted fix.
The key insight from the failing tests is:
- When a block is fully selected (like
{ let a = 1; let b = 2; a + b }), we should extract the block
- When a partial selection is made within a block, we should NOT extract the block, but extract the statements inside
The issue is distinguishing between these two cases.
Looking at the can_extract_expression check:
completely_within(selected_range, expression_range) returns true only if the selection is STRICTLY inside (not touching boundaries)
- So if the selection touches the opening or closing brace,
completely_within returns false, and the block is extracted
But for a partial selection within a function body, the selection might touch the closing brace (or whatever expression covers the end of the function).
Hmm, let me think about this more carefully. What expression covers the end of the function?
If the last statement in the function is a let assignment or a use statement, there's no block that covers the entire function body. The function body is just a list of statements.
But wait, what if the selection end position is past the last statement and within the function's closing brace? In that case, the selection might be considered to overlap with some expression that I haven't identified yet.
Actually, I think I need to understand the AST structure better. Let me check if there's a Fn expression that wraps the function body...
Looking at can_extract_expression for Fn:
TypedExpr::Fn { .. } => !completely_within(selected_range, expression_range)
If there's an anonymous function (like a callback in a use statement), its body might be a Fn expression. But the main function body is not a Fn expression.
OK, I think I've been going in circles. Let me take a step back and think about the actual fix.
The issue is that when the user selects from a partial point to the end of a function, the entire function body is extracted. This happens because some expression that covers the entire function body is being marked as extractable.
Looking at the code flow:
visit_typed_function sets up the context and calls ast::visit::visit_typed_function
- The default visitor iterates over the function body statements
- For each statement,
visit_typed_statement is called
- For expressions within statements,
visit_typed_expr is called
If visit_typed_expr marks an expression as extractable (because can_extract_expression returns true), then subsequent statements inside that expression are ignored (because self.function is no longer None).
So the question is: what expression covers the entire function body?
Wait, I just realized something. In Gleam, a function body can be a single expression (the return value). If the last statement is an expression without a let, it's the function's return value. But even then, it's just an expression, not a block that wraps everything.
Let me look at the issue description code again:
fn prepare_project_structure(...) -> 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(FailedToWriteGleamToml)
}
The last line is a pipeline expression. This expression is in tail position, meaning its value is returned from the function. But it doesn't wrap the entire function body.
OK, I think the issue might actually be with how Use statements are handled. Let me look at can_extract_statement for Use:
ast::Statement::Use(_) => {
!completely_within(selected_range, statement_range)
}
This returns true if the selection is NOT completely within the use statement. So if the selection extends beyond the use statement, the use statement is considered extractable.
But looking at the issue, the selection includes multiple statements, not just a use statement. So the use statement should not be the one extracted.
Wait, but visit_typed_statement is called for EACH statement in order. Let me trace through:
- Statement 1 (
use priv <- ...): can_extract_statement returns false (doesn't overlap)
- Statement 2 (
use _ <- ...): can_extract_statement returns false (doesn't overlap)
- Statement 3 (
let toml_path = ...): can_extract_statement returns true (overlaps)
- Since
self.function is None, it creates ExtractedValue::Statements with the location of statement 3
- Statement 4 (
use gleam_toml <- ...): can_extract_statement returns true (overlaps)
- Since
self.function is Some(ExtractedValue::Statements { ... }), it merges the location
- Statement 5 (
let gleam_toml = ...): Same as statement 4
- Statement 6 (pipeline): Same as statement 4
This looks correct! The location should be the merged range of statements 3-6, which is exactly what the user selected.
So why is the entire function body being extracted?
Hmm, wait. Let me re-read the issue description:
It will extract the entire function content into a new function leaving:
fn prepare_project_structure(...) {
function(target, user_id)
}
This shows that the entire function body is replaced with a single function call. So the extracted location must be the entire function body, not just statements 3-6.
But my trace above shows that only statements 3-6 should be extracted. So there must be something else going on.
Let me look at can_extract_statement for Assignment again:
ast::Statement::Assignment(assignment) => {
let value_range = self
.edits
.src_span_to_lsp_range(assignment.value.location());
!within(selected_range, value_range)
&& !completely_within(selected_range, statement_range)
}
This returns true if:
- The selection is NOT within the value range (i.e., the selection includes the
let keyword or the variable name)
- AND the selection is NOT completely within the statement range
For statement 3 (let toml_path = ...), the selection starts at the comment line, which is BEFORE the let keyword. So:
within(selected_range, value_range) - is the selection within the value range? The selection starts before the let keyword, so it starts before the value expression. So within returns false.
completely_within(selected_range, statement_range) - is the selection completely within statement 3? The selection extends beyond statement 3, so it's NOT completely within. completely_within returns false.
- Returns
!false && !false = true && true = true
OK so the assignment statement IS extractable. Good.
Now, what if the selection starts BEFORE the first statement of the function body? If the selection includes the opening brace { of the function body, then it might be considered to overlap with something else...
Actually, I wonder if the issue is with the Use statement extraction. Let me look at the Use case in visit_typed_statement:
TypedStatement::Use(use_) => {
Some(ExtractedFunction::new(ExtractedValue::Use {
location: use_.call.location(),
type_: statement.type_(),
}))
}
The location is set to use_.call.location(), which is the location of the result.try(...) call, NOT the entire use statement. This might cause issues.
But wait, the issue says the selection starts at a comment line, which is after statements 1 and 2. So the Use statements 1 and 2 should not be involved.
Let me think about this differently. Maybe the issue is with how the code is extracted after the extraction is determined. Let me look at extract_statements:
Actually, let me just run the tests and see what happens with a specific test case that mimics the issue.
OK wait, I think I might have been overthinking this. Let me re-read the issue one more time:
When triggering Extract function with the selection:
// <-------------------------------------------------------------- selected from here
let toml_path = ...
...
simplifile.write(toml_path, gleam_toml)
|> result.replace_error(FailedToWriteGleamToml)
// <---------------------------------------------------------------- to here
The selection is from a comment line to the end of the function. The comment line is NOT part of any AST node. So the selection effectively starts at the first AST node that overlaps with it, which is let toml_path = ....
Now, the issue is that the ENTIRE function body is extracted, not just the selected statements. This means either:
- An expression that covers the entire function body is being marked as extractable, or
- The location merging is going wrong somewhere
Let me check option 1. What expression could cover the entire function body?
Actually, I just realized: the function body might be wrapped in a block expression in the AST! Let me check...
Looking at the Gleam AST, I see TypedFunction has a body: Vec1<TypedStatement> field. So the function body is a list of statements, not a block expression.
But wait, when the visitor visits the function body, it iterates over the statements. So there's no block expression to extract.
Unless... there's a nested block expression within one of the statements. For example, a use statement might have a callback that's a block expression.
Hmm, let me just look at what happens when I run the test.
Actually, I think I finally understand the issue. Let me look at visit_typed_expr_block:
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;
}
This is called when visiting a block expression. It updates last_statement_location to the last statement in the block, then visits the block's contents.
Now, when the block expression is visited by visit_typed_expr, can_extract_expression is called:
TypedExpr::Block { .. } => !completely_within(selected_range, expression_range)
If the selection extends to the end of the block, completely_within returns false, and can_extract_expression returns true. So the block is extracted!
But wait, the function body is not a block. So where is this block coming from?
OH! I think I see it now. The Use statement in Gleam is syntactic sugar for a function call with a callback. The callback is typically a block expression. So when the visitor visits the use gleam_toml <- result.try(...) statement, it visits the callback block expression.
Let me check the AST structure for Use:
pub struct Use<...> {
pub location: SrcSpan,
pub call: Call<...>,
pub assignments: Vec<...>,
pub then: Box<TypedExpr>,
...
}
The then field is the callback expression, which could be a block! And the block might cover the rest of the statements after the use statement.
So when the user selects from let toml_path = ... to the end of the function, the selection might overlap with a block expression that's the then part of a use statement.
Wait, but the use gleam_toml <- result.try(...) statement is AFTER let toml_path = .... So the then block of that use statement would only include statements after it.
Let me think about this more carefully. In Gleam, use statements have a then clause that represents the rest of the function body after the use statement. For example:
use x <- result.try(call)
// The rest of the function body is the "then" clause
do_something(x)
So the then block of use gleam_toml <- result.try(...) would include:
let gleam_toml = ...
simplifile.write(...) (the return value)
But this block does NOT include let toml_path = ... or use priv <- result.try(...).
Hmm, but the user's selection starts at let toml_path = ..., which is BEFORE use gleam_toml <- result.try(...). So the selection might overlap with multiple nested blocks.
Actually, I think the issue might be with the use priv <- result.try(...) statement. Its then block would include ALL the statements after it:
use _ <- result.try(...)
let toml_path = ...
use gleam_toml <- result.try(...)
let gleam_toml = ...
simplifile.write(...)
And the then block of use _ <- result.try(...) would include:
let toml_path = ...
use gleam_toml <- result.try(...)
let gleam_toml = ...
simplifile.write(...)
So the then block of use _ <- result.try(...) covers exactly the user's selection! And when the visitor visits this block, can_extract_expression returns true (because the selection is not completely within the block, as it touches the boundaries), and the entire block is extracted.
That's the bug! The then block of a use statement that covers the user's selection is being extracted, instead of the individual statements.
The fix should be to not extract Block expressions when the selection is within them (not just when it's completely within). We should traverse into the block's statements instead.
So the fix is to change:
TypedExpr::Block { .. } => !completely_within(selected_range, expression_range)
to:
TypedExpr::Block { .. } => !within(selected_range, expression_range)
This way, if the selection is within the block (even if it touches the boundaries), we don't extract the block. We only extract the block if the selection is NOT within the block (i.e., it extends beyond the block).
But wait, this would also prevent extracting blocks that are explicitly selected. Let me think about when we DO want to extract a block...
Looking at the failing test:
let result = {
let a = 10 + a
let b = 10 + b
a * b
}
The user selects the entire block { ... }. In this case, within(selected_range, block_range) would be true, so !within would be false, and we wouldn't extract the block. But we WANT to extract it!
Hmm, so using within would break this case.
Wait, but looking at the test, the selection is find_position_of("{").nth_occurrence(2).select_until(find_position_of("}")). This selects from the opening brace to the closing brace. In this case:
selected_range.start is at the opening brace
selected_range.end is at the closing brace
And within(selected_range, block_range) checks if both are within the block range. If the block range is from the opening brace to the closing brace (inclusive), then both positions are within the range, and within returns true.
So with !within, we wouldn't extract this block. But the test expects us to extract it.
But wait, looking at the test more carefully, the selection includes the braces. And the block's location also includes the braces. So the selection is EXACTLY the same as the block's location.
Hmm, but in the issue, the selection is from a comment line (not part of the block) to the end of the function. So the selection does NOT start at the block's opening brace.
So maybe the fix should be:
- Extract the block if the selection starts AT or BEFORE the block's opening brace
- Don't extract the block if the selection starts AFTER the block's opening brace
Let me think about how to implement this...
Actually, I think the issue is that we want to extract the block when it's explicitly selected by the user (i.e., the selection includes the opening brace), but not when the selection starts inside the block.
The current check is:
TypedExpr::Block { .. } => !completely_within(selected_range, expression_range)
This returns true if the selection is NOT strictly inside the block. So it returns true when:
- The selection starts at or before the opening brace, OR
- The selection ends at or after the closing brace
But we want it to return true only when:
- The selection starts at or before the opening brace
So the fix should be:
TypedExpr::Block { .. } => selected_range.start <= expression_range.start
Wait, that doesn't sound right. Let me think again...
Actually, I think the issue is that we want to extract the block when the user explicitly selects it (by selecting from its opening brace), but not when the selection starts inside it (like from a use statement's then block).
So the check should be: extract the block if the selection starts at the block's opening brace. Otherwise, don't extract it.
TypedExpr::Block { .. } => selected_range.start == expression_range.start
But this might be too strict. What if the user selects from before the opening brace?
Hmm, let me think about this differently. The issue is that a use statement's then block is being extracted when the selection starts inside it. But we want to extract the individual statements instead.
One way to fix this is to check if the block is a use statement's then block and handle it specially. But that's complicated.
Another way is to check if the selection starts at the beginning of the block. If the selection starts at the block's opening brace, the user is explicitly selecting the block. If the selection starts inside the block, the user is selecting part of the block's content.
So the fix could be:
TypedExpr::Block { .. } => {
selected_range.start <= expression_range.start
&& !completely_within(selected_range, expression_range)
}
This returns true if:
- The selection starts at or before the block's opening brace
- AND the selection is not completely within the block
Hmm, but this still might not be right. Let me think about the failing test case:
- Selection starts at the opening brace
{
- Block range starts at the opening brace
{
selected_range.start <= expression_range.start is true
completely_within(selected_range, expression_range) is false (selection includes the braces)
- Returns
true && true = true
Good, this works for the test case.
Now for the issue case:
- Selection starts at a comment line (inside the block)
- Block range starts at the opening brace
selected_range.start <= expression_range.start is false (selection starts after the opening brace)
- Returns
false && ... = false
Good, this works for the issue case too!
But wait, what if the selection starts at a position before the block (like in the margin)? Then selected_range.start <= expression_range.start would be true, and we might incorrectly extract the block.
Hmm, but in that case, the selection would start before the block and end somewhere inside or at the end of the block. The user is selecting a range that includes the block's opening brace. This might be intentional.
Actually, I think selected_range.start <= expression_range.start is not quite right. Let me use within for the start position:
TypedExpr::Block { .. } => {
// Extract the block if the selection starts at or before the block's opening
// brace. This way, we don't extract blocks when the selection starts inside
// them (like when a use statement's then block overlaps with the selection).
selected_range.start <= expression_range.start
&& position_within(selected_range.start, expression_range)
&& !completely_within(selected_range, expression_range)
}
Hmm, this is getting complicated. Let me simplify:
TypedExpr::Block { .. } => {
// Don't extract the block if the selection starts after the block's opening
// brace. This prevents extracting blocks that the user didn't explicitly
// select (like use statement then blocks).
if selected_range.start > expression_range.start {
return false;
}
!completely_within(selected_range, expression_range)
}
Actually, I think the simplest fix is:
TypedExpr::Block { .. } => {
// Only extract the block if the selection starts at or before the block's
// opening brace. This prevents extracting blocks when the selection starts
// inside them.
selected_range.start <= expression_range.start
}
Wait, but this would also extract blocks when the selection starts way before the block. That might not be what we want either.
OK let me think about this more carefully. The conditions we want are:
- The block should be extractable if the user explicitly selects it (selection starts at or before the opening brace)
- The block should NOT be extractable if the user selects part of its contents (selection starts after the opening brace)
- The block should NOT be extractable if the selection is completely within the block (traverse into statements instead)
So the check should be:
TypedExpr::Block { .. } => {
// Selection starts at or before the opening brace
// AND selection is not completely within the block
selected_range.start <= expression_range.start
&& !completely_within(selected_range, expression_range)
}
Actually wait, if the selection starts before the opening brace and ends after the closing brace, then completely_within would return false (because the selection is NOT within the block). So we'd extract the block. But in this case, the user is selecting a range that includes the block, so extracting it makes sense.
And if the selection starts at the opening brace and ends at the closing brace, completely_within would return false (because the selection touches the boundaries). So we'd extract the block. Good.
And if the selection starts after the opening brace (inside the block), selected_range.start <= expression_range.start is false. So we don't extract the block. Good.
This seems like the right fix! Let me implement it.
Actually wait, I realize selected_range.start <= expression_range.start is checking LSP positions. In LSP, positions are compared lexicographically (line first, then character). So this should work.
Let me implement the fix:
TypedExpr::Block { .. } => {
selected_range.start <= expression_range.start
&& !completely_within(selected_range, expression_range)
}
Wait, but I also need to make sure the block overlaps with the selection. The overlaps check at the beginning of can_extract_expression already handles this.
Hmm, but what if the selection starts before the block and doesn't overlap with it? In that case, overlaps would return false, and we'd return false early. So the selected_range.start <= expression_range.start check would only be reached if there's an overlap.
OK I think this is the right fix. Let me implement it.