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 #91013

Closed
wants to merge 13 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
24 changes: 23 additions & 1 deletion compiler/rustc_incremental/src/persist/load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use rustc_middle::dep_graph::{SerializedDepGraph, WorkProduct, WorkProductId};
use rustc_middle::ty::OnDiskCache;
use rustc_serialize::opaque::Decoder;
use rustc_serialize::Decodable;
use rustc_session::config::IncrementalStateAssertion;
use rustc_session::Session;
use std::path::Path;

Expand All @@ -16,6 +17,7 @@ use super::work_product;

type WorkProductMap = FxHashMap<WorkProductId, WorkProduct>;

#[derive(Debug)]
pub enum LoadResult<T> {
Ok { data: T },
DataOutOfDate,
Expand All @@ -24,6 +26,26 @@ pub enum LoadResult<T> {

impl<T: Default> LoadResult<T> {
pub fn open(self, sess: &Session) -> T {
// Check for errors when using `-Zassert-incremental-state`
match (sess.opts.assert_incr_state, &self) {
(Some(IncrementalStateAssertion::NotLoaded), LoadResult::Ok { .. }) => {
sess.fatal(
"We asserted that the incremental cache should not be loaded, \
but it was loaded.",
);
}
(
Some(IncrementalStateAssertion::Loaded),
LoadResult::Error { .. } | LoadResult::DataOutOfDate,
) => {
sess.fatal(
"We asserted that an existing incremental cache directory should \
be successfully loaded, but it was not.",
);
}
_ => {}
};

match self {
LoadResult::Error { message } => {
sess.warn(&message);
Expand All @@ -33,7 +55,7 @@ impl<T: Default> LoadResult<T> {
if let Err(err) = delete_all_session_dir_contents(sess) {
sess.err(&format!(
"Failed to delete invalidated or incompatible \
incremental compilation session directory contents `{}`: {}.",
incremental compilation session directory contents `{}`: {}.",
dep_graph_path(sess).display(),
err
));
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_interface/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,7 @@ fn test_debugging_options_tracking_hash() {

// Make sure that changing an [UNTRACKED] option leaves the hash unchanged.
// This list is in alphabetical order.
untracked!(assert_incr_state, Some(String::from("loaded")));
untracked!(ast_json, true);
untracked!(ast_json_noexpand, true);
untracked!(borrowck, String::from("other"));
Expand Down
32 changes: 32 additions & 0 deletions compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,18 @@ pub enum LinkerPluginLto {
Disabled,
}

/// Used with `-Z assert-incr-state`.
#[derive(Clone, Copy, PartialEq, Hash, Debug)]
pub enum IncrementalStateAssertion {
/// Found and loaded an existing session directory.
///
/// Note that this says nothing about whether any particular query
/// will be found to be red or green.
Loaded,
/// Did not load an existing session directory.
NotLoaded,
}

impl LinkerPluginLto {
pub fn enabled(&self) -> bool {
match *self {
Expand Down Expand Up @@ -704,6 +716,7 @@ pub fn host_triple() -> &'static str {
impl Default for Options {
fn default() -> Options {
Options {
assert_incr_state: None,
crate_types: Vec::new(),
optimize: OptLevel::No,
debuginfo: DebugInfo::None,
Expand Down Expand Up @@ -1626,6 +1639,21 @@ fn select_debuginfo(
}
}

crate fn parse_assert_incr_state(
opt_assertion: &Option<String>,
error_format: ErrorOutputType,
) -> Option<IncrementalStateAssertion> {
match opt_assertion {
Some(s) if s.as_str() == "loaded" => Some(IncrementalStateAssertion::Loaded),
Some(s) if s.as_str() == "not-loaded" => Some(IncrementalStateAssertion::NotLoaded),
Some(s) => early_error(
error_format,
&format!("unexpected incremental state assertion value: {}", s),
),
None => None,
}
}

fn parse_native_lib_kind(
matches: &getopts::Matches,
kind: &str,
Expand Down Expand Up @@ -2015,6 +2043,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {

let incremental = cg.incremental.as_ref().map(PathBuf::from);

let assert_incr_state =
parse_assert_incr_state(&debugging_opts.assert_incr_state, error_format);

if debugging_opts.profile && incremental.is_some() {
early_error(
error_format,
Expand Down Expand Up @@ -2179,6 +2210,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
};

Options {
assert_incr_state,
crate_types,
optimize: opt_level,
debuginfo,
Expand Down
5 changes: 4 additions & 1 deletion compiler/rustc_session/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::early_error;
use crate::lint;
use crate::search_paths::SearchPath;
use crate::utils::NativeLib;

use rustc_target::spec::{CodeModel, LinkerFlavor, MergeFunctions, PanicStrategy, SanitizerSet};
use rustc_target::spec::{RelocModel, RelroLevel, SplitDebuginfo, TargetTriple, TlsModel};

Expand Down Expand Up @@ -150,6 +149,7 @@ top_level_options!(
/// If `Some`, enable incremental compilation, using the given
/// directory to store intermediate results.
incremental: Option<PathBuf> [UNTRACKED],
assert_incr_state: Option<IncrementalStateAssertion> [UNTRACKED],

debugging_opts: DebuggingOptions [SUBSTRUCT],
prints: Vec<PrintRequest> [UNTRACKED],
Expand Down Expand Up @@ -1046,6 +1046,9 @@ options! {
"make cfg(version) treat the current version as incomplete (default: no)"),
asm_comments: bool = (false, parse_bool, [TRACKED],
"generate comments into the assembly (may change behavior) (default: no)"),
assert_incr_state: Option<String> = (None, parse_opt_string, [UNTRACKED],
"assert that the incremental cache is in given state: \
either `loaded` or `not-loaded`."),
ast_json: bool = (false, parse_bool, [UNTRACKED],
"print the AST as JSON and halt (default: no)"),
ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_typeck/src/check/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -317,14 +317,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
.span_to_snippet(lit.span)
.unwrap_or_else(|_| "<numeric literal>".to_owned());

// If this is a floating point literal that ends with '.',
// get rid of it to stop this from becoming a member access.
let snippet = snippet.strip_suffix('.').unwrap_or(&snippet);

err.span_suggestion(
lit.span,
&format!(
"you must specify a concrete type for this numeric value, \
like `{}`",
concrete_type
),
format!("{}_{}", snippet, concrete_type),
format!("{snippet}_{concrete_type}"),
Applicability::MaybeIncorrect,
);
}
Expand Down
5 changes: 4 additions & 1 deletion library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1272,6 +1272,9 @@ impl<T, A: Allocator> Vec<T, A> {
/// The removed element is replaced by the last element of the vector.
///
/// This does not preserve ordering, but is *O*(1).
/// If you need to preserve the element order, use [`remove`] instead.
///
/// [`remove`]: Vec::remove
///
/// # Panics
///
Expand Down Expand Up @@ -1368,7 +1371,7 @@ impl<T, A: Allocator> Vec<T, A> {
/// shifting all elements after it to the left.
///
/// Note: Because this shifts over the remaining elements, it has a
/// worst-case performance of O(n). If you don't need the order of elements
/// worst-case performance of *O*(*n*). If you don't need the order of elements
/// to be preserved, use [`swap_remove`] instead.
///
/// [`swap_remove`]: Vec::swap_remove
Expand Down
1 change: 1 addition & 0 deletions library/alloc/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#![feature(const_btree_new)]
#![feature(const_default_impls)]
#![feature(const_trait_impl)]
#![feature(const_str_from_utf8)]

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
Expand Down
64 changes: 61 additions & 3 deletions library/alloc/tests/str.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::assert_matches::assert_matches;
use std::borrow::Cow;
use std::cmp::Ordering::{Equal, Greater, Less};
use std::str::{from_utf8, from_utf8_unchecked};
Expand Down Expand Up @@ -883,6 +884,33 @@ fn test_is_utf8() {
assert!(from_utf8(&[0xF4, 0x8F, 0xBF, 0xBF]).is_ok());
}

#[test]
fn test_const_is_utf8() {
const _: () = {
// deny overlong encodings
assert!(from_utf8(&[0xc0, 0x80]).is_err());
assert!(from_utf8(&[0xc0, 0xae]).is_err());
assert!(from_utf8(&[0xe0, 0x80, 0x80]).is_err());
assert!(from_utf8(&[0xe0, 0x80, 0xaf]).is_err());
assert!(from_utf8(&[0xe0, 0x81, 0x81]).is_err());
assert!(from_utf8(&[0xf0, 0x82, 0x82, 0xac]).is_err());
assert!(from_utf8(&[0xf4, 0x90, 0x80, 0x80]).is_err());

// deny surrogates
assert!(from_utf8(&[0xED, 0xA0, 0x80]).is_err());
assert!(from_utf8(&[0xED, 0xBF, 0xBF]).is_err());

assert!(from_utf8(&[0xC2, 0x80]).is_ok());
assert!(from_utf8(&[0xDF, 0xBF]).is_ok());
assert!(from_utf8(&[0xE0, 0xA0, 0x80]).is_ok());
assert!(from_utf8(&[0xED, 0x9F, 0xBF]).is_ok());
assert!(from_utf8(&[0xEE, 0x80, 0x80]).is_ok());
assert!(from_utf8(&[0xEF, 0xBF, 0xBF]).is_ok());
assert!(from_utf8(&[0xF0, 0x90, 0x80, 0x80]).is_ok());
assert!(from_utf8(&[0xF4, 0x8F, 0xBF, 0xBF]).is_ok());
};
}

#[test]
fn from_utf8_mostly_ascii() {
// deny invalid bytes embedded in long stretches of ascii
Expand All @@ -895,13 +923,43 @@ fn from_utf8_mostly_ascii() {
}
}

#[test]
fn const_from_utf8_mostly_ascii() {
const _: () = {
// deny invalid bytes embedded in long stretches of ascii
let mut i = 32;
while i < 64 {
let mut data = [0; 128];
data[i] = 0xC0;
assert!(from_utf8(&data).is_err());
data[i] = 0xC2;
assert!(from_utf8(&data).is_err());

i = i + 1;
}
};
}

#[test]
fn from_utf8_error() {
macro_rules! test {
($input: expr, $expected_valid_up_to: expr, $expected_error_len: expr) => {
($input: expr, $expected_valid_up_to:pat, $expected_error_len:pat) => {
let error = from_utf8($input).unwrap_err();
assert_eq!(error.valid_up_to(), $expected_valid_up_to);
assert_eq!(error.error_len(), $expected_error_len);
assert_matches!(error.valid_up_to(), $expected_valid_up_to);
assert_matches!(error.error_len(), $expected_error_len);

const _: () = {
match from_utf8($input) {
Err(error) => {
let valid_up_to = error.valid_up_to();
let error_len = error.error_len();

assert!(matches!(valid_up_to, $expected_valid_up_to));
assert!(matches!(error_len, $expected_error_len));
}
Ok(_) => unreachable!(),
}
};
};
}
test!(b"A\xC3\xA9 \xFF ", 4, Some(1));
Expand Down
3 changes: 3 additions & 0 deletions library/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
#![allow(explicit_outlives_requirements)]
//
// Library features for const fns:
#![feature(const_align_offset)]
#![feature(const_align_of_val)]
#![feature(const_alloc_layout)]
#![feature(const_arguments_as_str)]
Expand Down Expand Up @@ -130,6 +131,7 @@
#![feature(const_size_of_val)]
#![feature(const_slice_from_raw_parts)]
#![feature(const_slice_ptr_len)]
#![feature(const_str_from_utf8_unchecked_mut)]
#![feature(const_swap)]
#![feature(const_trait_impl)]
#![feature(const_type_id)]
Expand All @@ -138,6 +140,7 @@
#![feature(duration_consts_2)]
#![feature(ptr_metadata)]
#![feature(slice_ptr_get)]
#![feature(str_internals)]
#![feature(variant_count)]
#![feature(const_array_from_ref)]
#![feature(const_slice_from_ref)]
Expand Down
31 changes: 22 additions & 9 deletions library/core/src/str/converts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,16 @@ use super::Utf8Error;
/// assert_eq!("💖", sparkle_heart);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
run_utf8_validation(v)?;
// SAFETY: Just ran validation.
Ok(unsafe { from_utf8_unchecked(v) })
#[rustc_const_unstable(feature = "const_str_from_utf8", issue = "91006")]
pub const fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
// This should use `?` again, once it's `const`
match run_utf8_validation(v) {
Ok(_) => {
// SAFETY: validation succeeded.
Ok(unsafe { from_utf8_unchecked(v) })
}
Err(err) => Err(err),
}
}

/// Converts a mutable slice of bytes to a mutable string slice.
Expand Down Expand Up @@ -119,10 +125,16 @@ pub fn from_utf8(v: &[u8]) -> Result<&str, Utf8Error> {
/// See the docs for [`Utf8Error`] for more details on the kinds of
/// errors that can be returned.
#[stable(feature = "str_mut_extras", since = "1.20.0")]
pub fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
run_utf8_validation(v)?;
// SAFETY: Just ran validation.
Ok(unsafe { from_utf8_unchecked_mut(v) })
#[rustc_const_unstable(feature = "const_str_from_utf8", issue = "91006")]
pub const fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> {
// This should use `?` again, once it's `const`
match run_utf8_validation(v) {
Ok(_) => {
// SAFETY: validation succeeded.
Ok(unsafe { from_utf8_unchecked_mut(v) })
}
Err(err) => Err(err),
}
}

/// Converts a slice of bytes to a string slice without checking
Expand Down Expand Up @@ -184,7 +196,8 @@ pub const unsafe fn from_utf8_unchecked(v: &[u8]) -> &str {
#[inline]
#[must_use]
#[stable(feature = "str_mut_extras", since = "1.20.0")]
pub unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
#[rustc_const_unstable(feature = "const_str_from_utf8_unchecked_mut", issue = "91005")]
pub const unsafe fn from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str {
// SAFETY: the caller must guarantee that the bytes `v`
// are valid UTF-8, thus the cast to `*mut str` is safe.
// Also, the pointer dereference is safe because that pointer
Expand Down
12 changes: 9 additions & 3 deletions library/core/src/str/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,10 @@ impl Utf8Error {
/// assert_eq!(1, error.valid_up_to());
/// ```
#[stable(feature = "utf8_error", since = "1.5.0")]
#[rustc_const_unstable(feature = "const_str_from_utf8", issue = "91006")]
#[must_use]
#[inline]
pub fn valid_up_to(&self) -> usize {
pub const fn valid_up_to(&self) -> usize {
self.valid_up_to
}

Expand All @@ -94,10 +95,15 @@ impl Utf8Error {
///
/// [U+FFFD]: ../../std/char/constant.REPLACEMENT_CHARACTER.html
#[stable(feature = "utf8_error_error_len", since = "1.20.0")]
#[rustc_const_unstable(feature = "const_str_from_utf8", issue = "91006")]
#[must_use]
#[inline]
pub fn error_len(&self) -> Option<usize> {
self.error_len.map(|len| len as usize)
pub const fn error_len(&self) -> Option<usize> {
// This should become `map` again, once it's `const`
match self.error_len {
Some(len) => Some(len as usize),
None => None,
}
}
}

Expand Down
Loading