Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rollup of 6 pull requests #83658

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion compiler/rustc_middle/src/ty/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -699,7 +699,6 @@ impl<'tcx> ty::TyS<'tcx> {
/// optimization as well as the rules around static values. Note
/// that the `Freeze` trait is not exposed to end users and is
/// effectively an implementation detail.
// FIXME: use `TyCtxtAt` instead of separate `Span`.
pub fn is_freeze(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool {
self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self))
}
Expand Down
26 changes: 26 additions & 0 deletions library/core/src/num/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#![stable(feature = "rust1", since = "1.0.0")]

use crate::ascii;
use crate::intrinsics;
use crate::mem;
use crate::str::FromStr;
Expand Down Expand Up @@ -661,6 +662,31 @@ impl u8 {
pub const fn is_ascii_control(&self) -> bool {
matches!(*self, b'\0'..=b'\x1F' | b'\x7F')
}

/// Returns an iterator that produces an escaped version of a `u8`,
/// treating it as an ASCII character.
///
/// The behavior is identical to [`ascii::escape_default`].
///
/// # Examples
///
/// ```
/// #![feature(inherent_ascii_escape)]
///
/// assert_eq!("0", b'0'.escape_ascii().to_string());
/// assert_eq!("\\t", b'\t'.escape_ascii().to_string());
/// assert_eq!("\\r", b'\r'.escape_ascii().to_string());
/// assert_eq!("\\n", b'\n'.escape_ascii().to_string());
/// assert_eq!("\\'", b'\''.escape_ascii().to_string());
/// assert_eq!("\\\"", b'"'.escape_ascii().to_string());
/// assert_eq!("\\\\", b'\\'.escape_ascii().to_string());
/// assert_eq!("\\x9d", b'\x9d'.escape_ascii().to_string());
/// ```
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
#[inline]
pub fn escape_ascii(&self) -> ascii::EscapeDefault {
ascii::escape_default(*self)
}
}

#[lang = "u16"]
Expand Down
92 changes: 92 additions & 0 deletions library/core/src/slice/ascii.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
//! Operations on ASCII `[u8]`.

use crate::ascii;
use crate::fmt::{self, Write};
use crate::iter;
use crate::mem;
use crate::ops;

#[lang = "slice_u8"]
#[cfg(not(test))]
Expand Down Expand Up @@ -56,6 +59,95 @@ impl [u8] {
byte.make_ascii_lowercase();
}
}

/// Returns an iterator that produces an escaped version of this slice,
/// treating it as an ASCII string.
///
/// # Examples
///
/// ```
/// #![feature(inherent_ascii_escape)]
///
/// let s = b"0\t\r\n'\"\\\x9d";
/// let escaped = s.escape_ascii().to_string();
/// assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
/// ```
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
pub fn escape_ascii(&self) -> EscapeAscii<'_> {
EscapeAscii { inner: self.iter().flat_map(EscapeByte) }
}
}

impl_fn_for_zst! {
#[derive(Clone)]
struct EscapeByte impl Fn = |byte: &u8| -> ascii::EscapeDefault {
ascii::escape_default(*byte)
};
}

/// An iterator over the escaped version of a byte slice.
///
/// This `struct` is created by the [`slice::escape_ascii`] method. See its
/// documentation for more information.
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
#[derive(Clone)]
pub struct EscapeAscii<'a> {
inner: iter::FlatMap<super::Iter<'a, u8>, ascii::EscapeDefault, EscapeByte>,
}

#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::Iterator for EscapeAscii<'a> {
type Item = u8;
#[inline]
fn next(&mut self) -> Option<u8> {
self.inner.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
#[inline]
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Fold: FnMut(Acc, Self::Item) -> R,
R: ops::Try<Ok = Acc>,
{
self.inner.try_fold(init, fold)
}
#[inline]
fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.inner.fold(init, fold)
}
#[inline]
fn last(mut self) -> Option<u8> {
self.next_back()
}
}

#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::DoubleEndedIterator for EscapeAscii<'a> {
fn next_back(&mut self) -> Option<u8> {
self.inner.next_back()
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::ExactSizeIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::FusedIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Display for EscapeAscii<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.clone().try_for_each(|b| f.write_char(b as char))
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Debug for EscapeAscii<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad("EscapeAscii { .. }")
}
}

/// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
Expand Down
3 changes: 3 additions & 0 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ pub use index::SliceIndex;
#[unstable(feature = "slice_range", issue = "76393")]
pub use index::range;

#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
pub use ascii::EscapeAscii;

#[lang = "slice"]
#[cfg(not(test))]
impl<T> [T] {
Expand Down
1 change: 1 addition & 0 deletions src/librustdoc/html/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1162,6 +1162,7 @@ crate fn plain_text_summary(md: &str) -> String {
s
}

#[derive(Debug)]
crate struct MarkdownLink {
pub kind: LinkType,
pub link: String,
Expand Down
4 changes: 3 additions & 1 deletion src/librustdoc/html/static/rustdoc.css
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,9 @@ nav.sub {
text-overflow: ellipsis;
margin: 0;
}
.docblock-short code {
/* Wrap non-pre code blocks (`text`) but not (```text```). */
.docblock > :not(pre) > code,
.docblock-short > :not(pre) > code {
white-space: pre-wrap;
}

Expand Down
90 changes: 64 additions & 26 deletions src/librustdoc/passes/collect_intra_doc_links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -950,6 +950,7 @@ impl LinkCollector<'_, '_> {
}

let link = ori_link.link.replace("`", "");
let no_backticks_range = range_between_backticks(&ori_link);
let parts = link.split('#').collect::<Vec<_>>();
let (link, extra_fragment) = if parts.len() > 2 {
// A valid link can't have multiple #'s
Expand All @@ -973,10 +974,15 @@ impl LinkCollector<'_, '_> {
};

// Parse and strip the disambiguator from the link, if present.
let (mut path_str, disambiguator) = if let Ok((d, path)) = Disambiguator::from_str(&link) {
(path.trim(), Some(d))
} else {
(link.trim(), None)
let (mut path_str, disambiguator) = match Disambiguator::from_str(&link) {
Ok(Some((d, path))) => (path.trim(), Some(d)),
Ok(None) => (link.trim(), None),
Err((err_msg, relative_range)) => {
let disambiguator_range = (no_backticks_range.start + relative_range.start)
..(no_backticks_range.start + relative_range.end);
disambiguator_error(self.cx, &item, dox, disambiguator_range, &err_msg);
return None;
}
};

if path_str.contains(|ch: char| !(ch.is_alphanumeric() || ":_<>, !*&;".contains(ch))) {
Expand Down Expand Up @@ -1488,6 +1494,27 @@ impl LinkCollector<'_, '_> {
}
}

/// Get the section of a link between the backticks,
/// or the whole link if there aren't any backticks.
///
/// For example:
///
/// ```text
/// [`Foo`]
/// ^^^
/// ```
fn range_between_backticks(ori_link: &MarkdownLink) -> Range<usize> {
let after_first_backtick_group = ori_link.link.bytes().position(|b| b != b'`').unwrap_or(0);
let before_second_backtick_group = ori_link
.link
.bytes()
.skip(after_first_backtick_group)
.position(|b| b == b'`')
.unwrap_or(ori_link.link.len());
(ori_link.range.start + after_first_backtick_group)
..(ori_link.range.start + before_second_backtick_group)
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
/// Disambiguators for a link.
enum Disambiguator {
Expand All @@ -1514,27 +1541,14 @@ impl Disambiguator {
}
}

/// Given a link, parse and return `(disambiguator, path_str)`
fn from_str(link: &str) -> Result<(Self, &str), ()> {
/// Given a link, parse and return `(disambiguator, path_str)`.
///
/// This returns `Ok(Some(...))` if a disambiguator was found,
/// `Ok(None)` if no disambiguator was found, or `Err(...)`
/// if there was a problem with the disambiguator.
fn from_str(link: &str) -> Result<Option<(Self, &str)>, (String, Range<usize>)> {
use Disambiguator::{Kind, Namespace as NS, Primitive};

let find_suffix = || {
let suffixes = [
("!()", DefKind::Macro(MacroKind::Bang)),
("()", DefKind::Fn),
("!", DefKind::Macro(MacroKind::Bang)),
];
for &(suffix, kind) in &suffixes {
if let Some(link) = link.strip_suffix(suffix) {
// Avoid turning `!` or `()` into an empty string
if !link.is_empty() {
return Ok((Kind(kind), link));
}
}
}
Err(())
};

if let Some(idx) = link.find('@') {
let (prefix, rest) = link.split_at(idx);
let d = match prefix {
Expand All @@ -1551,11 +1565,24 @@ impl Disambiguator {
"value" => NS(Namespace::ValueNS),
"macro" => NS(Namespace::MacroNS),
"prim" | "primitive" => Primitive,
_ => return find_suffix(),
_ => return Err((format!("unknown disambiguator `{}`", prefix), 0..idx)),
};
Ok((d, &rest[1..]))
Ok(Some((d, &rest[1..])))
} else {
find_suffix()
let suffixes = [
("!()", DefKind::Macro(MacroKind::Bang)),
("()", DefKind::Fn),
("!", DefKind::Macro(MacroKind::Bang)),
];
for &(suffix, kind) in &suffixes {
if let Some(link) = link.strip_suffix(suffix) {
// Avoid turning `!` or `()` into an empty string
if !link.is_empty() {
return Ok(Some((Kind(kind), link)));
}
}
}
Ok(None)
}
}

Expand Down Expand Up @@ -1979,6 +2006,17 @@ fn anchor_failure(
});
}

/// Report an error in the link disambiguator.
fn disambiguator_error(
cx: &DocContext<'_>,
item: &Item,
dox: &str,
link_range: Range<usize>,
msg: &str,
) {
report_diagnostic(cx.tcx, BROKEN_INTRA_DOC_LINKS, msg, item, dox, &link_range, |_diag, _sp| {});
}

/// Report an ambiguity error, where there were multiple possible resolutions.
fn ambiguity_error(
cx: &DocContext<'_>,
Expand Down
13 changes: 13 additions & 0 deletions src/test/rustdoc-ui/intra-doc/unknown-disambiguator.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#![deny(warnings)]

//! Linking to [foo@banana] and [`bar@banana!()`].
//~^ ERROR unknown disambiguator `foo`
//~| ERROR unknown disambiguator `bar`
//! And to [no disambiguator](@nectarine) and [another](@apricot!()).
//~^ ERROR unknown disambiguator ``
//~| ERROR unknown disambiguator ``
//! And with weird backticks: [``foo@hello``] [foo`@`hello].
//~^ ERROR unknown disambiguator `foo`
//~| ERROR unknown disambiguator `foo`

fn main() {}
45 changes: 45 additions & 0 deletions src/test/rustdoc-ui/intra-doc/unknown-disambiguator.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
error: unknown disambiguator `foo`
--> $DIR/unknown-disambiguator.rs:3:17
|
LL | //! Linking to [foo@banana] and [`bar@banana!()`].
| ^^^
|
note: the lint level is defined here
--> $DIR/unknown-disambiguator.rs:1:9
|
LL | #![deny(warnings)]
| ^^^^^^^^
= note: `#[deny(rustdoc::broken_intra_doc_links)]` implied by `#[deny(warnings)]`

error: unknown disambiguator `bar`
--> $DIR/unknown-disambiguator.rs:3:35
|
LL | //! Linking to [foo@banana] and [`bar@banana!()`].
| ^^^

error: unknown disambiguator `foo`
--> $DIR/unknown-disambiguator.rs:9:34
|
LL | //! And with weird backticks: [``foo@hello``] [foo`@`hello].
| ^^^

error: unknown disambiguator `foo`
--> $DIR/unknown-disambiguator.rs:9:48
|
LL | //! And with weird backticks: [``foo@hello``] [foo`@`hello].
| ^^^

error: unknown disambiguator ``
--> $DIR/unknown-disambiguator.rs:6:31
|
LL | //! And to [no disambiguator](@nectarine) and [another](@apricot!()).
| ^

error: unknown disambiguator ``
--> $DIR/unknown-disambiguator.rs:6:57
|
LL | //! And to [no disambiguator](@nectarine) and [another](@apricot!()).
| ^

error: aborting due to 6 previous errors

Loading