<ins> // Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Windows file path handling use ascii::AsciiCast; use c_str::{CString, ToCStr}; use cast; use cmp::Eq; use from_str::FromStr; use iter::{AdditiveIterator, Extendable, Iterator}; use option::{Option, Some, None}; use str; use str::{OwnedStr, Str, StrVector}; use util; use vec::Vector; use super::{GenericPath, GenericPathUnsafe}; /// Iterator that yields successive components of a Path pub type ComponentIter<'self> = str::CharSplitIterator<'self, char>; /// Represents a Windows path // Notes for Windows path impl: // The MAX_PATH is 260, but 253 is the practical limit due to some API bugs // See http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx for good information // about windows paths. // That same page puts a bunch of restrictions on allowed characters in a path. // `foo.txt` means "relative to current drive", but will not be considered to be absolute here // as `∃P | P.join("foo.txt") != "foo.txt"`. // `C:` is interesting, that means "the current directory on drive C". // Long absolute paths need to have ? prefix (or, for UNC, ?UNC). I think that can be // ignored for now, though, and only added in a hypothetical .to_pwstr() function. // However, if a path is parsed that has ?, this needs to be preserved as it disables the // processing of "." and ".." components and / as a separator. // Experimentally, ?foo is not the same thing as foo. // Also, foo is not valid either (certainly not equivalent to foo). // Similarly, C:Users is not equivalent to C:Users, although C:Usersfoo is equivalent // to C:Usersfoo. In fact the command prompt treats C:foobar as UNC path. But it might be // best to just ignore that and normalize it to C:foobar. // // Based on all this, I think the right approach is to do the following: // * Require valid utf-8 paths. Windows API may use WCHARs, but we don't, and utf-8 is convertible // to UTF-16 anyway (though does Windows use UTF-16 or UCS-2? Not sure). // * Parse the prefixes ?UNC, ?, and . explicitly. // * If ?UNC, treat following two path components as servershare. Don't error for missing //   servershare. // * If ?, parse disk from following component, if present. Don't error for missing disk. // * If ., treat rest of path as just regular components. I don't know how . and .. are handled //   here, they probably aren't, but I'm not going to worry about that. // * Else if starts with , treat following two components as servershare. Don't error for missing //   servershare. // * Otherwise, attempt to parse drive from start of path. // // The only error condition imposed here is valid utf-8. All other invalid paths are simply // preserved by the data structure; let the Windows API error out on them. #[deriving(Clone, DeepClone)] pub struct Path { priv repr: ~str, // assumed to never be empty priv prefix: Option<PathPrefix>, priv sepidx: Option<uint> // index of the final separator in the non-prefix portion of repr } impl Eq for Path { #[inline] fn eq(&self, other: &Path) -> bool { self.repr == other.repr } } impl FromStr for Path { fn from_str(s: &str) -> Option<Path> { if contains_nul(s.as_bytes()) { None } else { Some(unsafe { GenericPathUnsafe::from_str_unchecked(s) }) } } } impl ToCStr for Path { #[inline] fn to_c_str(&self) -> CString { // The Path impl guarantees no embedded NULs unsafe { self.as_vec().to_c_str_unchecked() } } #[inline] unsafe fn to_c_str_unchecked(&self) -> CString { self.as_vec().to_c_str_unchecked() } } impl GenericPathUnsafe for Path { /// See `GenericPathUnsafe::from_vec_unchecked`. /// /// # Failure /// /// Raises the `str::not_utf8` condition if not valid UTF-8. #[inline] unsafe fn from_vec_unchecked(path: &[u8]) -> Path { if !str::is_utf8(path) { let path = str::from_utf8(path); // triggers not_utf8 condition GenericPathUnsafe::from_str_unchecked(path) } else { GenericPathUnsafe::from_str_unchecked(cast::transmute(path)) } } #[inline] unsafe fn from_str_unchecked(path: &str) -> Path { let (prefix, path) = Path::normalize_(path); assert!(!path.is_empty()); let mut ret = Path{ repr: path, prefix: prefix, sepidx: None }; ret.update_sepidx(); ret } /// See `GenericPathUnsafe::set_dirname_unchecked`. /// /// # Failure /// /// Raises the `str::not_utf8` condition if not valid UTF-8. #[inline] unsafe fn set_dirname_unchecked(&mut self, dirname: &[u8]) { if !str::is_utf8(dirname) { let dirname = str::from_utf8(dirname); // triggers not_utf8 condition self.set_dirname_str_unchecked(dirname); } else { self.set_dirname_str_unchecked(cast::transmute(dirname)) } } unsafe fn set_dirname_str_unchecked(&mut self, dirname: &str) { match self.sepidx_or_prefix_len() { None if "." == self.repr || ".." == self.repr => { self.update_normalized(dirname); } None => { let mut s = str::with_capacity(dirname.len() + self.repr.len() + 1); s.push_str(dirname); s.push_char(sep); s.push_str(self.repr); self.update_normalized(s); } Some((_,idxa,end)) if self.repr.slice(idxa,end) == ".." => { self.update_normalized(dirname); } Some((_,idxa,end)) if dirname.is_empty() => { let (prefix, path) = Path::normalize_(self.repr.slice(idxa,end)); self.repr = path; self.prefix = prefix; self.update_sepidx(); } Some((idxb,idxa,end)) => { let idx = if dirname.ends_with("") { idxa } else { let prefix = parse_prefix(dirname); if prefix == Some(DiskPrefix) && prefix_len(prefix) == dirname.len() { idxa } else { idxb } }; let mut s = str::with_capacity(dirname.len() + end - idx); s.push_str(dirname); s.push_str(self.repr.slice(idx,end)); self.update_normalized(s); } } } /// See `GenericPathUnsafe::set_filename_unchecekd`. /// /// # Failure /// /// Raises the `str::not_utf8` condition if not valid UTF-8. #[inline] unsafe fn set_filename_unchecked(&mut self, filename: &[u8]) { if !str::is_utf8(filename) { let filename = str::from_utf8(filename); // triggers not_utf8 condition self.set_filename_str_unchecked(filename) } else { self.set_filename_str_unchecked(cast::transmute(filename)) } } unsafe fn set_filename_str_unchecked(&mut self, filename: &str) { match self.sepidx_or_prefix_len() { None if ".." == self.repr => { let mut s = str::with_capacity(3 + filename.len()); s.push_str(".."); s.push_char(sep); s.push_str(filename); self.update_normalized(s); } None => { self.update_normalized(filename); } Some((_,idxa,end)) if self.repr.slice(idxa,end) == ".." => { let mut s = str::with_capacity(end + 1 + filename.len()); s.push_str(self.repr.slice_to(end)); s.push_char(sep); s.push_str(filename); self.update_normalized(s); } Some((idxb,idxa,_)) if self.prefix == Some(DiskPrefix) && idxa == self.prefix_len() => { let mut s = str::with_capacity(idxb + filename.len()); s.push_str(self.repr.slice_to(idxb)); s.push_str(filename); self.update_normalized(s); } Some((idxb,_,_)) => { let mut s = str::with_capacity(idxb + 1 + filename.len()); s.push_str(self.repr.slice_to(idxb)); s.push_char(sep); s.push_str(filename); self.update_normalized(s); } } } /// See `GenericPathUnsafe::push_unchecked`. /// /// # Failure /// /// Raises the `str::not_utf8` condition if not valid UTF-8. unsafe fn push_unchecked(&mut self, path: &[u8]) { if !str::is_utf8(path) { let path = str::from_utf8(path); // triggers not_utf8 condition self.push_str_unchecked(path); } else { self.push_str_unchecked(cast::transmute(path)); } } /// See `GenericPathUnsafe::push_str_unchecked`. /// /// Concatenating two Windows Paths is rather complicated. /// For the most part, it will behave as expected, except in the case of /// pushing a volume-relative path, e.g. `C:foo.txt`. Because we have no /// concept of per-volume cwds like Windows does, we can't behave exactly /// like Windows will. Instead, if the receiver is an absolute path on /// the same volume as the new path, it will be treated as the cwd that /// the new path is relative to. Otherwise, the new path will be treated /// as if it were absolute and will replace the receiver outright. unsafe fn push_str_unchecked(&mut self, path: &str) { fn is_vol_abs(path: &str, prefix: Option<PathPrefix>) -> bool { // assume prefix is Some(DiskPrefix) let rest = path.slice_from(prefix_len(prefix)); !rest.is_empty() && rest[0].is_ascii() && is_sep2(rest[0] as char) } fn shares_volume(me: &Path, path: &str) -> bool { // path is assumed to have a prefix of Some(DiskPrefix) match me.prefix { Some(DiskPrefix) => me.repr[0] == path[0].to_ascii().to_upper().to_byte(), Some(VerbatimDiskPrefix) => me.repr[4] == path[0].to_ascii().to_upper().to_byte(), _ => false } } fn is_sep_(prefix: Option<PathPrefix>, u: u8) -> bool { u.is_ascii() && if prefix_is_verbatim(prefix) { is_sep(u as char) } else { is_sep2(u as char) } } fn replace_path(me: &mut Path, path: &str, prefix: Option<PathPrefix>) { let newpath = Path::normalize__(path, prefix); me.repr = match newpath { Some(p) => p, None => path.to_owned() }; me.prefix = prefix; me.update_sepidx(); } fn append_path(me: &mut Path, path: &str) { // appends a path that has no prefix // if me is verbatim, we need to pre-normalize the new path let path_ = if me.is_verbatim() { Path::normalize__(path, None) } else { None }; let pathlen = path_.map_default(path.len(), |p| p.len()); let mut s = str::with_capacity(me.repr.len() + 1 + pathlen); s.push_str(me.repr); let plen = me.prefix_len(); if !(me.repr.len() > plen && me.repr[me.repr.len()-1] == sep as u8) { s.push_char(sep); } match path_ { None => s.push_str(path), Some(p) => s.push_str(p) }; me.update_normalized(s) } if !path.is_empty() { let prefix = parse_prefix(path); match prefix { Some(DiskPrefix) if !is_vol_abs(path, prefix) && shares_volume(self, path) => { // cwd-relative path, self is on the same volume append_path(self, path.slice_from(prefix_len(prefix))); } Some(_) => { // absolute path, or cwd-relative and self is not same volume replace_path(self, path, prefix); } None if !path.is_empty() && is_sep_(self.prefix, path[0]) => { // volume-relative path if self.prefix().is_some() { // truncate self down to the prefix, then append let n = self.prefix_len(); self.repr.truncate(n); append_path(self, path); } else { // we have no prefix, so nothing to be relative to replace_path(self, path, prefix); } } None => { // relative path append_path(self, path); } } } } } impl GenericPath for Path { /// See `GenericPath::as_str` for info. /// Always returns a `Some` value. #[inline] fn as_str<'a>(&'a self) -> Option<&'a str> { Some(self.repr.as_slice()) } #[inline] fn as_vec<'a>(&'a self) -> &'a [u8] { self.repr.as_bytes() } #[inline] fn dirname<'a>(&'a self) -> &'a [u8] { self.dirname_str().unwrap().as_bytes() } /// See `GenericPath::dirname_str` for info. /// Always returns a `Some` value. fn dirname_str<'a>(&'a self) -> Option<&'a str> { Some(match self.sepidx_or_prefix_len() { None if ".." == self.repr => self.repr.as_slice(), None => ".", Some((_,idxa,end)) if self.repr.slice(idxa, end) == ".." => { self.repr.as_slice() } Some((idxb,_,end)) if self.repr.slice(idxb, end) == "" => { self.repr.as_slice() } Some((0,idxa,_)) => self.repr.slice_to(idxa), Some((idxb,idxa,_)) => { match self.prefix { Some(DiskPrefix) | Some(VerbatimDiskPrefix) if idxb == self.prefix_len() => { self.repr.slice_to(idxa) } _ => self.repr.slice_to(idxb) } } }) } #[inline] fn filename<'a>(&'a self) -> &'a [u8] { self.filename_str().unwrap().as_bytes() } /// See `GenericPath::filename_str` for info. /// Always returns a `Some` value. fn filename_str<'a>(&'a self) -> Option<&'a str> { Some(match self.sepidx_or_prefix_len() { None if "." == self.repr || ".." == self.repr => "", None => self.repr.as_slice(), Some((_,idxa,end)) if self.repr.slice(idxa, end) == ".." => "", Some((_,idxa,end)) => self.repr.slice(idxa, end) }) } /// See `GenericPath::filestem_str` for info. /// Always returns a `Some` value. #[inline] fn filestem_str<'a>(&'a self) -> Option<&'a str> { // filestem() returns a byte vector that's guaranteed valid UTF-8 Some(unsafe { cast::transmute(self.filestem()) }) } #[inline] fn extension_str<'a>(&'a self) -> Option<&'a str> { // extension() returns a byte vector that's guaranteed valid UTF-8 self.extension().map_move(|v| unsafe { cast::transmute(v) }) } fn dir_path(&self) -> Path { unsafe { GenericPathUnsafe::from_str_unchecked(self.dirname_str().unwrap()) } } fn file_path(&self) -> Option<Path> { match self.filename_str() { None | Some("") => None, Some(s) => Some(unsafe { GenericPathUnsafe::from_str_unchecked(s) }) } } #[inline] fn push_path(&mut self, path: &Path) { self.push_str(path.as_str().unwrap()) } #[inline] fn pop_opt(&mut self) -> Option<~[u8]> { self.pop_opt_str().map_move(|s| s.into_bytes()) } fn pop_opt_str(&mut self) -> Option<~str> { match self.sepidx_or_prefix_len() { None if "." == self.repr => None, None => { let mut s = ~"."; util::swap(&mut s, &mut self.repr); self.sepidx = None; Some(s) } Some((idxb,idxa,end)) if idxb == idxa && idxb == end => None, Some((idxb,_,end)) if self.repr.slice(idxb, end) == "" => None, Some((idxb,idxa,end)) => { let s = self.repr.slice(idxa, end).to_owned(); let trunc = match self.prefix { Some(DiskPrefix) | Some(VerbatimDiskPrefix) | None => { let plen = self.prefix_len(); if idxb == plen { idxa } else { idxb } } _ => idxb }; self.repr.truncate(trunc); self.update_sepidx(); Some(s) } } } /// See `GenericPath::is_absolute` for info. /// /// A Windows Path is considered absolute only if it has a non-volume prefix, /// or if it has a volume prefix and the path starts with ''. /// A path of `foo` is not considered absolute because it's actually /// relative to the "current volume". A separate method `Path::is_vol_relative` /// is provided to indicate this case. Similarly a path of `C:foo` is not /// considered absolute because it's relative to the cwd on volume C:. A /// separate method `Path::is_cwd_relative` is provided to indicate this case. #[inline] fn is_absolute(&self) -> bool { match self.prefix { Some(DiskPrefix) => { let rest = self.repr.slice_from(self.prefix_len()); rest.len() > 0 && rest[0] == sep as u8 } Some(_) => true, None => false } } fn is_ancestor_of(&self, other: &Path) -> bool { if !self.equiv_prefix(other) { false } else if self.is_absolute() != other.is_absolute() || self.is_vol_relative() != other.is_vol_relative() { false } else { let mut ita = self.component_iter(); let mut itb = other.component_iter(); if "." == self.repr { return itb.next() != Some(".."); } loop { match (ita.next(), itb.next()) { (None, _) => break, (Some(a), Some(b)) if a == b => { loop }, (Some(a), _) if a == ".." => { // if ita contains only .. components, it's an ancestor return ita.all(|x| x == ".."); } _ => return false } } true } } fn path_relative_from(&self, base: &Path) -> Option<Path> { fn comp_requires_verbatim(s: &str) -> bool { s == "." || s == ".." || s.contains_char(sep2) } if !self.equiv_prefix(base) { // prefixes differ if self.is_absolute() { Some(self.clone()) } else if self.prefix == Some(DiskPrefix) && base.prefix == Some(DiskPrefix) { // both drives, drive letters must differ or they'd be equiv Some(self.clone()) } else { None } } else if self.is_absolute() != base.is_absolute() { if self.is_absolute() { Some(self.clone()) } else { None } } else if self.is_vol_relative() != base.is_vol_relative() { if self.is_vol_relative() { Some(self.clone()) } else { None } } else { let mut ita = self.component_iter(); let mut itb = base.component_iter(); let mut comps = ~[]; let a_verb = self.is_verbatim(); let b_verb = base.is_verbatim(); loop { match (ita.next(), itb.next()) { (None, None) => break, (Some(a), None) if a_verb && comp_requires_verbatim(a) => { return Some(self.clone()) } (Some(a), None) => { comps.push(a); if !a_verb { comps.extend(&mut ita); break; } } (None, _) => comps.push(".."), (Some(a), Some(b)) if comps.is_empty() && a == b => (), (Some(a), Some(b)) if !b_verb && b == "." => { if a_verb && comp_requires_verbatim(a) { return Some(self.clone()) } else { comps.push(a) } } (Some(_), Some(b)) if !b_verb && b == ".." => return None, (Some(a), Some(_)) if a_verb && comp_requires_verbatim(a) => { return Some(self.clone()) } (Some(a), Some(_)) => { comps.push(".."); for _ in itb { comps.push(".."); } comps.push(a); if !a_verb { comps.extend(&mut ita); break; } } } } Some(Path::from_str(comps.connect(""))) } } } impl Path { /// Returns a new Path from a byte vector /// /// # Failure /// /// Raises the `null_byte` condition if the vector contains a NUL. /// Raises the `str::not_utf8` condition if invalid UTF-8. #[inline] pub fn new(v: &[u8]) -> Path { GenericPath::from_vec(v) } /// Returns a new Path from a string /// /// # Failure /// /// Raises the `null_byte` condition if the vector contains a NUL. #[inline] pub fn from_str(s: &str) -> Path { GenericPath::from_str(s) } /// Converts the Path into an owned byte vector pub fn into_vec(self) -> ~[u8] { self.repr.into_bytes() } /// Converts the Path into an owned string /// Returns an Option for compatibility with posix::Path, but the /// return value will always be Some. pub fn into_str(self) -> Option<~str> { Some(self.repr) } /// Returns a normalized string representation of a path, by removing all empty /// components, and unnecessary . and .. components. pub fn normalize<S: Str>(s: S) -> ~str { let (_, path) = Path::normalize_(s); path } /// Returns an iterator that yields each component of the path in turn. /// Does not yield the path prefix (including server/share components in UNC paths). /// Does not distinguish between volume-relative and relative paths, e.g. /// abc and abc. /// Does not distinguish between absolute and cwd-relative paths, e.g. /// C:foo and C:foo. pub fn component_iter<'a>(&'a self) -> ComponentIter<'a> { let s = match self.prefix { Some(_) => { let plen = self.prefix_len(); if self.repr.len() > plen && self.repr[plen] == sep as u8 { self.repr.slice_from(plen+1) } else { self.repr.slice_from(plen) } } None if self.repr[0] == sep as u8 => self.repr.slice_from(1), None => self.repr.as_slice() }; let ret = s.split_terminator_iter(sep); ret } /// Returns whether the path is considered "volume-relative", which means a path /// that looks like "foo". Paths of this form are relative to the current volume, /// but absolute within that volume. #[inline] pub fn is_vol_relative(&self) -> bool { self.prefix.is_none() && self.repr[0] == sep as u8 } /// Returns whether the path is considered "cwd-relative", which means a path /// with a volume prefix that is not absolute. This look like "C:foo.txt". Paths /// of this form are relative to the cwd on the given volume. #[inline] pub fn is_cwd_relative(&self) -> bool { self.prefix == Some(DiskPrefix) && !self.is_absolute() } /// Returns the PathPrefix for this Path #[inline] pub fn prefix(&self) -> Option<PathPrefix> { self.prefix } /// Returns whether the prefix is a verbatim prefix, i.e. ? #[inline] pub fn is_verbatim(&self) -> bool { prefix_is_verbatim(self.prefix) } fn equiv_prefix(&self, other: &Path) -> bool { match (self.prefix, other.prefix) { (Some(DiskPrefix), Some(VerbatimDiskPrefix)) => { self.is_absolute() && self.repr[0].to_ascii().eq_ignore_case(other.repr[4].to_ascii()) } (Some(VerbatimDiskPrefix), Some(DiskPrefix)) => { other.is_absolute() && self.repr[4].to_ascii().eq_ignore_case(other.repr[0].to_ascii()) } (Some(VerbatimDiskPrefix), Some(VerbatimDiskPrefix)) => { self.repr[4].to_ascii().eq_ignore_case(other.repr[4].to_ascii()) } (Some(UNCPrefix(_,_)), Some(VerbatimUNCPrefix(_,_))) => { self.repr.slice(2, self.prefix_len()) == other.repr.slice(8, other.prefix_len()) } (Some(VerbatimUNCPrefix(_,_)), Some(UNCPrefix(_,_))) => { self.repr.slice(8, self.prefix_len()) == other.repr.slice(2, other.prefix_len()) } (None, None) => true, (a, b) if a == b => { self.repr.slice_to(self.prefix_len()) == other.repr.slice_to(other.prefix_len()) } _ => false } } fn normalize_<S: Str>(s: S) -> (Option<PathPrefix>, ~str) { // make borrowck happy let (prefix, val) = { let prefix = parse_prefix(s.as_slice()); let path = Path::normalize__(s.as_slice(), prefix); (prefix, path) }; (prefix, match val { None => s.into_owned(), Some(val) => val }) } fn normalize__(s: &str, prefix: Option<PathPrefix>) -> Option<~str> { if prefix_is_verbatim(prefix) { // don't do any normalization match prefix { Some(VerbatimUNCPrefix(x, 0)) if s.len() == 8 + x => { // the server component has no trailing '' let mut s = s.into_owned(); s.push_char(sep); Some(s) } _ => None } } else { let (is_abs, comps) = normalize_helper(s, prefix); let mut comps = comps; match (comps.is_some(),prefix) { (false, Some(DiskPrefix)) => { if s[0] >= 'a' as u8 && s[0] <= 'z' as u8 { comps = Some(~[]); } } (false, Some(VerbatimDiskPrefix)) => { if s[4] >= 'a' as u8 && s[0] <= 'z' as u8 { comps = Some(~[]); } } _ => () } match comps { None => None, Some(comps) => { if prefix.is_some() && comps.is_empty() { match prefix.unwrap() { DiskPrefix => { let len = prefix_len(prefix) + is_abs as uint; let mut s = s.slice_to(len).to_owned(); s[0] = s[0].to_ascii().to_upper().to_byte(); if is_abs { s[2] = sep as u8; // normalize C:/ to C: } Some(s) } VerbatimDiskPrefix => { let len = prefix_len(prefix) + is_abs as uint; let mut s = s.slice_to(len).to_owned(); s[4] = s[4].to_ascii().to_upper().to_byte(); Some(s) } _ => { let plen = prefix_len(prefix); if s.len() > plen { Some(s.slice_to(plen).to_owned()) } else { None } } } } else if is_abs && comps.is_empty() { Some(str::from_char(sep)) } else { let prefix_ = s.slice_to(prefix_len(prefix)); let n = prefix_.len() + if is_abs { comps.len() } else { comps.len() - 1} + comps.iter().map(|v| v.len()).sum(); let mut s = str::with_capacity(n); match prefix { Some(DiskPrefix) => { s.push_char(prefix_[0].to_ascii().to_upper().to_char()); s.push_char(':'); } Some(VerbatimDiskPrefix) => { s.push_str(prefix_.slice_to(4)); s.push_char(prefix_[4].to_ascii().to_upper().to_char()); s.push_str(prefix_.slice_from(5)); } Some(UNCPrefix(a,b)) => { s.push_str(""); s.push_str(prefix_.slice(2, a+2)); s.push_char(sep); s.push_str(prefix_.slice(3+a, 3+a+b)); } Some(_) => s.push_str(prefix_), None => () } let mut it = comps.move_iter(); if !is_abs { match it.next() { None => (), Some(comp) => s.push_str(comp) } } for comp in it { s.push_char(sep); s.push_str(comp); } Some(s) } } } } } fn update_sepidx(&mut self) { let s = if self.has_nonsemantic_trailing_slash() { self.repr.slice_to(self.repr.len()-1) } else { self.repr.as_slice() }; let idx = s.rfind(if !prefix_is_verbatim(self.prefix) { is_sep2 } else { is_sep }); let prefixlen = self.prefix_len(); self.sepidx = idx.and_then(|x| if x < prefixlen { None } else { Some(x) }); } fn prefix_len(&self) -> uint { prefix_len(self.prefix) } // Returns a tuple (before, after, end) where before is the index of the separator // and after is the index just after the separator. // end is the length of the string, normally, or the index of the final character if it is // a non-semantic trailing separator in a verbatim string. // If the prefix is considered the separator, before and after are the same. fn sepidx_or_prefix_len(&self) -> Option<(uint,uint,uint)> { match self.sepidx { None => match self.prefix_len() { 0 => None, x => Some((x,x,self.repr.len())) }, Some(x) => { if self.has_nonsemantic_trailing_slash() { Some((x,x+1,self.repr.len()-1)) } else { Some((x,x+1,self.repr.len())) } } } } fn has_nonsemantic_trailing_slash(&self) -> bool { self.is_verbatim() && self.repr.len() > self.prefix_len()+1 && self.repr[self.repr.len()-1] == sep as u8 } fn update_normalized<S: Str>(&mut self, s: S) { let (prefix, path) = Path::normalize_(s); self.repr = path; self.prefix = prefix; self.update_sepidx(); } } /// The standard path separator character pub static sep: char = ''; /// The alternative path separator character pub static sep2: char = '/'; /// Returns whether the given byte is a path separator. /// Only allows the primary separator ''; use is_sep2 to allow '/'. #[inline] pub fn is_sep(c: char) -> bool { c == sep } /// Returns whether the given byte is a path separator. /// Allows both the primary separator '' and the alternative separator '/'. #[inline] pub fn is_sep2(c: char) -> bool { c == sep || c == sep2 } /// Prefix types for Path #[deriving(Eq, Clone, DeepClone)] pub enum PathPrefix { /// Prefix `?`, uint is the length of the following component VerbatimPrefix(uint), /// Prefix `?UNC`, uints are the lengths of the UNC components VerbatimUNCPrefix(uint, uint), /// Prefix `?C:` (for any alphabetic character) VerbatimDiskPrefix, /// Prefix `.`, uint is the length of the following component DeviceNSPrefix(uint), /// UNC prefix `servershare`, uints are the lengths of the server/share UNCPrefix(uint, uint), /// Prefix `C:` for any alphabetic character DiskPrefix } /// Internal function; only public for tests. Don't use. // FIXME (#8169): Make private once visibility is fixed pub fn parse_prefix<'a>(mut path: &'a str) -> Option<PathPrefix> { if path.starts_with("") { //  path = path.slice_from(2); if path.starts_with("?") { // ? path = path.slice_from(2); if path.starts_with("UNC") { // ?UNCservershare path = path.slice_from(4); let (idx_a, idx_b) = match parse_two_comps(path, is_sep) { Some(x) => x, None => (path.len(), 0) }; return Some(VerbatimUNCPrefix(idx_a, idx_b)); } else { // ?path let idx = path.find(''); if idx == Some(2) && path[1] == ':' as u8 { let c = path[0]; if c.is_ascii() && ::char::is_alphabetic(c as char) { // ?C: path return Some(VerbatimDiskPrefix); } } let idx = idx.unwrap_or(path.len()); return Some(VerbatimPrefix(idx)); } } else if path.starts_with(".") { // .path path = path.slice_from(2); let idx = path.find('').unwrap_or(path.len()); return Some(DeviceNSPrefix(idx)); } match parse_two_comps(path, is_sep2) { Some((idx_a, idx_b)) if idx_a > 0 && idx_b > 0 => { // servershare return Some(UNCPrefix(idx_a, idx_b)); } _ => () } } else if path.len() > 1 && path[1] == ':' as u8 { // C: let c = path[0]; if c.is_ascii() && ::char::is_alphabetic(c as char) { return Some(DiskPrefix); } } return None; fn parse_two_comps<'a>(mut path: &'a str, f: &fn(char)->bool) -> Option<(uint, uint)> { let idx_a = match path.find(|x| f(x)) { None => return None, Some(x) => x }; path = path.slice_from(idx_a+1); let idx_b = path.find(f).unwrap_or(path.len()); Some((idx_a, idx_b)) } } // None result means the string didn't need normalizing fn normalize_helper<'a>(s: &'a str, prefix: Option<PathPrefix>) -> (bool,Option<~[&'a str]>) { let f = if !prefix_is_verbatim(prefix) { is_sep2 } else { is_sep }; let is_abs = s.len() > prefix_len(prefix) && f(s.char_at(prefix_len(prefix))); let s_ = s.slice_from(prefix_len(prefix)); let s_ = if is_abs { s_.slice_from(1) } else { s_ }; if is_abs && s_.is_empty() { return (is_abs, match prefix { Some(DiskPrefix) | None => (if is_sep(s.char_at(prefix_len(prefix))) { None } else { Some(~[]) }), Some(_) => Some(~[]), // need to trim the trailing separator }); } let mut comps: ~[&'a str] = ~[]; let mut n_up = 0u; let mut changed = false; for comp in s_.split_iter(f) { if comp.is_empty() { changed = true } else if comp == "." { changed = true } else if comp == ".." { let has_abs_prefix = match prefix { Some(DiskPrefix) => false, Some(_) => true, None => false }; if (is_abs || has_abs_prefix) && comps.is_empty() { changed = true } else if comps.len() == n_up { comps.push(".."); n_up += 1 } else { comps.pop_opt(); changed = true } } else { comps.push(comp) } } if !changed && !prefix_is_verbatim(prefix) { changed = s.find(is_sep2).is_some(); } if changed { if comps.is_empty() && !is_abs && prefix.is_none() { if s == "." { return (is_abs, None); } comps.push("."); } (is_abs, Some(comps)) } else { (is_abs, None) } } // FIXME (#8169): Pull this into parent module once visibility works #[inline(always)] fn contains_nul(v: &[u8]) -> bool { v.iter().any(|&x| x == 0) } fn prefix_is_verbatim(p: Option<PathPrefix>) -> bool { match p { Some(VerbatimPrefix(_)) | Some(VerbatimUNCPrefix(_,_)) | Some(VerbatimDiskPrefix) => true, Some(DeviceNSPrefix(_)) => true, // not really sure, but I think so _ => false } } fn prefix_len(p: Option<PathPrefix>) -> uint { match p { None => 0, Some(VerbatimPrefix(x)) => 4 + x, Some(VerbatimUNCPrefix(x,y)) => 8 + x + 1 + y, Some(VerbatimDiskPrefix) => 6, Some(UNCPrefix(x,y)) => 2 + x + 1 + y, Some(DeviceNSPrefix(x)) => 4 + x, Some(DiskPrefix) => 2 } } fn prefix_is_sep(p: Option<PathPrefix>, c: u8) -> bool { c.is_ascii() && if !prefix_is_verbatim(p) { is_sep2(c as char) } else { is_sep(c as char) } } #[cfg(test)] mod tests { use super::*; use option::{Some,None}; use iter::Iterator; use vec::Vector; macro_rules! t( (s: $path:expr, $exp:expr) => ( { let path = $path; assert_eq!(path.as_str(), Some($exp)); } ); (v: $path:expr, $exp:expr) => ( { let path = $path; assert_eq!(path.as_vec(), $exp); } ) ) macro_rules! b( ($($arg:expr),+) => ( bytes!($($arg),+) ) ) #[test] fn test_parse_prefix() { macro_rules! t( ($path:expr, $exp:expr) => ( { let path = $path; let exp = $exp; let res = parse_prefix(path); assert!(res == exp, "parse_prefix("%s"): expected %?, found %?", path, exp, res); } ) ) t!("SERVERsharefoo", Some(UNCPrefix(6,5))); t!("", None); t!("SERVER", None); t!("SERVER", None); t!("SERVER", None); t!("SERVERfoo", None); t!("SERVERshare", Some(UNCPrefix(6,5))); t!("SERVER/share/foo", Some(UNCPrefix(6,5))); t!("SERVERshare/foo", Some(UNCPrefix(6,5))); t!("//SERVER/share/foo", None); t!("abc", None); t!("?abc", Some(VerbatimPrefix(1))); t!("?a/b/c", Some(VerbatimPrefix(5))); t!("//?/a/b/c", None); t!(".ab", Some(DeviceNSPrefix(1))); t!(".a/b", Some(DeviceNSPrefix(3))); t!("//./a/b", None); t!("?UNCserversharefoo", Some(VerbatimUNCPrefix(6,5))); t!("?UNCsharefoo", Some(VerbatimUNCPrefix(0,5))); t!("?UNC", Some(VerbatimUNCPrefix(0,0))); t!("?UNCserver/share/foo", Some(VerbatimUNCPrefix(16,0))); t!("?UNCserver", Some(VerbatimUNCPrefix(6,0))); t!("?UNCserver", Some(VerbatimUNCPrefix(6,0))); t!("?UNC/server/share", Some(VerbatimPrefix(16))); t!("?UNC", Some(VerbatimPrefix(3))); t!("?C:ab.txt", Some(VerbatimDiskPrefix)); t!("?z:", Some(VerbatimDiskPrefix)); t!("?C:", Some(VerbatimPrefix(2))); t!("?C:a.txt", Some(VerbatimPrefix(7))); t!("?C:ab.txt", Some(VerbatimPrefix(3))); t!("?C:/a", Some(VerbatimPrefix(4))); t!("C:foo", Some(DiskPrefix)); t!("z:/foo", Some(DiskPrefix)); t!("d:", Some(DiskPrefix)); t!("ab:", None); t!("ü:foo", None); t!("3:foo", None); t!(" :foo", None); t!("::foo", None); t!("?C:", Some(VerbatimPrefix(2))); t!("?z:", Some(VerbatimDiskPrefix)); t!("?ab:", Some(VerbatimPrefix(3))); t!("?C:a", Some(VerbatimDiskPrefix)); t!("?C:/a", Some(VerbatimPrefix(4))); t!("?C:a/b", Some(VerbatimDiskPrefix)); } #[test] fn test_paths() { t!(v: Path::new([]), b!(".")); t!(v: Path::new(b!("")), b!("")); t!(v: Path::new(b!("abc")), b!("abc")); t!(s: Path::from_str(""), "."); t!(s: Path::from_str(""), ""); t!(s: Path::from_str("hi"), "hi"); t!(s: Path::from_str("hi"), "hi"); t!(s: Path::from_str("lib"), "lib"); t!(s: Path::from_str("lib"), "lib"); t!(s: Path::from_str("hithere"), "hithere"); t!(s: Path::from_str("hithere.txt"), "hithere.txt"); t!(s: Path::from_str("/"), ""); t!(s: Path::from_str("hi/"), "hi"); t!(s: Path::from_str("/lib"), "lib"); t!(s: Path::from_str("/lib/"), "lib"); t!(s: Path::from_str("hi/there"), "hithere"); t!(s: Path::from_str("hithere"), "hithere"); t!(s: Path::from_str("hi..there"), "there"); t!(s: Path::from_str("hi/../there"), "there"); t!(s: Path::from_str("..hithere"), "..hithere"); t!(s: Path::from_str("..hithere"), "hithere"); t!(s: Path::from_str("/../hi/there"), "hithere"); t!(s: Path::from_str("foo.."), "."); t!(s: Path::from_str("foo.."), ""); t!(s: Path::from_str("foo...."), ""); t!(s: Path::from_str("foo....bar"), "bar"); t!(s: Path::from_str(".hi.there."), "hithere"); t!(s: Path::from_str(".hi.there..."), "hi"); t!(s: Path::from_str("foo...."), ".."); t!(s: Path::from_str("foo......"), "...."); t!(s: Path::from_str("foo....bar"), "..bar"); assert_eq!(Path::new(b!("foobar")).into_vec(), b!("foobar").to_owned()); assert_eq!(Path::new(b!("foo....bar")).into_vec(), b!("bar").to_owned()); assert_eq!(Path::from_str("foobar").into_str(), Some(~"foobar")); assert_eq!(Path::from_str("foo....bar").into_str(), Some(~"bar")); t!(s: Path::from_str("a"), "a"); t!(s: Path::from_str("a"), "a"); t!(s: Path::from_str("ab"), "ab"); t!(s: Path::from_str("ab"), "ab"); t!(s: Path::from_str("ab/"), "ab"); t!(s: Path::from_str("b"), "b"); t!(s: Path::from_str("ab"), "ab"); t!(s: Path::from_str("abc"), "abc"); t!(s: Path::from_str("servershare/path"), "serversharepath"); t!(s: Path::from_str("server/share/path"), "serversharepath"); t!(s: Path::from_str("C:ab.txt"), "C:ab.txt"); t!(s: Path::from_str("C:a/b.txt"), "C:ab.txt"); t!(s: Path::from_str("z:ab.txt"), "Z:ab.txt"); t!(s: Path::from_str("z:/a/b.txt"), "Z:ab.txt"); t!(s: Path::from_str("ab:/a/b.txt"), "ab:ab.txt"); t!(s: Path::from_str("C:"), "C:"); t!(s: Path::from_str("C:"), "C:"); t!(s: Path::from_str("q:"), "Q:"); t!(s: Path::from_str("C:/"), "C:"); t!(s: Path::from_str("C:foo.."), "C:"); t!(s: Path::from_str("C:foo.."), "C:"); t!(s: Path::from_str("C:a"), "C:a"); t!(s: Path::from_str("C:a/"), "C:a"); t!(s: Path::from_str("C:ab"), "C:ab"); t!(s: Path::from_str("C:ab/"), "C:ab"); t!(s: Path::from_str("C:a"), "C:a"); t!(s: Path::from_str("C:a/"), "C:a"); t!(s: Path::from_str("C:ab"), "C:ab"); t!(s: Path::from_str("C:ab/"), "C:ab"); t!(s: Path::from_str("?z:ab.txt"), "?z:ab.txt"); t!(s: Path::from_str("?C:/a/b.txt"), "?C:/a/b.txt"); t!(s: Path::from_str("?C:a/b.txt"), "?C:a/b.txt"); t!(s: Path::from_str("?testab.txt"), "?testab.txt"); t!(s: Path::from_str("?foobar"), "?foobar"); t!(s: Path::from_str(".foobar"), ".foobar"); t!(s: Path::from_str("."), "."); t!(s: Path::from_str("?UNCserversharefoo"), "?UNCserversharefoo"); t!(s: Path::from_str("?UNCserver/share"), "?UNCserver/share"); t!(s: Path::from_str("?UNCserver"), "?UNCserver"); t!(s: Path::from_str("?UNC"), "?UNC"); t!(s: Path::from_str("?UNC"), "?UNC"); // I'm not sure whether .foo/bar should normalize to .foobar // as information is sparse and this isn't really googleable. // I'm going to err on the side of not normalizing it, as this skips the filesystem t!(s: Path::from_str(".foo/bar"), ".foo/bar"); t!(s: Path::from_str(".foobar"), ".foobar"); } #[test] fn test_null_byte() { use path2::null_byte::cond; let mut handled = false; let mut p = do cond.trap(|v| { handled = true; assert_eq!(v.as_slice(), b!("foobar", 0)); (b!("bar").to_owned()) }).inside { Path::new(b!("foobar", 0)) }; assert!(handled); assert_eq!(p.as_vec(), b!("bar")); handled = false; do cond.trap(|v| { handled = true; assert_eq!(v.as_slice(), b!("f", 0, "o")); (b!("foo").to_owned()) }).inside { p.set_filename(b!("f", 0, "o")) }; assert!(handled); assert_eq!(p.as_vec(), b!("foo")); handled = false; do cond.trap(|v| { handled = true; assert_eq!(v.as_slice(), b!("null", 0, "byte")); (b!("nullbyte").to_owned()) }).inside { p.set_dirname(b!("null", 0, "byte")); }; assert!(handled); assert_eq!(p.as_vec(), b!("nullbytefoo")); handled = false; do cond.trap(|v| { handled = true; assert_eq!(v.as_slice(), b!("f", 0, "o")); (b!("foo").to_owned()) }).inside { p.push(b!("f", 0, "o")); }; assert!(handled); assert_eq!(p.as_vec(), b!("nullbytefoofoo")); } #[test] fn test_null_byte_fail() { use path2::null_byte::cond; use task; macro_rules! t( ($name:expr => $code:block) => ( { let mut t = task::task(); t.supervised(); t.name($name); let res = do t.try $code; assert!(res.is_err()); } ) ) t!(~"new() wnul" => { do cond.trap(|_| { (b!("null", 0).to_owned()) }).inside { Path::new(b!("foobar", 0)) }; }) t!(~"set_filename wnul" => { let mut p = Path::new(b!("foobar")); do cond.trap(|_| { (b!("null", 0).to_owned()) }).inside { p.set_filename(b!("foo", 0)) }; }) t!(~"set_dirname wnul" => { let mut p = Path::new(b!("foobar")); do cond.trap(|_| { (b!("null", 0).to_owned()) }).inside { p.set_dirname(b!("foo", 0)) }; }) t!(~"push wnul" => { let mut p = Path::new(b!("foobar")); do cond.trap(|_| { (b!("null", 0).to_owned()) }).inside { p.push(b!("foo", 0)) }; }) } #[test] #[should_fail] fn test_not_utf8_fail() { Path::new(b!("hello", 0x80, ".txt")); } #[test] fn test_components() { macro_rules! t( (s: $path:expr, $op:ident, $exp:expr) => ( { let path = Path::from_str($path); assert_eq!(path.$op(), Some($exp)); } ); (s: $path:expr, $op:ident, $exp:expr, opt) => ( { let path = Path::from_str($path); let left = path.$op(); assert_eq!(left, $exp); } ); (v: $path:expr, $op:ident, $exp:expr) => ( { let path = Path::new($path); assert_eq!(path.$op(), $exp); } ) ) t!(v: b!("abc"), filename, b!("c")); t!(s: "abc", filename_str, "c"); t!(s: "abc", filename_str, "c"); t!(s: "a", filename_str, "a"); t!(s: "a", filename_str, "a"); t!(s: ".", filename_str, ""); t!(s: "", filename_str, ""); t!(s: "..", filename_str, ""); t!(s: "....", filename_str, ""); t!(s: "c:foo.txt", filename_str, "foo.txt"); t!(s: "C:", filename_str, ""); t!(s: "C:", filename_str, ""); t!(s: "serversharefoo.txt", filename_str, "foo.txt"); t!(s: "servershare", filename_str, ""); t!(s: "server", filename_str, "server"); t!(s: "?barfoo.txt", filename_str, "foo.txt"); t!(s: "?bar", filename_str, ""); t!(s: "?", filename_str, ""); t!(s: "?UNCserversharefoo.txt", filename_str, "foo.txt"); t!(s: "?UNCserver", filename_str, ""); t!(s: "?UNC", filename_str, ""); t!(s: "?C:foo.txt", filename_str, "foo.txt"); t!(s: "?C:", filename_str, ""); t!(s: "?C:", filename_str, ""); t!(s: "?foo/bar", filename_str, ""); t!(s: "?C:/foo", filename_str, ""); t!(s: ".foobar", filename_str, "bar"); t!(s: ".foo", filename_str, ""); t!(s: ".foo/bar", filename_str, ""); t!(s: ".foobar/baz", filename_str, "bar/baz"); t!(s: ".", filename_str, ""); t!(s: "?ab", filename_str, "b"); t!(v: b!("abc"), dirname, b!("ab")); t!(s: "abc", dirname_str, "ab"); t!(s: "abc", dirname_str, "ab"); t!(s: "a", dirname_str, "."); t!(s: "a", dirname_str, ""); t!(s: ".", dirname_str, "."); t!(s: "", dirname_str, ""); t!(s: "..", dirname_str, ".."); t!(s: "....", dirname_str, "...."); t!(s: "c:foo.txt", dirname_str, "C:"); t!(s: "C:", dirname_str, "C:"); t!(s: "C:", dirname_str, "C:"); t!(s: "C:foo.txt", dirname_str, "C:"); t!(s: "serversharefoo.txt", dirname_str, "servershare"); t!(s: "servershare", dirname_str, "servershare"); t!(s: "server", dirname_str, ""); t!(s: "?barfoo.txt", dirname_str, "?bar"); t!(s: "?bar", dirname_str, "?bar"); t!(s: "?", dirname_str, "?"); t!(s: "?UNCserversharefoo.txt", dirname_str, "?UNCservershare"); t!(s: "?UNCserver", dirname_str, "?UNCserver"); t!(s: "?UNC", dirname_str, "?UNC"); t!(s: "?C:foo.txt", dirname_str, "?C:"); t!(s: "?C:", dirname_str, "?C:"); t!(s: "?C:", dirname_str, "?C:"); t!(s: "?C:/foo/bar", dirname_str, "?C:/foo/bar"); t!(s: "?foo/bar", dirname_str, "?foo/bar"); t!(s: ".foobar", dirname_str, ".foo"); t!(s: ".foo", dirname_str, ".foo"); t!(s: "?ab", dirname_str, "?a"); t!(v: b!("hithere.txt"), filestem, b!("there")); t!(s: "hithere.txt", filestem_str, "there"); t!(s: "hithere", filestem_str, "there"); t!(s: "there.txt", filestem_str, "there"); t!(s: "there", filestem_str, "there"); t!(s: ".", filestem_str, ""); t!(s: "", filestem_str, ""); t!(s: "foo.bar", filestem_str, ".bar"); t!(s: ".bar", filestem_str, ".bar"); t!(s: "..bar", filestem_str, "."); t!(s: "hithere..txt", filestem_str, "there."); t!(s: "..", filestem_str, ""); t!(s: "....", filestem_str, ""); // filestem is based on filename, so we don't need the full set of prefix tests t!(v: b!("hithere.txt"), extension, Some(b!("txt"))); t!(v: b!("hithere"), extension, None); t!(s: "hithere.txt", extension_str, Some("txt"), opt); t!(s: "hithere", extension_str, None, opt); t!(s: "there.txt", extension_str, Some("txt"), opt); t!(s: "there", extension_str, None, opt); t!(s: ".", extension_str, None, opt); t!(s: "", extension_str, None, opt); t!(s: "foo.bar", extension_str, None, opt); t!(s: ".bar", extension_str, None, opt); t!(s: "..bar", extension_str, Some("bar"), opt); t!(s: "hithere..txt", extension_str, Some("txt"), opt); t!(s: "..", extension_str, None, opt); t!(s: "....", extension_str, None, opt); // extension is based on filename, so we don't need the full set of prefix tests } #[test] fn test_push() { macro_rules! t( (s: $path:expr, $join:expr) => ( { let path = ($path); let join = ($join); let mut p1 = Path::from_str(path); let p2 = p1.clone(); p1.push_str(join); assert_eq!(p1, p2.join_str(join)); } ) ) t!(s: "abc", ".."); t!(s: "abc", "d"); t!(s: "ab", "cd"); t!(s: "ab", "cd"); // this is just a sanity-check test. push_str and join_str share an implementation, // so there's no need for the full set of prefix tests // we do want to check one odd case though to ensure the prefix is re-parsed let mut p = Path::from_str("?C:"); assert_eq!(p.prefix(), Some(VerbatimPrefix(2))); p.push_str("foo"); assert_eq!(p.prefix(), Some(VerbatimDiskPrefix)); assert_eq!(p.as_str(), Some("?C:foo")); // and another with verbatim non-normalized paths let mut p = Path::from_str("?C:a"); p.push_str("foo"); assert_eq!(p.as_str(), Some("?C:afoo")); } #[test] fn test_push_path() { macro_rules! t( (s: $path:expr, $push:expr, $exp:expr) => ( { let mut p = Path::from_str($path); let push = Path::from_str($push); p.push_path(&push); assert_eq!(p.as_str(), Some($exp)); } ) ) t!(s: "abc", "d", "abcd"); t!(s: "abc", "d", "abcd"); t!(s: "ab", "cd", "abcd"); t!(s: "ab", "cd", "cd"); t!(s: "ab", ".", "ab"); t!(s: "ab", "..c", "ac"); t!(s: "ab", "C:a.txt", "C:a.txt"); t!(s: "ab", "......c", "..c"); t!(s: "ab", "C:a.txt", "C:a.txt"); t!(s: "C:a", "C:b.txt", "C:b.txt"); t!(s: "C:abc", "C:d", "C:abcd"); t!(s: "C:abc", "C:d", "C:abcd"); t!(s: "C:ab", "......c", "C:..c"); t!(s: "C:ab", "......c", "C:c"); t!(s: "serversharefoo", "bar", "serversharefoobar"); t!(s: "serversharefoo", "....bar", "serversharebar"); t!(s: "serversharefoo", "C:baz", "C:baz"); t!(s: "?C:ab", "C:cd", "?C:abcd"); t!(s: "?C:ab", "C:cd", "C:cd"); t!(s: "?C:ab", "C:cd", "C:cd"); t!(s: "?foobar", "baz", "?foobarbaz"); t!(s: "?C:ab", "......c", "?C:ab......c"); t!(s: "?foobar", "....c", "?foobar....c"); t!(s: "?", "foo", "?foo"); t!(s: "?UNCserversharefoo", "bar", "?UNCserversharefoobar"); t!(s: "?UNCservershare", "C:a", "C:a"); t!(s: "?UNCservershare", "C:a", "C:a"); t!(s: "?UNCserver", "foo", "?UNCserverfoo"); t!(s: "C:a", "?UNCservershare", "?UNCservershare"); t!(s: ".foobar", "baz", ".foobarbaz"); t!(s: ".foobar", "C:a", "C:a"); // again, not sure about the following, but I'm assuming . should be verbatim t!(s: ".foo", "..bar", ".foo..bar"); t!(s: "?C:", "foo", "?C:foo"); // this is a weird one } #[test] fn test_pop() { macro_rules! t( (s: $path:expr, $left:expr, $right:expr) => ( { let pstr = $path; let mut p = Path::from_str(pstr); let file = p.pop_opt_str(); let left = $left; assert!(p.as_str() == Some(left), "`%s`.pop() failed; expected remainder `%s`, found `%s`", pstr, left, p.as_str().unwrap()); let right = $right; let res = file.map(|s| s.as_slice()); assert!(res == right, "`%s`.pop() failed; expected `%?`, found `%?`", pstr, right, res); } ); (v: [$($path:expr),+], [$($left:expr),+], Some($($right:expr),+)) => ( { let mut p = Path::new(b!($($path),+)); let file = p.pop_opt(); assert_eq!(p.as_vec(), b!($($left),+)); assert_eq!(file.map(|v| v.as_slice()), Some(b!($($right),+))); } ); (v: [$($path:expr),+], [$($left:expr),+], None) => ( { let mut p = Path::new(b!($($path),+)); let file = p.pop_opt(); assert_eq!(p.as_vec(), b!($($left),+)); assert_eq!(file, None); } ) ) t!(s: "abc", "ab", Some("c")); t!(s: "a", ".", Some("a")); t!(s: ".", ".", None); t!(s: "a", "", Some("a")); t!(s: "", "", None); t!(v: ["abc"], ["ab"], Some("c")); t!(v: ["a"], ["."], Some("a")); t!(v: ["."], ["."], None); t!(v: ["a"], [""], Some("a")); t!(v: [""], [""], None); t!(s: "C:ab", "C:a", Some("b")); t!(s: "C:a", "C:", Some("a")); t!(s: "C:", "C:", None); t!(s: "C:ab", "C:a", Some("b")); t!(s: "C:a", "C:", Some("a")); t!(s: "C:", "C:", None); t!(s: "servershareab", "serversharea", Some("b")); t!(s: "serversharea", "servershare", Some("a")); t!(s: "servershare", "servershare", None); t!(s: "?abc", "?ab", Some("c")); t!(s: "?ab", "?a", Some("b")); t!(s: "?a", "?a", None); t!(s: "?C:ab", "?C:a", Some("b")); t!(s: "?C:a", "?C:", Some("a")); t!(s: "?C:", "?C:", None); t!(s: "?UNCservershareab", "?UNCserversharea", Some("b")); t!(s: "?UNCserversharea", "?UNCservershare", Some("a")); t!(s: "?UNCservershare", "?UNCservershare", None); t!(s: ".abc", ".ab", Some("c")); t!(s: ".ab", ".a", Some("b")); t!(s: ".a", ".a", None); t!(s: "?ab", "?a", Some("b")); } #[test] fn test_join() { t!(s: Path::from_str("abc").join_str(".."), "ab"); t!(s: Path::from_str("abc").join_str("d"), "abcd"); t!(s: Path::from_str("ab").join_str("cd"), "abcd"); t!(s: Path::from_str("ab").join_str("cd"), "cd"); t!(s: Path::from_str(".").join_str("ab"), "ab"); t!(s: Path::from_str("").join_str("ab"), "ab"); t!(v: Path::new(b!("abc")).join(b!("..")), b!("ab")); t!(v: Path::new(b!("abc")).join(b!("d")), b!("abcd")); // full join testing is covered under test_push_path, so no need for // the full set of prefix tests } #[test] fn test_join_path() { macro_rules! t( (s: $path:expr, $join:expr, $exp:expr) => ( { let path = Path::from_str($path); let join = Path::from_str($join); let res = path.join_path(&join); assert_eq!(res.as_str(), Some($exp)); } ) ) t!(s: "abc", "..", "ab"); t!(s: "abc", "d", "abcd"); t!(s: "ab", "cd", "abcd"); t!(s: "ab", "cd", "cd"); t!(s: ".", "ab", "ab"); t!(s: "", "ab", "ab"); // join_path is implemented using push_path, so there's no need for // the full set of prefix tests } #[test] fn test_with_helpers() { macro_rules! t( (s: $path:expr, $op:ident, $arg:expr, $res:expr) => ( { let pstr = $path; let path = Path::from_str(pstr); let arg = $arg; let res = path.$op(arg); let exp = $res; assert!(res.as_str() == Some(exp), "`%s`.%s("%s"): Expected `%s`, found `%s`", pstr, stringify!($op), arg, exp, res.as_str().unwrap()); } ) ) t!(s: "abc", with_dirname_str, "d", "dc"); t!(s: "abc", with_dirname_str, "de", "dec"); t!(s: "abc", with_dirname_str, "", "c"); t!(s: "abc", with_dirname_str, "", "c"); t!(s: "abc", with_dirname_str, "/", "c"); t!(s: "abc", with_dirname_str, ".", "c"); t!(s: "abc", with_dirname_str, "..", "..c"); t!(s: "", with_dirname_str, "foo", "foo"); t!(s: "", with_dirname_str, "", "."); t!(s: "foo", with_dirname_str, "bar", "barfoo"); t!(s: "..", with_dirname_str, "foo", "foo"); t!(s: "....", with_dirname_str, "foo", "foo"); t!(s: "..", with_dirname_str, "", "."); t!(s: "....", with_dirname_str, "", "."); t!(s: ".", with_dirname_str, "foo", "foo"); t!(s: "foo", with_dirname_str, "..", "..foo"); t!(s: "foo", with_dirname_str, "....", "....foo"); t!(s: "C:ab", with_dirname_str, "foo", "foob"); t!(s: "foo", with_dirname_str, "C:ab", "C:abfoo"); t!(s: "C:ab", with_dirname_str, "servershare", "servershareb"); t!(s: "a", with_dirname_str, "servershare", "serversharea"); t!(s: "ab", with_dirname_str, "?", "?b"); t!(s: "ab", with_dirname_str, "C:", "C:b"); t!(s: "ab", with_dirname_str, "C:", "C:b"); t!(s: "ab", with_dirname_str, "C:/", "C:b"); t!(s: "C:", with_dirname_str, "foo", "foo"); t!(s: "C:", with_dirname_str, "foo", "foo"); t!(s: ".", with_dirname_str, "C:", "C:"); t!(s: ".", with_dirname_str, "C:/", "C:"); t!(s: "?C:foo", with_dirname_str, "C:", "C:foo"); t!(s: "?C:", with_dirname_str, "bar", "bar"); t!(s: "foobar", with_dirname_str, "?C:baz", "?C:bazbar"); t!(s: "?foo", with_dirname_str, "C:bar", "C:bar"); t!(s: "?afoo", with_dirname_str, "C:bar", "C:barfoo"); t!(s: "?afoo/bar", with_dirname_str, "C:baz", "C:bazfoobar"); t!(s: "?UNCserversharebaz", with_dirname_str, "a", "abaz"); t!(s: "foobar", with_dirname_str, "?UNCserversharebaz", "?UNCserversharebazbar"); t!(s: ".foo", with_dirname_str, "bar", "bar"); t!(s: ".foobar", with_dirname_str, "baz", "bazbar"); t!(s: ".foobar", with_dirname_str, "baz", "bazbar"); t!(s: ".foobar", with_dirname_str, "baz/", "bazbar"); t!(s: "abc", with_filename_str, "d", "abd"); t!(s: ".", with_filename_str, "foo", "foo"); t!(s: "abc", with_filename_str, "d", "abd"); t!(s: "", with_filename_str, "foo", "foo"); t!(s: "a", with_filename_str, "foo", "foo"); t!(s: "foo", with_filename_str, "bar", "bar"); t!(s: "", with_filename_str, "foo", "foo"); t!(s: "a", with_filename_str, "foo", "foo"); t!(s: "abc", with_filename_str, "", "ab"); t!(s: "abc", with_filename_str, ".", "ab"); t!(s: "abc", with_filename_str, "..", "a"); t!(s: "a", with_filename_str, "", ""); t!(s: "foo", with_filename_str, "", "."); t!(s: "abc", with_filename_str, "de", "abde"); t!(s: "abc", with_filename_str, "d", "abd"); t!(s: "..", with_filename_str, "foo", "..foo"); t!(s: "....", with_filename_str, "foo", "....foo"); t!(s: "..", with_filename_str, "", ".."); t!(s: "....", with_filename_str, "", "...."); t!(s: "C:foobar", with_filename_str, "baz", "C:foobaz"); t!(s: "C:foo", with_filename_str, "bar", "C:bar"); t!(s: "C:", with_filename_str, "foo", "C:foo"); t!(s: "C:foobar", with_filename_str, "baz", "C:foobaz"); t!(s: "C:foo", with_filename_str, "bar", "C:bar"); t!(s: "C:", with_filename_str, "foo", "C:foo"); t!(s: "C:foo", with_filename_str, "", "C:"); t!(s: "C:foo", with_filename_str, "", "C:"); t!(s: "C:foobar", with_filename_str, "..", "C:"); t!(s: "C:foo", with_filename_str, "..", "C:"); t!(s: "C:", with_filename_str, "..", "C:"); t!(s: "C:foobar", with_filename_str, "..", "C:"); t!(s: "C:foo", with_filename_str, "..", "C:.."); t!(s: "C:", with_filename_str, "..", "C:.."); t!(s: "serversharefoo", with_filename_str, "bar", "serversharebar"); t!(s: "servershare", with_filename_str, "foo", "serversharefoo"); t!(s: "serversharefoo", with_filename_str, "", "servershare"); t!(s: "servershare", with_filename_str, "", "servershare"); t!(s: "serversharefoo", with_filename_str, "..", "servershare"); t!(s: "servershare", with_filename_str, "..", "servershare"); t!(s: "?C:foobar", with_filename_str, "baz", "?C:foobaz"); t!(s: "?C:foo", with_filename_str, "bar", "?C:bar"); t!(s: "?C:", with_filename_str, "foo", "?C:foo"); t!(s: "?C:foo", with_filename_str, "..", "?C:.."); t!(s: "?foobar", with_filename_str, "baz", "?foobaz"); t!(s: "?foo", with_filename_str, "bar", "?foobar"); t!(s: "?", with_filename_str, "foo", "?foo"); t!(s: "?foobar", with_filename_str, "..", "?foo.."); t!(s: ".foobar", with_filename_str, "baz", ".foobaz"); t!(s: ".foo", with_filename_str, "bar", ".foobar"); t!(s: ".foobar", with_filename_str, "..", ".foo.."); t!(s: "hithere.txt", with_filestem_str, "here", "hihere.txt"); t!(s: "hithere.txt", with_filestem_str, "", "hi.txt"); t!(s: "hithere.txt", with_filestem_str, ".", "hi..txt"); t!(s: "hithere.txt", with_filestem_str, "..", "hi...txt"); t!(s: "hithere.txt", with_filestem_str, "", "hi.txt"); t!(s: "hithere.txt", with_filestem_str, "foobar", "hifoobar.txt"); t!(s: "hithere.foo.txt", with_filestem_str, "here", "hihere.txt"); t!(s: "hithere", with_filestem_str, "here", "hihere"); t!(s: "hithere", with_filestem_str, "", "hi"); t!(s: "hi", with_filestem_str, "", "."); t!(s: "hi", with_filestem_str, "", ""); t!(s: "hithere", with_filestem_str, "..", "."); t!(s: "hithere", with_filestem_str, ".", "hi"); t!(s: "hithere.", with_filestem_str, "foo", "hifoo."); t!(s: "hithere.", with_filestem_str, "", "hi"); t!(s: "hithere.", with_filestem_str, ".", "."); t!(s: "hithere.", with_filestem_str, "..", "hi..."); t!(s: "", with_filestem_str, "foo", "foo"); t!(s: ".", with_filestem_str, "foo", "foo"); t!(s: "hithere..", with_filestem_str, "here", "hihere."); t!(s: "hithere..", with_filestem_str, "", "hi"); // filestem setter calls filename setter internally, no need for extended tests t!(s: "hithere.txt", with_extension_str, "exe", "hithere.exe"); t!(s: "hithere.txt", with_extension_str, "", "hithere"); t!(s: "hithere.txt", with_extension_str, ".", "hithere.."); t!(s: "hithere.txt", with_extension_str, "..", "hithere..."); t!(s: "hithere", with_extension_str, "txt", "hithere.txt"); t!(s: "hithere", with_extension_str, ".", "hithere.."); t!(s: "hithere", with_extension_str, "..", "hithere..."); t!(s: "hithere.", with_extension_str, "txt", "hithere.txt"); t!(s: "hi.foo", with_extension_str, "txt", "hi.foo.txt"); t!(s: "hithere.txt", with_extension_str, ".foo", "hithere..foo"); t!(s: "", with_extension_str, "txt", ""); t!(s: "", with_extension_str, ".", ""); t!(s: "", with_extension_str, "..", ""); t!(s: ".", with_extension_str, "txt", "."); // extension setter calls filename setter internally, no need for extended tests } #[test] fn test_setters() { macro_rules! t( (s: $path:expr, $set:ident, $with:ident, $arg:expr) => ( { let path = $path; let arg = $arg; let mut p1 = Path::from_str(path); p1.$set(arg); let p2 = Path::from_str(path); assert_eq!(p1, p2.$with(arg)); } ); (v: $path:expr, $set:ident, $with:ident, $arg:expr) => ( { let path = $path; let arg = $arg; let mut p1 = Path::new(path); p1.$set(arg); let p2 = Path::new(path); assert_eq!(p1, p2.$with(arg)); } ) ) t!(v: b!("abc"), set_dirname, with_dirname, b!("d")); t!(v: b!("abc"), set_dirname, with_dirname, b!("de")); t!(s: "abc", set_dirname_str, with_dirname_str, "d"); t!(s: "abc", set_dirname_str, with_dirname_str, "de"); t!(s: "", set_dirname_str, with_dirname_str, "foo"); t!(s: "foo", set_dirname_str, with_dirname_str, "bar"); t!(s: "abc", set_dirname_str, with_dirname_str, ""); t!(s: "....", set_dirname_str, with_dirname_str, "x"); t!(s: "foo", set_dirname_str, with_dirname_str, "...."); t!(v: b!("abc"), set_filename, with_filename, b!("d")); t!(v: b!(""), set_filename, with_filename, b!("foo")); t!(s: "abc", set_filename_str, with_filename_str, "d"); t!(s: "", set_filename_str, with_filename_str, "foo"); t!(s: ".", set_filename_str, with_filename_str, "foo"); t!(s: "ab", set_filename_str, with_filename_str, ""); t!(s: "a", set_filename_str, with_filename_str, ""); t!(v: b!("hithere.txt"), set_filestem, with_filestem, b!("here")); t!(s: "hithere.txt", set_filestem_str, with_filestem_str, "here"); t!(s: "hithere.", set_filestem_str, with_filestem_str, "here"); t!(s: "hithere", set_filestem_str, with_filestem_str, "here"); t!(s: "hithere.txt", set_filestem_str, with_filestem_str, ""); t!(s: "hithere", set_filestem_str, with_filestem_str, ""); t!(v: b!("hithere.txt"), set_extension, with_extension, b!("exe")); t!(s: "hithere.txt", set_extension_str, with_extension_str, "exe"); t!(s: "hithere.", set_extension_str, with_extension_str, "txt"); t!(s: "hithere", set_extension_str, with_extension_str, "txt"); t!(s: "hithere.txt", set_extension_str, with_extension_str, ""); t!(s: "hithere", set_extension_str, with_extension_str, ""); t!(s: ".", set_extension_str, with_extension_str, "txt"); // with_ helpers use the setter internally, so the tests for the with_ helpers // will suffice. No need for the full set of prefix tests. } #[test] fn test_getters() { macro_rules! t( (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { let path = $path; assert_eq!(path.filename_str(), $filename); assert_eq!(path.dirname_str(), $dirname); assert_eq!(path.filestem_str(), $filestem); assert_eq!(path.extension_str(), $ext); } ); (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { let path = $path; assert_eq!(path.filename(), $filename); assert_eq!(path.dirname(), $dirname); assert_eq!(path.filestem(), $filestem); assert_eq!(path.extension(), $ext); } ) ) t!(v: Path::new(b!("abc")), b!("c"), b!("ab"), b!("c"), None); t!(s: Path::from_str("abc"), Some("c"), Some("ab"), Some("c"), None); t!(s: Path::from_str("."), Some(""), Some("."), Some(""), None); t!(s: Path::from_str(""), Some(""), Some(""), Some(""), None); t!(s: Path::from_str(".."), Some(""), Some(".."), Some(""), None); t!(s: Path::from_str("...."), Some(""), Some("...."), Some(""), None); t!(s: Path::from_str("hithere.txt"), Some("there.txt"), Some("hi"), Some("there"), Some("txt")); t!(s: Path::from_str("hithere"), Some("there"), Some("hi"), Some("there"), None); t!(s: Path::from_str("hithere."), Some("there."), Some("hi"), Some("there"), Some("")); t!(s: Path::from_str("hi.there"), Some(".there"), Some("hi"), Some(".there"), None); t!(s: Path::from_str("hi..there"), Some("..there"), Some("hi"), Some("."), Some("there")); // these are already tested in test_components, so no need for extended tests } #[test] fn test_dir_file_path() { t!(s: Path::from_str("hithere").dir_path(), "hi"); t!(s: Path::from_str("hi").dir_path(), "."); t!(s: Path::from_str("hi").dir_path(), ""); t!(s: Path::from_str("").dir_path(), ""); t!(s: Path::from_str("..").dir_path(), ".."); t!(s: Path::from_str("....").dir_path(), "...."); macro_rules! t( ($path:expr, $exp:expr) => ( { let path = $path; let left = path.and_then_ref(|p| p.as_str()); assert_eq!(left, $exp); } ); ) t!(Path::from_str("hithere").file_path(), Some("there")); t!(Path::from_str("hi").file_path(), Some("hi")); t!(Path::from_str(".").file_path(), None); t!(Path::from_str("").file_path(), None); t!(Path::from_str("..").file_path(), None); t!(Path::from_str("....").file_path(), None); // dir_path and file_path are just dirname and filename interpreted as paths. // No need for extended tests } #[test] fn test_is_absolute() { macro_rules! t( ($path:expr, $abs:expr, $vol:expr, $cwd:expr) => ( { let path = Path::from_str($path); let (abs, vol, cwd) = ($abs, $vol, $cwd); let b = path.is_absolute(); assert!(b == abs, "Path '%s'.is_absolute(): expected %?, found %?", path.as_str().unwrap(), abs, b); let b = path.is_vol_relative(); assert!(b == vol, "Path '%s'.is_vol_relative(): expected %?, found %?", path.as_str().unwrap(), vol, b); let b = path.is_cwd_relative(); assert!(b == cwd, "Path '%s'.is_cwd_relative(): expected %?, found %?", path.as_str().unwrap(), cwd, b); } ) ) t!("abc", false, false, false); t!("abc", false, true, false); t!("a", false, false, false); t!("a", false, true, false); t!(".", false, false, false); t!("", false, true, false); t!("..", false, false, false); t!("....", false, false, false); t!("C:ab.txt", false, false, true); t!("C:ab.txt", true, false, false); t!("servershareab.txt", true, false, false); t!("?abc.txt", true, false, false); t!("?C:ab.txt", true, false, false); t!("?C:ab.txt", true, false, false); // NB: not equivalent to C:ab.txt t!("?UNCservershareab.txt", true, false, false); t!(".ab", true, false, false); } #[test] fn test_is_ancestor_of() { macro_rules! t( (s: $path:expr, $dest:expr, $exp:expr) => ( { let path = Path::from_str($path); let dest = Path::from_str($dest); let exp = $exp; let res = path.is_ancestor_of(&dest); assert!(res == exp, "`%s`.is_ancestor_of(`%s`): Expected %?, found %?", path.as_str().unwrap(), dest.as_str().unwrap(), exp, res); } ) ) t!(s: "abc", "abcd", true); t!(s: "abc", "abc", true); t!(s: "abc", "ab", false); t!(s: "abc", "abc", true); t!(s: "ab", "abc", true); t!(s: "abcd", "abc", false); t!(s: "ab", "abc", false); t!(s: "ab", "abc", false); t!(s: "abc", "abd", false); t!(s: "..abc", "abc", false); t!(s: "abc", "..abc", false); t!(s: "abc", "abcd", false); t!(s: "abcd", "abc", false); t!(s: "..ab", "..abc", true); t!(s: ".", "ab", true); t!(s: ".", ".", true); t!(s: "", "", true); t!(s: "", "ab", true); t!(s: "..", "ab", true); t!(s: "....", "ab", true); t!(s: "foobar", "foobar", false); t!(s: "foobar", "foobar", false); t!(s: "foo", "C:foo", false); t!(s: "C:foo", "foo", false); t!(s: "C:foo", "C:foobar", true); t!(s: "C:foobar", "C:foo", false); t!(s: "C:foo", "C:foobar", true); t!(s: "C:", "C:", true); t!(s: "C:", "C:", false); t!(s: "C:", "C:", false); t!(s: "C:", "C:", true); t!(s: "C:foobar", "C:foo", false); t!(s: "C:foobar", "C:foo", false); t!(s: "C:foo", "foo", false); t!(s: "foo", "C:foo", false); t!(s: "serversharefoo", "serversharefoobar", true); t!(s: "servershare", "serversharefoo", true); t!(s: "serversharefoo", "servershare", false); t!(s: "C:foo", "serversharefoo", false); t!(s: "serversharefoo", "C:foo", false); t!(s: "?foobar", "?foobarbaz", true); t!(s: "?foobarbaz", "?foobar", false); t!(s: "?foobar", "foobarbaz", false); t!(s: "foobar", "?foobarbaz", false); t!(s: "?C:foobar", "?C:foobarbaz", true); t!(s: "?C:foobarbaz", "?C:foobar", false); t!(s: "?C:", "?C:foo", true); t!(s: "?C:", "?C:", false); // this is a weird one t!(s: "?C:", "?C:", false); t!(s: "?C:a", "?c:ab", true); t!(s: "?c:a", "?C:ab", true); t!(s: "?C:a", "?D:ab", false); t!(s: "?foo", "?foobar", false); t!(s: "?ab", "?abc", true); t!(s: "?ab", "?ab", true); t!(s: "?ab", "?ab", true); t!(s: "?abc", "?ab", false); t!(s: "?abc", "?ab", false); t!(s: "?UNCabc", "?UNCabcd", true); t!(s: "?UNCabcd", "?UNCabc", false); t!(s: "?UNCab", "?UNCabc", true); t!(s: ".foobar", ".foobarbaz", true); t!(s: ".foobarbaz", ".foobar", false); t!(s: ".foo", ".foobar", true); t!(s: ".foo", ".foobar", false); t!(s: "ab", "?ab", false); t!(s: "?ab", "ab", false); t!(s: "ab", "?C:ab", false); t!(s: "?C:ab", "ab", false); t!(s: "Z:ab", "?z:ab", true); t!(s: "C:ab", "?D:ab", false); t!(s: "ab", "?ab", false); t!(s: "?ab", "ab", false); t!(s: "C:ab", "?C:ab", true); t!(s: "?C:ab", "C:ab", true); t!(s: "C:ab", "?C:ab", false); t!(s: "C:ab", "?C:ab", false); t!(s: "?C:ab", "C:ab", false); t!(s: "?C:ab", "C:ab", false); t!(s: "C:ab", "?C:ab", true); t!(s: "?C:ab", "C:ab", true); t!(s: "abc", "?UNCabc", true); t!(s: "?UNCabc", "abc", true); } #[test] fn test_path_relative_from() { macro_rules! t( (s: $path:expr, $other:expr, $exp:expr) => ( { let path = Path::from_str($path); let other = Path::from_str($other); let res = path.path_relative_from(&other); let exp = $exp; assert!(res.and_then_ref(|x| x.as_str()) == exp, "`%s`.path_relative_from(`%s`): Expected %?, got %?", path.as_str().unwrap(), other.as_str().unwrap(), exp, res.and_then_ref(|x| x.as_str())); } ) ) t!(s: "abc", "ab", Some("c")); t!(s: "abc", "abd", Some("..c")); t!(s: "abc", "abcd", Some("..")); t!(s: "abc", "abc", Some(".")); t!(s: "abc", "abcde", Some("....")); t!(s: "abc", "ade", Some("....bc")); t!(s: "abc", "def", Some("......abc")); t!(s: "abc", "abc", None); t!(s: "abc", "abc", Some("abc")); t!(s: "abc", "abcd", Some("..")); t!(s: "abc", "ab", Some("c")); t!(s: "abc", "abcde", Some("....")); t!(s: "abc", "ade", Some("....bc")); t!(s: "abc", "def", Some("......abc")); t!(s: "hithere.txt", "hithere", Some("..there.txt")); t!(s: ".", "a", Some("..")); t!(s: ".", "ab", Some("....")); t!(s: ".", ".", Some(".")); t!(s: "a", ".", Some("a")); t!(s: "ab", ".", Some("ab")); t!(s: "..", ".", Some("..")); t!(s: "abc", "abc", Some(".")); t!(s: "abc", "abc", Some(".")); t!(s: "", "", Some(".")); t!(s: "", ".", Some("")); t!(s: "....a", "b", Some("......a")); t!(s: "a", "....b", None); t!(s: "....a", "....b", Some("..a")); t!(s: "....a", "....ab", Some("..")); t!(s: "....ab", "....a", Some("b")); t!(s: "C:abc", "C:ab", Some("c")); t!(s: "C:ab", "C:abc", Some("..")); t!(s: "C:" ,"C:ab", Some("....")); t!(s: "C:ab", "C:cd", Some("....ab")); t!(s: "C:ab", "D:cd", Some("C:ab")); t!(s: "C:ab", "C:..c", None); t!(s: "C:..a", "C:bc", Some("......a")); t!(s: "C:abc", "C:ab", Some("c")); t!(s: "C:ab", "C:abc", Some("..")); t!(s: "C:", "C:ab", Some("....")); t!(s: "C:ab", "C:cd", Some("....ab")); t!(s: "C:ab", "C:ab", Some("C:ab")); t!(s: "C:ab", "C:ab", None); t!(s: "ab", "C:ab", None); t!(s: "ab", "C:ab", None); t!(s: "ab", "C:ab", None); t!(s: "ab", "C:ab", None); t!(s: "abc", "ab", Some("c")); t!(s: "ab", "abc", Some("..")); t!(s: "abce", "abcd", Some("..e")); t!(s: "acd", "abd", Some("acd")); t!(s: "bcd", "acd", Some("bcd")); t!(s: "abc", "de", Some("abc")); t!(s: "de", "abc", None); t!(s: "de", "abc", None); t!(s: "C:abc", "abc", Some("C:abc")); t!(s: "C:c", "abc", Some("C:c")); t!(s: "?ab", "ab", Some("?ab")); t!(s: "?ab", "ab", Some("?ab")); t!(s: "?ab", "b", Some("?ab")); t!(s: "?ab", "b", Some("?ab")); t!(s: "?ab", "?abc", Some("..")); t!(s: "?abc", "?ab", Some("c")); t!(s: "?ab", "?cd", Some("?ab")); t!(s: "?a", "?b", Some("?a")); t!(s: "?C:ab", "?C:a", Some("b")); t!(s: "?C:a", "?C:ab", Some("..")); t!(s: "?C:a", "?C:b", Some("..a")); t!(s: "?C:a", "?D:a", Some("?C:a")); t!(s: "?C:ab", "?c:a", Some("b")); t!(s: "?C:ab", "C:a", Some("b")); t!(s: "?C:a", "C:ab", Some("..")); t!(s: "C:ab", "?C:a", Some("b")); t!(s: "C:a", "?C:ab", Some("..")); t!(s: "?C:a", "D:a", Some("?C:a")); t!(s: "?c:ab", "C:a", Some("b")); t!(s: "?C:ab", "C:ab", Some("?C:ab")); t!(s: "?C:a.b", "C:a", Some("?C:a.b")); t!(s: "?C:ab/c", "C:a", Some("?C:ab/c")); t!(s: "?C:a..b", "C:a", Some("?C:a..b")); t!(s: "C:ab", "?C:ab", None); t!(s: "?C:a.b", "?C:a", Some("?C:a.b")); t!(s: "?C:ab/c", "?C:a", Some("?C:ab/c")); t!(s: "?C:a..b", "?C:a", Some("?C:a..b")); t!(s: "?C:ab", "?C:a", Some("b")); t!(s: "?C:.b", "?C:.", Some("b")); t!(s: "C:b", "?C:.", Some("..b")); t!(s: "?a.bc", "?a.b", Some("c")); t!(s: "?abc", "?a.d", Some("....bc")); t!(s: "?a..b", "?a..", Some("b")); t!(s: "?ab..", "?ab", Some("?ab..")); t!(s: "?abc", "?a..b", Some("....bc")); t!(s: "?UNCabc", "?UNCab", Some("c")); t!(s: "?UNCab", "?UNCabc", Some("..")); t!(s: "?UNCabc", "?UNCacd", Some("?UNCabc")); t!(s: "?UNCbcd", "?UNCacd", Some("?UNCbcd")); t!(s: "?UNCabc", "?abc", Some("?UNCabc")); t!(s: "?UNCabc", "?C:abc", Some("?UNCabc")); t!(s: "?UNCabc/d", "?UNCab", Some("?UNCabc/d")); t!(s: "?UNCab.", "?UNCab", Some("?UNCab.")); t!(s: "?UNCab..", "?UNCab", Some("?UNCab..")); t!(s: "?UNCabc", "ab", Some("c")); t!(s: "?UNCab", "abc", Some("..")); t!(s: "?UNCabc", "acd", Some("?UNCabc")); t!(s: "?UNCbcd", "acd", Some("?UNCbcd")); t!(s: "?UNCab.", "ab", Some("?UNCab.")); t!(s: "?UNCabc/d", "ab", Some("?UNCabc/d")); t!(s: "?UNCab..", "ab", Some("?UNCab..")); t!(s: "abc", "?UNCab", Some("c")); t!(s: "abc", "?UNCacd", Some("abc")); } #[test] fn test_component_iter() { macro_rules! t( (s: $path:expr, $exp:expr) => ( { let path = Path::from_str($path); let comps = path.component_iter().to_owned_vec(); let exp: &[&str] = $exp; assert_eq!(comps.as_slice(), exp); } ); (v: [$($arg:expr),+], $exp:expr) => ( { let path = Path::new(b!($($arg),+)); let comps = path.component_iter().to_owned_vec(); let exp: &[&str] = $exp; assert_eq!(comps.as_slice(), exp); } ) ) t!(v: ["abc"], ["a", "b", "c"]); t!(s: "abc", ["a", "b", "c"]); t!(s: "abd", ["a", "b", "d"]); t!(s: "abcd", ["a", "b", "cd"]); t!(s: "abc", ["a", "b", "c"]); t!(s: "a", ["a"]); t!(s: "a", ["a"]); t!(s: "", []); t!(s: ".", ["."]); t!(s: "..", [".."]); t!(s: "....", ["..", ".."]); t!(s: "....foo", ["..", "..", "foo"]); t!(s: "C:foobar", ["foo", "bar"]); t!(s: "C:foo", ["foo"]); t!(s: "C:", []); t!(s: "C:foobar", ["foo", "bar"]); t!(s: "C:foo", ["foo"]); t!(s: "C:", []); t!(s: "serversharefoobar", ["foo", "bar"]); t!(s: "serversharefoo", ["foo"]); t!(s: "servershare", []); t!(s: "?foobarbaz", ["bar", "baz"]); t!(s: "?foobar", ["bar"]); t!(s: "?foo", []); t!(s: "?", []); t!(s: "?ab", ["b"]); t!(s: "?ab", ["b"]); t!(s: "?foobarbaz", ["bar", "", "baz"]); t!(s: "?C:foobar", ["foo", "bar"]); t!(s: "?C:foo", ["foo"]); t!(s: "?C:", []); t!(s: "?C:foo", ["foo"]); t!(s: "?UNCserversharefoobar", ["foo", "bar"]); t!(s: "?UNCserversharefoo", ["foo"]); t!(s: "?UNCservershare", []); t!(s: ".foobarbaz", ["bar", "baz"]); t!(s: ".foobar", ["bar"]); t!(s: ".foo", []); } } </ins>


- [rustdoc: Only look at blanket impls in `get_blanket_impls`][83681] - [Rework rustdoc const type][82873] <ins> [85667]: https://github.com/rust-lang/rust/pull/85667 </ins> [83386]: https://github.com/rust-lang/rust/pull/83386 [82771]: https://github.com/rust-lang/rust/pull/82771 [84147]: https://github.com/rust-lang/rust/pull/84147


<ins> // Out-of-line module is found on the filesystem if passed through a proc macro (issue #58818). // check-pass // aux-build:test-macros.rs #[macro_use] extern crate test_macros; mod outer { identity! { mod inner; } } fn main() {} </ins>


} _ => { Err(if self.prev_token_kind == PrevTokenKind::DocComment { <del> self.span_fatal_err(self.prev_span, Error::UselessDocComment) } else { self.expected_ident_found() }) </del> <ins> self.span_fatal_err(self.prev_span, Error::UselessDocComment) } else { self.expected_ident_found() }) </ins> } } }


#[rustc_const_unstable(feature = "const_waker", issue = "102012")] #[unstable(feature = "context_ext", issue = "123392")] pub const fn from(cx: &'a mut Context<'_>) -> Self { <del> let ext = match &mut cx.ext { </del> <ins> let ext = match &mut *cx.ext { </ins> ExtData::Some(ext) => ExtData::Some(*ext), ExtData::None(()) => ExtData::None(()), };


<ins> error[E0599]: no method named `clone` found for struct `issue_69725::Struct<A>` in the current scope --> $DIR/issue-69725.rs:7:32 | LL |     let _ = Struct::<A>::new().clone(); |                                ^^^^^ method not found in `issue_69725::Struct<A>` | ::: $DIR/auxiliary/issue-69725.rs:2:1 | LL | pub struct Struct<A>(A); | ------------------------ doesn't satisfy `issue_69725::Struct<A>: std::clone::Clone` | = note: the method `clone` exists but the following trait bounds were not satisfied: `A: std::clone::Clone` which is required by `issue_69725::Struct<A>: std::clone::Clone` error: aborting due to previous error For more information about this error, try `rustc --explain E0599`. </ins>


} } } else { <del> if matches!(def_kind, DefKind::AnonConst) && tcx.features().generic_const_exprs { let hir_id = tcx.local_def_id_to_hir_id(def_id); let parent_def_id = tcx.hir().get_parent_item(hir_id); if let Some(defaulted_param_def_id) = tcx.hir().opt_const_param_default_param_def_id(hir_id) { // In `generics_of` we set the generics' parent to be our parent's parent which means that // we lose out on the predicates of our actual parent if we dont return those predicates here. // (See comment in `generics_of` for more information on why the parent shenanigans is necessary) // // struct Foo<T, const N: usize = { <T as Trait>::ASSOC }>(T) where T: Trait; //        ^^^                     ^^^^^^^^^^^^^^^^^^^^^^^ the def id we are calling //        ^^^                                             explicit_predicates_of on //        parent item we dont have set as the //        parent of generics returned by `generics_of` // // In the above code we want the anon const to have predicates in its param env for `T: Trait` // and we would be calling `explicit_predicates_of(Foo)` here let parent_preds = tcx.explicit_predicates_of(parent_def_id); // If we dont filter out `ConstArgHasType` predicates then every single defaulted const parameter // will ICE because of #106994. FIXME(generic_const_exprs): remove this when a more general solution // to #106994 is implemented. let filtered_predicates = parent_preds .predicates .into_iter() .filter(|(pred, _)| { if let ty::ClauseKind::ConstArgHasType(ct, _) = pred.kind().skip_binder() { match ct.kind() { ty::ConstKind::Param(param_const) => { let defaulted_param_idx = tcx .generics_of(parent_def_id) .param_def_id_to_index[&defaulted_param_def_id.to_def_id()]; param_const.index < defaulted_param_idx } _ => bug!( "`ConstArgHasType` in `predicates_of` that isn't a `Param` const" ), </del> <ins> if matches!(def_kind, DefKind::AnonConst) && tcx.features().generic_const_exprs && let Some(defaulted_param_def_id) = tcx.hir().opt_const_param_default_param_def_id(tcx.local_def_id_to_hir_id(def_id)) { // In `generics_of` we set the generics' parent to be our parent's parent which means that // we lose out on the predicates of our actual parent if we dont return those predicates here. // (See comment in `generics_of` for more information on why the parent shenanigans is necessary) // // struct Foo<T, const N: usize = { <T as Trait>::ASSOC }>(T) where T: Trait; //        ^^^                     ^^^^^^^^^^^^^^^^^^^^^^^ the def id we are calling //        ^^^                                             explicit_predicates_of on //        parent item we dont have set as the //        parent of generics returned by `generics_of` // // In the above code we want the anon const to have predicates in its param env for `T: Trait` // and we would be calling `explicit_predicates_of(Foo)` here let parent_def_id = tcx.local_parent(def_id); let parent_preds = tcx.explicit_predicates_of(parent_def_id); // If we dont filter out `ConstArgHasType` predicates then every single defaulted const parameter // will ICE because of #106994. FIXME(generic_const_exprs): remove this when a more general solution // to #106994 is implemented. let filtered_predicates = parent_preds .predicates .into_iter() .filter(|(pred, _)| { if let ty::ClauseKind::ConstArgHasType(ct, _) = pred.kind().skip_binder() { match ct.kind() { ty::ConstKind::Param(param_const) => { let defaulted_param_idx = tcx .generics_of(parent_def_id) .param_def_id_to_index[&defaulted_param_def_id.to_def_id()]; param_const.index < defaulted_param_idx </ins> } <del> } else { true </del> <ins> _ => bug!( "`ConstArgHasType` in `predicates_of` that isn't a `Param` const" ), </ins> } <del> }) .cloned(); return GenericPredicates { parent: parent_preds.parent, predicates: { tcx.arena.alloc_from_iter(filtered_predicates) }, }; } let parent_def_kind = tcx.def_kind(parent_def_id); if matches!(parent_def_kind, DefKind::OpaqueTy) { // In `instantiate_identity` we inherit the predicates of our parent. // However, opaque types do not have a parent (see `gather_explicit_predicates_of`), which means // that we lose out on the predicates of our actual parent if we dont return those predicates here. // // // fn foo<T: Trait>() -> impl Iterator<Output = Another<{ <T as Trait>::ASSOC }> > { todo!() } //                                                        ^^^^^^^^^^^^^^^^^^^ the def id we are calling //                                                                            explicit_predicates_of on // // In the above code we want the anon const to have predicates in its param env for `T: Trait`. // However, the anon const cannot inherit predicates from its parent since it's opaque. // // To fix this, we call `explicit_predicates_of` directly on `foo`, the parent's parent. // In the above example this is `foo::{opaque#0}` or `impl Iterator` let parent_hir_id = tcx.local_def_id_to_hir_id(parent_def_id.def_id); // In the above example this is the function `foo` let item_def_id = tcx.hir().get_parent_item(parent_hir_id); // In the above code example we would be calling `explicit_predicates_of(foo)` here return tcx.explicit_predicates_of(item_def_id); } </del> <ins> } else { true } }) .cloned(); return GenericPredicates { parent: parent_preds.parent, predicates: { tcx.arena.alloc_from_iter(filtered_predicates) }, }; </ins> } gather_explicit_predicates_of(tcx, def_id) }


use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; use rustc_span::Span; <ins> use crate::constraints::graph::{self, NormalConstraintGraph, RegionGraph}; </ins> use crate::dataflow::BorrowIndex; use crate::{ <del> constraints::{ graph::NormalConstraintGraph, ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet, }, </del> <ins> constraints::{ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet}, </ins> diagnostics::{RegionErrorKind, RegionErrors, UniverseInfo}, member_constraints::{MemberConstraintSet, NllMemberConstraintIndex}, nll::PoloniusOutput,


<ins> struct Binder(i32, i32, i32); fn main() { let x = Binder(1, 2, 3); match x { Binder(_a, _x @ ..) => {} _ => {} } } //~^^^^ ERROR `_x @` is not allowed in a tuple struct </ins>


{ "pre-link-args": {"gcc": ["-m64"]}, <del> "data-layout": "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128", </del> <ins> "data-layout": "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128", </ins> "linker-flavor": "gcc", "llvm-target": "x86_64-unknown-linux-gnu", "target-endian": "little",


<ins> #![feature(return_position_impl_trait_in_trait)] trait Extend { fn extend<'a: 'a>(_: &'a str) -> (impl Sized + 'a, &'static str); } impl Extend for () { fn extend<'a: 'a>(s: &'a str) -> (Option<&'static &'a ()>, &'static str) //~^ ERROR in type `&'static &'a ()`, reference has a longer lifetime than the data it references where 'a: 'static, { (None, s) } } // This indirection is not necessary for reproduction, // but it makes this test future-proof against #114936. fn extend<T: Extend>(s: &str) -> &'static str { <T as Extend>::extend(s).1 } fn main() { let use_after_free = extend::<()>(&String::from("temporary")); println!("{}", use_after_free); } </ins>


<ins> use super::{error_to_const_error, CompileTimeEvalContext, CompileTimeInterpreter}; use crate::interpret::eval_nullary_intrinsic; use crate::interpret::{ intern_const_alloc_recursive, Allocation, ConstValue, GlobalId, ImmTy, Immediate, InterpCx, InterpResult, MPlaceTy, MemoryKind, OpTy, RawConst, RefTracking, Scalar, ScalarMaybeUndef, StackPopCleanup, }; use rustc::hir::def::DefKind; use rustc::mir; use rustc::mir::interpret::{ConstEvalErr, ErrorHandled}; use rustc::traits::Reveal; use rustc::ty::{self, layout, layout::LayoutOf, subst::Subst, TyCtxt}; use std::convert::TryInto; use syntax::source_map::Span; pub fn note_on_undefined_behavior_error() -> &'static str { "The rules on what exactly is undefined behavior aren't clear,  so this check might be overzealous. Please open an issue on the rustc  repository if you believe it should not be considered undefined behavior." } // Returns a pointer to where the result lives fn eval_body_using_ecx<'mir, 'tcx>( ecx: &mut CompileTimeEvalContext<'mir, 'tcx>, cid: GlobalId<'tcx>, body: &'mir mir::Body<'tcx>, ) -> InterpResult<'tcx, MPlaceTy<'tcx>> { debug!("eval_body_using_ecx: {:?}, {:?}", cid, ecx.param_env); let tcx = ecx.tcx.tcx; let layout = ecx.layout_of(body.return_ty().subst(tcx, cid.instance.substs))?; assert!(!layout.is_unsized()); let ret = ecx.allocate(layout, MemoryKind::Stack); let name = ty::tls::with(|tcx| tcx.def_path_str(cid.instance.def_id())); let prom = cid.promoted.map_or(String::new(), |p| format!("::promoted[{:?}]", p)); trace!("eval_body_using_ecx: pushing stack frame for global: {}{}", name, prom); // Assert all args (if any) are zero-sized types; `eval_body_using_ecx` doesn't // make sense if the body is expecting nontrivial arguments. // (The alternative would be to use `eval_fn_call` with an args slice.) for arg in body.args_iter() { let decl = body.local_decls.get(arg).expect("arg missing from local_decls"); let layout = ecx.layout_of(decl.ty.subst(tcx, cid.instance.substs))?; assert!(layout.is_zst()) } ecx.push_stack_frame( cid.instance, body.span, body, Some(ret.into()), StackPopCleanup::None { cleanup: false }, )?; // The main interpreter loop. ecx.run()?; // Intern the result intern_const_alloc_recursive(ecx, tcx.static_mutability(cid.instance.def_id()), ret)?; debug!("eval_body_using_ecx done: {:?}", *ret); Ok(ret) } /// The `InterpCx` is only meant to be used to do field and index projections into constants for /// `simd_shuffle` and const patterns in match arms. /// /// The function containing the `match` that is currently being analyzed may have generic bounds /// that inform us about the generic bounds of the constant. E.g., using an associated constant /// of a function's generic parameter will require knowledge about the bounds on the generic /// parameter. These bounds are passed to `mk_eval_cx` via the `ParamEnv` argument. pub(super) fn mk_eval_cx<'mir, 'tcx>( tcx: TyCtxt<'tcx>, span: Span, param_env: ty::ParamEnv<'tcx>, can_access_statics: bool, ) -> CompileTimeEvalContext<'mir, 'tcx> { debug!("mk_eval_cx: {:?}", param_env); InterpCx::new( tcx.at(span), param_env, CompileTimeInterpreter::new(), MemoryExtra { can_access_statics }, ) } pub(super) fn op_to_const<'tcx>( ecx: &CompileTimeEvalContext<'_, 'tcx>, op: OpTy<'tcx>, ) -> &'tcx ty::Const<'tcx> { // We do not have value optimizations for everything. // Only scalars and slices, since they are very common. // Note that further down we turn scalars of undefined bits back to `ByRef`. These can result // from scalar unions that are initialized with one of their zero sized variants. We could // instead allow `ConstValue::Scalar` to store `ScalarMaybeUndef`, but that would affect all // the usual cases of extracting e.g. a `usize`, without there being a real use case for the // `Undef` situation. let try_as_immediate = match op.layout.abi { layout::Abi::Scalar(..) => true, layout::Abi::ScalarPair(..) => match op.layout.ty.kind { ty::Ref(_, inner, _) => match inner.kind { ty::Slice(elem) => elem == ecx.tcx.types.u8, ty::Str => true, _ => false, }, _ => false, }, _ => false, }; let immediate = if try_as_immediate { Err(ecx.read_immediate(op).expect("normalization works on validated constants")) } else { // It is guaranteed that any non-slice scalar pair is actually ByRef here. // When we come back from raw const eval, we are always by-ref. The only way our op here is // by-val is if we are in const_field, i.e., if this is (a field of) something that we // "tried to make immediate" before. We wouldn't do that for non-slice scalar pairs or // structs containing such. op.try_as_mplace() }; let val = match immediate { Ok(mplace) => { let ptr = mplace.ptr.to_ptr().unwrap(); let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id); ConstValue::ByRef { alloc, offset: ptr.offset } } // see comment on `let try_as_immediate` above Err(ImmTy { imm: Immediate::Scalar(x), .. }) => match x { ScalarMaybeUndef::Scalar(s) => ConstValue::Scalar(s), ScalarMaybeUndef::Undef => { // When coming out of "normal CTFE", we'll always have an `Indirect` operand as // argument and we will not need this. The only way we can already have an // `Immediate` is when we are called from `const_field`, and that `Immediate` // comes from a constant so it can happen have `Undef`, because the indirect // memory that was read had undefined bytes. let mplace = op.assert_mem_place(); let ptr = mplace.ptr.to_ptr().unwrap(); let alloc = ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id); ConstValue::ByRef { alloc, offset: ptr.offset } } }, Err(ImmTy { imm: Immediate::ScalarPair(a, b), .. }) => { let (data, start) = match a.not_undef().unwrap() { Scalar::Ptr(ptr) => { (ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id), ptr.offset.bytes()) } Scalar::Raw { .. } => ( ecx.tcx.intern_const_alloc(Allocation::from_byte_aligned_bytes(b"" as &[u8])), 0, ), }; let len = b.to_machine_usize(&ecx.tcx.tcx).unwrap(); let start = start.try_into().unwrap(); let len: usize = len.try_into().unwrap(); ConstValue::Slice { data, start, end: start + len } } }; ecx.tcx.mk_const(ty::Const { val: ty::ConstKind::Value(val), ty: op.layout.ty }) } fn validate_and_turn_into_const<'tcx>( tcx: TyCtxt<'tcx>, constant: RawConst<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> { let cid = key.value; let def_id = cid.instance.def.def_id(); let is_static = tcx.is_static(def_id); let ecx = mk_eval_cx(tcx, tcx.def_span(key.value.instance.def_id()), key.param_env, is_static); let val = (|| { let mplace = ecx.raw_const_to_mplace(constant)?; let mut ref_tracking = RefTracking::new(mplace); while let Some((mplace, path)) = ref_tracking.todo.pop() { ecx.validate_operand(mplace.into(), path, Some(&mut ref_tracking))?; } // Now that we validated, turn this into a proper constant. // Statics/promoteds are always `ByRef`, for the rest `op_to_const` decides // whether they become immediates. if is_static || cid.promoted.is_some() { let ptr = mplace.ptr.to_ptr()?; Ok(tcx.mk_const(ty::Const { val: ty::ConstKind::Value(ConstValue::ByRef { alloc: ecx.tcx.alloc_map.lock().unwrap_memory(ptr.alloc_id), offset: ptr.offset, }), ty: mplace.layout.ty, })) } else { Ok(op_to_const(&ecx, mplace.into())) } })(); val.map_err(|error| { let err = error_to_const_error(&ecx, error); match err.struct_error(ecx.tcx, "it is undefined behavior to use this value") { Ok(mut diag) => { diag.note(note_on_undefined_behavior_error()); diag.emit(); ErrorHandled::Reported } Err(err) => err, } }) } pub fn const_eval_validated_provider<'tcx>( tcx: TyCtxt<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ::rustc::mir::interpret::ConstEvalResult<'tcx> { // see comment in const_eval_raw_provider for what we're doing here if key.param_env.reveal == Reveal::All { let mut key = key.clone(); key.param_env.reveal = Reveal::UserFacing; match tcx.const_eval_validated(key) { // try again with reveal all as requested Err(ErrorHandled::TooGeneric) => { // Promoteds should never be "too generic" when getting evaluated. // They either don't get evaluated, or we are in a monomorphic context assert!(key.value.promoted.is_none()); } // dedupliate calls other => return other, } } // We call `const_eval` for zero arg intrinsics, too, in order to cache their value. // Catch such calls and evaluate them instead of trying to load a constant's MIR. if let ty::InstanceDef::Intrinsic(def_id) = key.value.instance.def { let ty = key.value.instance.ty(tcx); let substs = match ty.kind { ty::FnDef(_, substs) => substs, _ => bug!("intrinsic with type {:?}", ty), }; return eval_nullary_intrinsic(tcx, key.param_env, def_id, substs).map_err(|error| { let span = tcx.def_span(def_id); let error = ConstEvalErr { error: error.kind, stacktrace: vec![], span }; error.report_as_error(tcx.at(span), "could not evaluate nullary intrinsic") }); } tcx.const_eval_raw(key).and_then(|val| validate_and_turn_into_const(tcx, val, key)) } pub fn const_eval_raw_provider<'tcx>( tcx: TyCtxt<'tcx>, key: ty::ParamEnvAnd<'tcx, GlobalId<'tcx>>, ) -> ::rustc::mir::interpret::ConstEvalRawResult<'tcx> { // Because the constant is computed twice (once per value of `Reveal`), we are at risk of // reporting the same error twice here. To resolve this, we check whether we can evaluate the // constant in the more restrictive `Reveal::UserFacing`, which most likely already was // computed. For a large percentage of constants that will already have succeeded. Only // associated constants of generic functions will fail due to not enough monomorphization // information being available. // In case we fail in the `UserFacing` variant, we just do the real computation. if key.param_env.reveal == Reveal::All { let mut key = key.clone(); key.param_env.reveal = Reveal::UserFacing; match tcx.const_eval_raw(key) { // try again with reveal all as requested Err(ErrorHandled::TooGeneric) => {} // dedupliate calls other => return other, } } if cfg!(debug_assertions) { // Make sure we format the instance even if we do not print it. // This serves as a regression test against an ICE on printing. // The next two lines concatenated contain some discussion: // https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/ // subject/anon_const_instance_printing/near/135980032 let instance = key.value.instance.to_string(); trace!("const eval: {:?} ({})", key, instance); } let cid = key.value; let def_id = cid.instance.def.def_id(); if def_id.is_local() && tcx.typeck_tables_of(def_id).tainted_by_errors { return Err(ErrorHandled::Reported); } let is_static = tcx.is_static(def_id); let span = tcx.def_span(cid.instance.def_id()); let mut ecx = InterpCx::new( tcx.at(span), key.param_env, CompileTimeInterpreter::new(), MemoryExtra { can_access_statics: is_static }, ); let res = ecx.load_mir(cid.instance.def, cid.promoted); res.and_then(|body| eval_body_using_ecx(&mut ecx, cid, *body)) .and_then(|place| { Ok(RawConst { alloc_id: place.ptr.assert_ptr().alloc_id, ty: place.layout.ty }) }) .map_err(|error| { let err = error_to_const_error(&ecx, error); // errors in statics are always emitted as fatal errors if is_static { // Ensure that if the above error was either `TooGeneric` or `Reported` // an error must be reported. let v = err.report_as_error(ecx.tcx, "could not evaluate static initializer"); tcx.sess.delay_span_bug( err.span, &format!("static eval failure did not emit an error: {:#?}", v), ); v } else if def_id.is_local() { // constant defined in this crate, we can figure out a lint level! match tcx.def_kind(def_id) { // constants never produce a hard error at the definition site. Anything else is // a backwards compatibility hazard (and will break old versions of winapi for sure) // // note that validation may still cause a hard error on this very same constant, // because any code that existed before validation could not have failed validation // thus preventing such a hard error from being a backwards compatibility hazard Some(DefKind::Const) | Some(DefKind::AssocConst) => { let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap(); err.report_as_lint( tcx.at(tcx.def_span(def_id)), "any use of this value will cause an error", hir_id, Some(err.span), ) } // promoting runtime code is only allowed to error if it references broken constants // any other kind of error will be reported to the user as a deny-by-default lint _ => { if let Some(p) = cid.promoted { let span = tcx.promoted_mir(def_id)[p].span; if let err_inval!(ReferencedConstant) = err.error { err.report_as_error( tcx.at(span), "evaluation of constant expression failed", ) } else { err.report_as_lint( tcx.at(span), "reaching this expression at runtime will panic or abort", tcx.hir().as_local_hir_id(def_id).unwrap(), Some(err.span), ) } // anything else (array lengths, enum initializers, constant patterns) are reported // as hard errors } else { err.report_as_error(ecx.tcx, "evaluation of constant value failed") } } } } else { // use of broken constant from other crate err.report_as_error(ecx.tcx, "could not evaluate constant") } }) } </ins>


<ins> // Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Regression test for a weird corner case in our dep-graph reduction // code. When we solve `CoerceUnsized<Foo>`, we find no impls, so we // don't end up with an edge to any HIR nodes, but it still gets // preserved in the dep graph. // revisions:rpass1 rpass2 // compile-flags: -Z query-dep-graph use std::sync::Arc; #[cfg(rpass1)] struct Foo { x: usize } #[cfg(rpass1)] fn main() { let x: Arc<Foo> = Arc::new(Foo { x: 22 }); let y: Arc<Foo> = x; } #[cfg(rpass2)] struct FooX { x: usize } #[cfg(rpass2)] fn main() { let x: Arc<FooX> = Arc::new(FooX { x: 22 }); let y: Arc<FooX> = x; } </ins>


} } <del> #[unstable(feature = "panic_info_message", issue = "66745")] </del> <ins> #[stable(feature = "panic_info_message", since = "CURRENT_RUSTC_VERSION")] </ins> impl fmt::Debug for PanicMessage<'_> { #[inline] fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {


endif endif <ins> ifdef CFG_DISABLE_RPATH ifeq ($$(OSTYPE_$(3)),apple-darwin) RPATH_VAR$(1)_T_$(2)_H_$(3) :=  DYLD_LIBRARY_PATH="$$$$DYLD_LIBRARY_PATH:$$(HLIB$(1)_H_$(3))" else RPATH_VAR$(1)_T_$(2)_H_$(3) :=  LD_LIBRARY_PATH="$$$$LD_LIBRARY_PATH:$$(HLIB$(1)_H_$(3))" endif else RPATH_VAR$(1)_T_$(2)_H_$(3) := endif </ins> STAGE$(1)_T_$(2)_H_$(3) := 						 <del> $$(Q)$$(call CFG_RUN_TARG_$(3),$(1),				 </del> <ins> $$(Q)$$(RPATH_VAR$(1)_T_$(2)_H_$(3))                             $$(call CFG_RUN_TARG_$(3),$(1),				 </ins> $$(CFG_VALGRIND_COMPILE$(1)) 			 $$(HBIN$(1)_H_$(3))/rustc$$(X_$(3))			 --cfg $$(CFGFLAG$(1)_T_$(2)_H_$(3))


[[package]] name = "unicase" <del> version = "2.6.0" </del> <ins> version = "2.7.0" </ins> source = "registry+https://github.com/rust-lang/crates.io-index" <del> checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" </del> <ins> checksum = "f7d2d4dafb69621809a81864c9c1b864479e1235c0dd4e199924b9742439ed89" </ins> dependencies = [ "version_check", ]


<ins> error[E0432]: unresolved import `self::a::E` --> $DIR/unresolved-seg-after-ambiguous.rs:19:14 | LL | use self::a::E::in_exist; |              ^ `E` is a struct, not a module warning: `E` is ambiguous --> $DIR/unresolved-seg-after-ambiguous.rs:19:14 | LL | use self::a::E::in_exist; |              ^ ambiguous name | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #114095 <https://github.com/rust-lang/rust/issues/114095> = note: ambiguous because of multiple glob imports of a name in the same module note: `E` could refer to the struct imported here --> $DIR/unresolved-seg-after-ambiguous.rs:13:17 | LL |         pub use self::c::*; |                 ^^^^^^^^^^ = help: consider adding an explicit import of `E` to disambiguate note: `E` could also refer to the struct imported here --> $DIR/unresolved-seg-after-ambiguous.rs:12:17 | LL |         pub use self::d::*; |                 ^^^^^^^^^^ = help: consider adding an explicit import of `E` to disambiguate = note: `#[warn(ambiguous_glob_imports)]` on by default error: aborting due to 1 previous error; 1 warning emitted For more information about this error, try `rustc --explain E0432`. </ins>


self.raw_bytes().starts_with(METADATA_HEADER) } <ins> pub fn get_rustc_version(&self) -> String { Lazy::with_position(METADATA_HEADER.len() + 4).decode(self) } </ins> pub fn get_root(&self) -> CrateRoot { let slice = self.raw_bytes(); let offset = METADATA_HEADER.len();


check_operand(tcx, discr, span, def_id, body) } <ins> // FIXME(ecstaticmorse): We probably want to allow `Unreachable` unconditionally. TerminatorKind::Unreachable if tcx.features().const_if_match => Ok(()), </ins> | TerminatorKind::Abort | TerminatorKind::Unreachable => { Err((span, "const fn with unreachable code is not stable".into())) }


<ins> // ignore-tidy-linelength // We do not promote mutable references. static mut TEST1: Option<&mut [i32]> = Some(&mut [1, 2, 3]); //~ ERROR temporary value dropped while borrowed static mut TEST2: &'static mut [i32] = { let x = &mut [1,2,3]; //~ ERROR temporary value dropped while borrowed x }; fn main() {} </ins>


<ins> error[E0423]: expected function, found struct `B` --> $DIR/issue-42944.rs:9:9 | LL |         B(()); //~ ERROR expected function, found struct `B` [E0423] |         ^ constructor is not visible here due to private fields error[E0425]: cannot find function `B` in this scope --> $DIR/issue-42944.rs:15:9 | LL |         B(()); //~ ERROR cannot find function `B` in this scope [E0425] |         ^ not found in this scope help: possible candidate is found in another module, you can import it into scope | LL |     use foo::B; | error: aborting due to 2 previous errors Some errors occurred: E0423, E0425. For more information about an error, try `rustc --explain E0423`. </ins>


= note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced) = help: copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers) <del> error: aborting due to 7 previous errors </del> <ins> error: reference to packed field is unaligned --> $DIR/unaligned_references.rs:90:20 | LL |         let _ref = &m1.1.a; |                    ^^^^^^^ | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #82523 <https://github.com/rust-lang/rust/issues/82523> = note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced) = help: copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers) error: reference to packed field is unaligned --> $DIR/unaligned_references.rs:100:20 | LL |         let _ref = &m2.1.a; |                    ^^^^^^^ | = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #82523 <https://github.com/rust-lang/rust/issues/82523> = note: fields of packed structs are not properly aligned, and creating a misaligned reference is undefined behavior (even if that reference is never dereferenced) = help: copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers) error: aborting due to 9 previous errors </ins> Future incompatibility report: Future breakage diagnostic: error: reference to packed field is unaligned


| = note: see issue #65991 <https://github.com/rust-lang/rust/issues/65991> for more information = help: add `#![feature(trait_upcasting)]` to the crate attributes to enable <ins> = note: required when coercing `Box<(dyn Fn() + 'static)>` into `Box<(dyn FnMut() + 'static)>` </ins> error: aborting due to previous error


} ast::ExprStruct(_, ref fields, _) => { match ty::expr_ty(self.tcx, expr).sty { <del> ty::ty_struct(id, _) => { for field in &(*fields) { self.check_field(expr.span, id, NamedField(field.ident.node)); </del> <ins> ty::ty_struct(ctor_id, _) => { // RFC 736: ensure all unmentioned fields are visible. // Rather than computing the set of unmentioned fields // (i.e. `all_fields - fields`), just check them all. let all_fields = ty::lookup_struct_fields(self.tcx, ctor_id); for field in all_fields { self.check_field(expr.span, ctor_id, NamedField(field.name)); </ins> } } ty::ty_enum(_, _) => {


<ins> error[E0491]: in type `&'static &()`, reference has a longer lifetime than the data it references --> $DIR/rpitit-hidden-types-self-implied-wf.rs:8:27 | LL |     fn extend(s: &str) -> (Option<&'static &'_ ()>, &'static str) { |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: the pointer is valid for the static lifetime note: but the referenced data is only valid for the anonymous lifetime defined here --> $DIR/rpitit-hidden-types-self-implied-wf.rs:8:18 | LL |     fn extend(s: &str) -> (Option<&'static &'_ ()>, &'static str) { |                  ^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0491`. </ins>


version = "0.18.2" dependencies = [ "derive-new", <del> "env_logger 0.7.1", </del> <ins> "env_logger 0.9.0", </ins> "fst", <del> "itertools 0.9.0", </del> <ins> "itertools 0.10.1", </ins> "json", "lazy_static", "log",


} impl<T,U> Foo<T> for U { <del> // OK, T, U are used everywhere. Note that the coherence check // hasn't executed yet, so no errors about overlap. </del> <ins> //~^ ERROR conflicting implementations of trait `Foo<_>` for type `[isize; 0]` </ins> } impl<T,U> Bar for T {


needlesArr.iter().fold(|x, y| { }); //~^^ ERROR this function takes 2 parameters but 1 parameter was supplied <del> //~^^^ NOTE the following parameter types were expected // </del> <ins> //~| NOTE the following parameter types were expected //~| NOTE expected 2 parameters </ins> // the first error is, um, non-ideal. }