Description
Immediate problem: In the following code, when the mentioned assist is triggered, all but the last either panic or produce bogus code. The last one had also panicked before #12789.
Code
// inline into all callers (bogus output)
fn inline_me/*$0*/(a: i32) -> i32 { a }
fn test1() {
inline_me(inline_me(0));
}
// inline type alias (panic)
type Alias/*$0*/<T> = Vec<T>;
fn test2(_: Alias<Alias<i32>>) {}
// convert to named struct (panic)
struct Tuple/*$0*/<T>(T);
fn test3() {
let _ = Tuple(Tuple(0));
}
// convert to tuple struct (panic)
struct Named/*$0*/<T> { inner: T }
fn test4() {
let _ = Named {
inner: Named {
inner: 0,
}
};
}
// remove unused parameter (handles correctly!)
fn unused(a/*$0*/: i32) -> i32 { 0 }
fn test5() {
unused(unused(5));
}
Problem: SourceChangeBuilder
is easy to use, but also easy to misuse when the assist operates on self-nestable nodes (e.g. record expressions can be embedded into another record expression) because there is an invariant for the edits: each range of the edits MUST NOT overlap with each other.
We can avoid violating the invariant by:
- retrieve all nodes/ranges to modify
- check if one is contained in another, build a forest whose each tree represent disjoint nodes
- make the root node of each tree in the forest mutable, and then start mutating the nodes in the order of innermost to outermost
- turn the modifications into text edits
(This is just an example generic procedure that should work for all cases, there may be better/more efficient procedures depending on the assist)
Currently we should implement this for every assist that may operate on overlappable nodes, but manually doing so is extremely error-prone. There should be another API that wraps SourceChangeBuilder
(or anything needed) and does things correctly without much care from its users.
Feel free to change the issue title, I'm obviously not the best person to come up with a good title.