Files
zed/crates/path/src/path_component.rs
T
Xin Zhao 9521840152 path: Reimplement PathStyle::join based on the standard library's implementation (#65966)
## Summary

Final follow-up of #64149, this PR reimplements `PathStyle::join()` on
top of `std::path::PathBuf::push`, via a new `PathStyle`-aware
`PathBufExt::styled_push` helper. The old `join_path()` and
`join_path_preserving_components()` are removed, and their call sites
are migrated as follows:

- `join` -> `join`
- `join_path` -> `join` + `normalize_lexically`
- `join_path_preserving_components` -> `join`, plus
`normalize_separators` only where the joined path is displayed to the
user

I'm confident that the new `join()` mirrors std's behavior. The main
thing to be aware of is that the old `join` rejected a rooted right-hand
side and returned `None`, while the new one accepts it and handles it:
the left-hand side is replaced entirely, except for a root-only operand
such as `\b` on Windows, which keeps the left side's prefix (`C:\a` +
`\b` = `C:\b`).

Because the old `join` rejected rooted right-hand sides, all migrated
call sites were audited for `has_root`: the right operand either cannot
be rooted by construction, or the call site already guards rooted inputs
with `has_root`, or an explicit guard was added here.

One edge case was noticed but left unchanged: a drive-relative operand
such as `C:foo.rs` is now replaced instead of concatenated (mirroring
std). This case was equally unhandled before, so it is left as-is here;
adding another check beyond the existing `has_root` guard would not be
self-explanatory either. #65911 (git worktree names containing path
components) is likewise pre-existing and tracked separately.

## Testing

New tests are added for the new `join` method, adapted from the std lib.
The tests of the affected caller crates have been run to prevent
regressions, but this is not a guarantee.

## Self-review

- [x] I've reviewed my diff for quality, security, reliability, and
performance.
- [x] UI changes follow the
[checklist](https://zed.dev/docs/development/ui-checklist).
- [x] Tests cover the new or changed behavior.

Release Notes:

- N/A
2026-10-28 15:21:52 +00:00

578 lines
18 KiB
Rust

//! Path component parsing adapted from the Rust standard library
//! (`std::path::Components` in rust-lang/rust's `library/std/src/path.rs`,
//! revision 315ecf4a9).
//!
//! The code is largely a copy of upstream; the only notable changes are
//! `PathStyle`-related: the `cfg(windows)`/`cfg(unix)` branches are replaced
//! with runtime checks on [`PathStyle`], and helpers that `std` defines as
//! private inherent methods on `Prefix` live in the local [`PrefixExt`] trait.
use crate::PathStyle;
use std::ffi::{OsStr, OsString};
pub use std::path::Prefix;
use std::path::{Path, PathBuf};
pub(crate) trait PrefixExt {
fn len(&self) -> usize;
fn is_drive(&self) -> bool;
#[inline]
fn has_implicit_root(&self) -> bool {
!self.is_drive()
}
}
impl PrefixExt for Prefix<'_> {
#[inline]
fn len(&self) -> usize {
use self::Prefix::*;
fn os_str_len(s: &OsStr) -> usize {
s.as_encoded_bytes().len()
}
match *self {
Verbatim(x) => 4 + os_str_len(x),
VerbatimUNC(x, y) => {
8 + os_str_len(x)
+ if os_str_len(y) > 0 {
1 + os_str_len(y)
} else {
0
}
}
VerbatimDisk(_) => 6,
UNC(x, y) => {
2 + os_str_len(x)
+ if os_str_len(y) > 0 {
1 + os_str_len(y)
} else {
0
}
}
DeviceNS(x) => 4 + os_str_len(x),
Disk(_) => 2,
}
}
#[inline]
fn is_drive(&self) -> bool {
matches!(*self, Prefix::Disk(_))
}
}
// Iterate through `iter` while it matches `prefix`; return `None` if `prefix`
// is not a prefix of `iter`, otherwise return `Some(iter_after_prefix)` giving
// `iter` after having exhausted `prefix`.
pub(crate) fn iter_after<'a, 'b, I, J>(mut iter: I, mut prefix: J) -> Option<I>
where
I: Iterator<Item = Component<'a>> + Clone,
J: Iterator<Item = Component<'b>>,
{
loop {
let mut iter_next = iter.clone();
match (iter_next.next(), prefix.next()) {
(Some(ref x), Some(ref y)) if x == y => (),
(Some(_), Some(_)) => return None,
(Some(_), None) => return Some(iter),
(None, None) => return Some(iter),
(None, Some(_)) => return None,
}
iter = iter_next;
}
}
#[derive(PartialEq, PartialOrd, Clone)]
enum State {
Prefix = 0, // c:
StartDir = 1, // / or . or nothing
Body = 2, // foo/bar/baz
Done = 3,
}
#[allow(dead_code)]
pub(crate) struct PrefixComponent<'a> {
/// The prefix as an unparsed `OsStr` slice.
raw: &'a OsStr,
/// The parsed prefix data.
parsed: Prefix<'a>,
}
impl<'a> PartialEq for PrefixComponent<'a> {
#[inline]
fn eq(&self, other: &PrefixComponent<'a>) -> bool {
self.parsed == other.parsed
}
}
#[derive(PartialEq)]
pub(crate) enum Component<'a> {
/// A Windows path prefix, e.g., `C:` or `\\server\share`.
///
/// There is a large variety of prefix types, see [`Prefix`]'s documentation
/// for more.
///
/// Does not occur on Unix.
Prefix(PrefixComponent<'a>),
/// The root directory component, appears after any prefix and before anything else.
///
/// It represents a separator that designates that a path starts from root.
RootDir,
/// A reference to the current directory, i.e., `.`.
CurDir,
/// A reference to the parent directory, i.e., `..`.
ParentDir,
/// A normal component, e.g., `a` and `b` in `a/b`.
///
/// This variant is the most common one, it represents references to files
/// or directories.
Normal(&'a OsStr),
}
impl<'a> Component<'a> {
pub fn as_os_str(&self, path_style: PathStyle) -> &'a OsStr {
match self {
Component::Prefix(p) => p.raw,
Component::RootDir => OsStr::new(path_style.primary_separator()),
Component::CurDir => OsStr::new("."),
Component::ParentDir => OsStr::new(".."),
Component::Normal(path) => path,
}
}
}
#[derive(Clone)]
pub(crate) struct Components<'a> {
path_style: PathStyle,
// The path left to parse components from
path: &'a [u8],
// The prefix as it was originally parsed, if any
prefix: Option<Prefix<'a>>,
// true if path *physically* has a root separator; for most Windows
// prefixes, it may have a "logical" root separator for the purposes of
// normalization, e.g., \\server\share == \\server\share\.
has_physical_root: bool,
// The iterator is double-ended, and these two states keep track of what has
// been produced from either end
front: State,
back: State,
}
impl<'a> Components<'a> {
pub fn new(path_style: PathStyle, path: &'a Path) -> Self {
let prefix = path_style.parse_prefix(path.as_os_str());
Components {
path_style,
path: path.as_os_str().as_encoded_bytes(),
prefix,
has_physical_root: path_style
.has_physical_root(path.as_os_str().as_encoded_bytes(), prefix),
// use a platform-specific initial state to avoid one turn of
// the state-machine when the platform doesn't have a Prefix.
front: if path_style.has_prefixes() {
State::Prefix
} else {
State::StartDir
},
back: State::Body,
}
}
pub(crate) fn prefix(&self) -> Option<Prefix<'_>> {
self.prefix
}
fn has_prefixes(&self) -> bool {
self.path_style.has_prefixes()
}
#[inline]
fn prefix_len(&self) -> usize {
if !self.has_prefixes() {
return 0;
}
self.prefix.as_ref().map(Prefix::len).unwrap_or(0)
}
#[inline]
fn prefix_verbatim(&self) -> bool {
if !self.has_prefixes() {
return false;
}
self.prefix
.as_ref()
.map(Prefix::is_verbatim)
.unwrap_or(false)
}
#[inline]
fn prefix_remaining(&self) -> usize {
if !self.has_prefixes() {
return 0;
}
if self.front == State::Prefix {
self.prefix_len()
} else {
0
}
}
#[inline]
fn len_before_body(&self) -> usize {
let root = if self.front <= State::StartDir && self.has_physical_root {
1
} else {
0
};
let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() {
1
} else {
0
};
self.prefix_remaining() + root + cur_dir
}
#[inline]
fn finished(&self) -> bool {
self.front == State::Done || self.back == State::Done || self.front > self.back
}
#[inline]
fn is_sep_byte(&self, b: u8) -> bool {
if self.prefix_verbatim() {
self.path_style.is_verbatim_sep(b)
} else {
self.path_style.is_sep_byte(b)
}
}
pub fn as_path(&self) -> &'a Path {
let mut comps = self.clone();
if comps.front == State::Body {
comps.trim_left();
}
if comps.back == State::Body {
comps.trim_right();
}
unsafe { Path::new(OsStr::from_encoded_bytes_unchecked(comps.path)) }
}
pub(crate) fn has_root(&self) -> bool {
if self.has_physical_root {
return true;
}
if self.has_prefixes()
&& let Some(p) = self.prefix
{
if p.has_implicit_root() {
return true;
}
}
false
}
fn include_cur_dir(&self) -> bool {
if self.has_root() {
return false;
}
let slice = &self.path[self.prefix_remaining()..];
match slice {
[b'.'] => true,
[b'.', b, ..] => self.is_sep_byte(*b),
_ => false,
}
}
unsafe fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option<Component<'b>> {
match comp {
b"." if self.has_prefixes() && self.prefix_verbatim() => Some(Component::CurDir),
b"." => None, // . components are normalized away, except at
// the beginning of a path, which is treated
// separately via `include_cur_dir`
b".." => Some(Component::ParentDir),
b"" => None,
_ => Some(Component::Normal(unsafe {
OsStr::from_encoded_bytes_unchecked(comp)
})),
}
}
fn parse_next_component(&self) -> (usize, Option<Component<'a>>) {
debug_assert!(self.front == State::Body);
let (extra, comp) = match self.path.iter().position(|b| self.is_sep_byte(*b)) {
None => (0, self.path),
Some(i) => (1, &self.path[..i]),
};
// SAFETY: `comp` is a valid substring, since it is split on a separator.
(comp.len() + extra, unsafe {
self.parse_single_component(comp)
})
}
fn parse_next_component_back(&self) -> (usize, Option<Component<'a>>) {
debug_assert!(self.back == State::Body);
let start = self.len_before_body();
let (extra, comp) = match self.path[start..]
.iter()
.rposition(|b| self.is_sep_byte(*b))
{
None => (0, &self.path[start..]),
Some(i) => (1, &self.path[start + i + 1..]),
};
// SAFETY: `comp` is a valid substring, since it is split on a separator.
(comp.len() + extra, unsafe {
self.parse_single_component(comp)
})
}
fn trim_left(&mut self) {
while !self.path.is_empty() {
let (size, comp) = self.parse_next_component();
if comp.is_some() {
return;
} else {
self.path = &self.path[size..];
}
}
}
fn trim_right(&mut self) {
while self.path.len() > self.len_before_body() {
let (size, comp) = self.parse_next_component_back();
if comp.is_some() {
return;
} else {
self.path = &self.path[..self.path.len() - size];
}
}
}
}
impl<'a> Iterator for Components<'a> {
type Item = Component<'a>;
fn next(&mut self) -> Option<Component<'a>> {
while !self.finished() {
match self.front {
// most likely case first
State::Body if !self.path.is_empty() => {
let (size, comp) = self.parse_next_component();
self.path = &self.path[size..];
if comp.is_some() {
return comp;
}
}
State::Body => {
self.front = State::Done;
}
State::StartDir => {
self.front = State::Body;
if self.has_physical_root {
debug_assert!(!self.path.is_empty());
self.path = &self.path[1..];
return Some(Component::RootDir);
} else if self.has_prefixes()
&& let Some(p) = self.prefix
{
if p.has_implicit_root() && !p.is_verbatim() {
return Some(Component::RootDir);
}
} else if self.include_cur_dir() {
debug_assert!(!self.path.is_empty());
self.path = &self.path[1..];
return Some(Component::CurDir);
}
}
_ if !self.has_prefixes() => unreachable!(),
State::Prefix if self.prefix_len() == 0 => {
self.front = State::StartDir;
}
State::Prefix => {
self.front = State::StartDir;
debug_assert!(self.prefix_len() <= self.path.len());
let raw = &self.path[..self.prefix_len()];
self.path = &self.path[self.prefix_len()..];
return Some(Component::Prefix(PrefixComponent {
raw: unsafe { OsStr::from_encoded_bytes_unchecked(raw) },
parsed: self.prefix.unwrap(),
}));
}
State::Done => unreachable!(),
}
}
None
}
}
impl<'a> DoubleEndedIterator for Components<'a> {
fn next_back(&mut self) -> Option<Component<'a>> {
while !self.finished() {
match self.back {
State::Body if self.path.len() > self.len_before_body() => {
let (size, comp) = self.parse_next_component_back();
self.path = &self.path[..self.path.len() - size];
if comp.is_some() {
return comp;
}
}
State::Body => {
self.back = State::StartDir;
}
State::StartDir => {
self.back = if self.has_prefixes() {
State::Prefix
} else {
State::Done
};
if self.has_physical_root {
self.path = &self.path[..self.path.len() - 1];
return Some(Component::RootDir);
} else if self.has_prefixes()
&& let Some(p) = self.prefix
{
if p.has_implicit_root() && !p.is_verbatim() {
return Some(Component::RootDir);
}
} else if self.include_cur_dir() {
self.path = &self.path[..self.path.len() - 1];
return Some(Component::CurDir);
}
}
_ if !self.has_prefixes() => unreachable!(),
State::Prefix if self.prefix_len() > 0 => {
self.back = State::Done;
return Some(Component::Prefix(PrefixComponent {
raw: unsafe { OsStr::from_encoded_bytes_unchecked(self.path) },
parsed: self.prefix.unwrap(),
}));
}
State::Prefix => {
self.back = State::Done;
return None;
}
State::Done => unreachable!(),
}
}
None
}
}
// basic workhorse for splitting stem and extension
pub(crate) fn rsplit_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) {
if file.as_encoded_bytes() == b".." {
return (Some(file), None);
}
// The unsafety here stems from converting between &OsStr and &[u8]
// and back. This is safe to do because (1) we only look at ASCII
// contents of the encoding and (2) new &OsStr values are produced
// only from ASCII-bounded slices of existing &OsStr values.
let mut iter = file.as_encoded_bytes().rsplitn(2, |b| *b == b'.');
let after = iter.next();
let before = iter.next();
if before == Some(b"") {
(Some(file), None)
} else {
unsafe {
(
before.map(|s| OsStr::from_encoded_bytes_unchecked(s)),
after.map(|s| OsStr::from_encoded_bytes_unchecked(s)),
)
}
}
}
pub(crate) trait PathBufExt {
fn styled_push(&mut self, path: impl AsRef<Path>, path_style: PathStyle);
}
impl PathBufExt for PathBuf {
fn styled_push(&mut self, path: impl AsRef<Path>, path_style: PathStyle) {
let path = path.as_ref();
// in general, a separator is needed if the rightmost byte is not a separator
let buf = self.as_os_str().as_encoded_bytes();
let mut need_sep = buf
.last()
.map(|c| !path_style.is_sep_byte(*c))
.unwrap_or(false);
// in the special case of `C:` on Windows, do *not* add a separator
let comps = path_style.components(self);
if comps.prefix_len() > 0
&& comps.prefix_len() == comps.path.len()
&& comps.prefix.is_some_and(|p| p.is_drive())
{
need_sep = false
}
let path_comps = path_style.components(path);
// absolute `path` replaces `self`
if path_style.is_absolute(path) || path_comps.prefix().is_some() {
self.clear();
// verbatim paths need . and .. removed
} else if comps.prefix_verbatim() && !path.is_empty() {
let mut buf: Vec<_> = comps.collect();
for c in path_comps {
match c {
Component::RootDir => {
buf.truncate(1);
buf.push(c);
}
Component::CurDir => (),
Component::ParentDir => {
if let Some(Component::Normal(_)) = buf.last() {
buf.pop();
}
}
_ => buf.push(c),
}
}
let mut res = OsString::new();
let mut need_sep = false;
for c in buf {
if need_sep && c != Component::RootDir {
res.push(path_style.primary_separator());
}
res.push(c.as_os_str(path_style));
need_sep = match c {
Component::RootDir => false,
Component::Prefix(prefix) => {
!prefix.parsed.is_drive() && prefix.parsed.len() > 0
}
_ => true,
}
}
*self.as_mut_os_string() = res;
return;
// `path` has a root but no prefix, e.g., `\windows` (Windows only)
} else if path_style.has_root(path) {
let prefix = match path_style.components(self).next() {
Some(Component::Prefix(prefix)) => prefix.raw.to_os_string(),
_ => OsString::new(),
};
*self.as_mut_os_string() = prefix;
// `path` is a pure relative path
} else if need_sep {
self.as_mut_os_string().push(path_style.primary_separator());
}
self.as_mut_os_string().push(path);
}
}