rust-lang / rust-lang/rust-analyzer
Detect and Fix Overscope unsafe Block
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 16.9k
- Forks
- 2.2k
- Avg merge
- 1d 12h
- Merged PRs (30d)
- 72
Description
In actual development, I often see unsafe blocks of code that are abused. For example, in one version of the Smallvec library there is a function that looks like this:
pub fn grow(&mut self, new_cap: usize) {
unsafe {
let (ptr, &mut len, cap) = self.triple_mut();
let unspilled = !self.spilled();
assert!(new_cap >= len);
if new_cap <= self.inline_size() {
if unspilled {
return;
}
self.data = SmallVecData::from_inline(mem::uninitialized());
ptr::copy_nonoverlapping(ptr, self.data.inline_mut().ptr_mut(), len);
} else if new_cap != cap {
let mut vec = Vec::with_capacity(new_cap);
let new_alloc = vec.as_mut_ptr();
mem::forget(vec);
ptr::copy_nonoverlapping(ptr, new_alloc, len);
self.data = SmallVecData::from_heap(new_alloc, len);
self.capacity = new_cap;
if unspilled {
return;
}
}
deallocate(ptr, cap);
}
}
It obviously uses an unsafe block more than necessary, putting the entire function in an unsafe block. This can be disruptive to subsequent developers, who are unsure what part is truly unsafe. It would be better to use an unsafe block only to the smallest extent, using several small unsafe blocks of code, rather than an entire unsafe block that contains all functions. I want to try to implement a feature that can automatically detect (or, one step further, fix) such situations. Can rust-analyzer do this now, and is it necessary to add this feature?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by investigating whether rust-analyzer currently detects oversized unsafe blocks or can apply a safe narrowing assist. Use the Smallvec grow example in the issue as the motivating case. Done would be a clear feasibility and scope decision for detection or automated fixing, rather than an implementation based on an unspecified design.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100