1
Fork 0

Auto merge of #91962 - matthiaskrgr:rollup-2g082jw, r=matthiaskrgr

Rollup of 7 pull requests

Successful merges:

 - #91880 (fix clippy::single_char_pattern perf findings)
 - #91885 (Remove `in_band_lifetimes` from `rustc_codegen_ssa`)
 - #91898 (Make `TyS::is_suggestable` check for non-suggestable types structually)
 - #91915 (Add another regression test for unnormalized fn args with Self)
 - #91916 (Fix a bunch of typos)
 - #91918 (Constify `bool::then{,_some}`)
 - #91920 (Use `tcx.def_path_hash` in `ExistentialPredicate.stable_cmp`)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
This commit is contained in:
bors 2021-12-15 12:41:42 +00:00
commit c5ecc15704
92 changed files with 283 additions and 210 deletions

View file

@ -2226,8 +2226,8 @@ fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>(
continue; continue;
} }
let canonical = f.replace("-", "_"); let canonical = f.replace('-', "_");
let canonical_name = name.replace("-", "_"); let canonical_name = name.replace('-', "_");
let is_rust_object = let is_rust_object =
canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f); canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f);

View file

@ -154,7 +154,7 @@ fn is_reachable_non_generic_provider_extern(tcx: TyCtxt<'_>, def_id: DefId) -> b
tcx.reachable_non_generics(def_id.krate).contains_key(&def_id) tcx.reachable_non_generics(def_id.krate).contains_key(&def_id)
} }
fn exported_symbols_provider_local( fn exported_symbols_provider_local<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
cnum: CrateNum, cnum: CrateNum,
) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportLevel)] { ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportLevel)] {

View file

@ -486,7 +486,7 @@ fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
pub fn codegen_crate<B: ExtraBackendMethods>( pub fn codegen_crate<B: ExtraBackendMethods>(
backend: B, backend: B,
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'_>,
target_cpu: String, target_cpu: String,
metadata: EncodedMetadata, metadata: EncodedMetadata,
need_metadata_module: bool, need_metadata_module: bool,

View file

@ -150,9 +150,9 @@ impl<'tcx> FunctionCoverage<'tcx> {
/// Generate an array of CounterExpressions, and an iterator over all `Counter`s and their /// Generate an array of CounterExpressions, and an iterator over all `Counter`s and their
/// associated `Regions` (from which the LLVM-specific `CoverageMapGenerator` will create /// associated `Regions` (from which the LLVM-specific `CoverageMapGenerator` will create
/// `CounterMappingRegion`s. /// `CounterMappingRegion`s.
pub fn get_expressions_and_counter_regions<'a>( pub fn get_expressions_and_counter_regions(
&'a self, &self,
) -> (Vec<CounterExpression>, impl Iterator<Item = (Counter, &'a CodeRegion)>) { ) -> (Vec<CounterExpression>, impl Iterator<Item = (Counter, &CodeRegion)>) {
assert!( assert!(
self.source_hash != 0 || !self.is_used, self.source_hash != 0 || !self.is_used,
"No counters provided the source_hash for used function: {:?}", "No counters provided the source_hash for used function: {:?}",
@ -168,7 +168,7 @@ impl<'tcx> FunctionCoverage<'tcx> {
(counter_expressions, counter_regions) (counter_expressions, counter_regions)
} }
fn counter_regions<'a>(&'a self) -> impl Iterator<Item = (Counter, &'a CodeRegion)> { fn counter_regions(&self) -> impl Iterator<Item = (Counter, &CodeRegion)> {
self.counters.iter_enumerated().filter_map(|(index, entry)| { self.counters.iter_enumerated().filter_map(|(index, entry)| {
// Option::map() will return None to filter out missing counters. This may happen // Option::map() will return None to filter out missing counters. This may happen
// if, for example, a MIR-instrumented counter is removed during an optimization. // if, for example, a MIR-instrumented counter is removed during an optimization.
@ -177,8 +177,8 @@ impl<'tcx> FunctionCoverage<'tcx> {
} }
fn expressions_with_regions( fn expressions_with_regions(
&'a self, &self,
) -> (Vec<CounterExpression>, impl Iterator<Item = (Counter, &'a CodeRegion)>) { ) -> (Vec<CounterExpression>, impl Iterator<Item = (Counter, &CodeRegion)>) {
let mut counter_expressions = Vec::with_capacity(self.expressions.len()); let mut counter_expressions = Vec::with_capacity(self.expressions.len());
let mut expression_regions = Vec::with_capacity(self.expressions.len()); let mut expression_regions = Vec::with_capacity(self.expressions.len());
let mut new_indexes = IndexVec::from_elem_n(None, self.expressions.len()); let mut new_indexes = IndexVec::from_elem_n(None, self.expressions.len());
@ -336,7 +336,7 @@ impl<'tcx> FunctionCoverage<'tcx> {
(counter_expressions, expression_regions.into_iter()) (counter_expressions, expression_regions.into_iter())
} }
fn unreachable_regions<'a>(&'a self) -> impl Iterator<Item = (Counter, &'a CodeRegion)> { fn unreachable_regions(&self) -> impl Iterator<Item = (Counter, &CodeRegion)> {
self.unreachable_regions.iter().map(|region| (Counter::zero(), region)) self.unreachable_regions.iter().map(|region| (Counter::zero(), region))
} }

View file

@ -376,7 +376,7 @@ fn push_debuginfo_type_name<'tcx>(
// format (natvis) is able to understand enums and render the active variant correctly in the // format (natvis) is able to understand enums and render the active variant correctly in the
// debugger. For more information, look in `src/etc/natvis/intrinsic.natvis` and // debugger. For more information, look in `src/etc/natvis/intrinsic.natvis` and
// `EnumMemberDescriptionFactor::create_member_descriptions`. // `EnumMemberDescriptionFactor::create_member_descriptions`.
fn msvc_enum_fallback( fn msvc_enum_fallback<'tcx>(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
ty: Ty<'tcx>, ty: Ty<'tcx>,
def: &AdtDef, def: &AdtDef,
@ -496,7 +496,7 @@ pub fn compute_debuginfo_vtable_name<'tcx>(
vtable_name vtable_name
} }
pub fn push_item_name(tcx: TyCtxt<'tcx>, def_id: DefId, qualified: bool, output: &mut String) { pub fn push_item_name(tcx: TyCtxt<'_>, def_id: DefId, qualified: bool, output: &mut String) {
let def_key = tcx.def_key(def_id); let def_key = tcx.def_key(def_id);
if qualified { if qualified {
if let Some(parent) = def_key.parent { if let Some(parent) = def_key.parent {
@ -509,7 +509,7 @@ pub fn push_item_name(tcx: TyCtxt<'tcx>, def_id: DefId, qualified: bool, output:
} }
fn push_unqualified_item_name( fn push_unqualified_item_name(
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'_>,
def_id: DefId, def_id: DefId,
disambiguated_data: DisambiguatedDefPathData, disambiguated_data: DisambiguatedDefPathData,
output: &mut String, output: &mut String,

View file

@ -2,7 +2,6 @@
#![feature(bool_to_option)] #![feature(bool_to_option)]
#![feature(box_patterns)] #![feature(box_patterns)]
#![feature(try_blocks)] #![feature(try_blocks)]
#![feature(in_band_lifetimes)]
#![feature(let_else)] #![feature(let_else)]
#![feature(once_cell)] #![feature(once_cell)]
#![feature(nll)] #![feature(nll)]

View file

@ -73,7 +73,7 @@ struct LocalAnalyzer<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
locals: IndexVec<mir::Local, LocalKind>, locals: IndexVec<mir::Local, LocalKind>,
} }
impl<Bx: BuilderMethods<'a, 'tcx>> LocalAnalyzer<'mir, 'a, 'tcx, Bx> { impl<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> LocalAnalyzer<'mir, 'a, 'tcx, Bx> {
fn assign(&mut self, local: mir::Local, location: Location) { fn assign(&mut self, local: mir::Local, location: Location) {
let kind = &mut self.locals[local]; let kind = &mut self.locals[local];
match *kind { match *kind {

View file

@ -47,7 +47,7 @@ pub struct OperandRef<'tcx, V> {
pub layout: TyAndLayout<'tcx>, pub layout: TyAndLayout<'tcx>,
} }
impl<V: CodegenObject> fmt::Debug for OperandRef<'tcx, V> { impl<V: CodegenObject> fmt::Debug for OperandRef<'_, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout) write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout)
} }

View file

@ -97,7 +97,7 @@ pub trait DerivedTypeMethods<'tcx>: BaseTypeMethods<'tcx> + MiscMethods<'tcx> {
} }
} }
impl<T> DerivedTypeMethods<'tcx> for T where Self: BaseTypeMethods<'tcx> + MiscMethods<'tcx> {} impl<'tcx, T> DerivedTypeMethods<'tcx> for T where Self: BaseTypeMethods<'tcx> + MiscMethods<'tcx> {}
pub trait LayoutTypeMethods<'tcx>: Backend<'tcx> { pub trait LayoutTypeMethods<'tcx>: Backend<'tcx> {
fn backend_type(&self, layout: TyAndLayout<'tcx>) -> Self::Type; fn backend_type(&self, layout: TyAndLayout<'tcx>) -> Self::Type;
@ -135,4 +135,4 @@ pub trait ArgAbiMethods<'tcx>: HasCodegen<'tcx> {
pub trait TypeMethods<'tcx>: DerivedTypeMethods<'tcx> + LayoutTypeMethods<'tcx> {} pub trait TypeMethods<'tcx>: DerivedTypeMethods<'tcx> + LayoutTypeMethods<'tcx> {}
impl<T> TypeMethods<'tcx> for T where Self: DerivedTypeMethods<'tcx> + LayoutTypeMethods<'tcx> {} impl<'tcx, T> TypeMethods<'tcx> for T where Self: DerivedTypeMethods<'tcx> + LayoutTypeMethods<'tcx> {}

View file

@ -872,7 +872,7 @@ Available lint options:
let print_lints = |lints: Vec<&Lint>| { let print_lints = |lints: Vec<&Lint>| {
for lint in lints { for lint in lints {
let name = lint.name_lower().replace("_", "-"); let name = lint.name_lower().replace('_', "-");
println!( println!(
" {} {:7.7} {}", " {} {:7.7} {}",
padded(&name), padded(&name),
@ -908,10 +908,10 @@ Available lint options:
let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>| { let print_lint_groups = |lints: Vec<(&'static str, Vec<LintId>)>| {
for (name, to) in lints { for (name, to) in lints {
let name = name.to_lowercase().replace("_", "-"); let name = name.to_lowercase().replace('_', "-");
let desc = to let desc = to
.into_iter() .into_iter()
.map(|x| x.to_string().replace("_", "-")) .map(|x| x.to_string().replace('_', "-"))
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", "); .join(", ");
println!(" {} {}", padded(&name), desc); println!(" {} {}", padded(&name), desc);
@ -960,7 +960,7 @@ fn print_flag_list<T>(
println!( println!(
" {} {:>width$}=val -- {}", " {} {:>width$}=val -- {}",
cmdline_opt, cmdline_opt,
name.replace("_", "-"), name.replace('_', "-"),
desc, desc,
width = max_len width = max_len
); );
@ -1015,7 +1015,7 @@ pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
.iter() .iter()
.map(|&(name, ..)| ('C', name)) .map(|&(name, ..)| ('C', name))
.chain(DB_OPTIONS.iter().map(|&(name, ..)| ('Z', name))) .chain(DB_OPTIONS.iter().map(|&(name, ..)| ('Z', name)))
.find(|&(_, name)| *opt == name.replace("_", "-")) .find(|&(_, name)| *opt == name.replace('_', "-"))
.map(|(flag, _)| format!("{}. Did you mean `-{} {}`?", e, flag, opt)), .map(|(flag, _)| format!("{}. Did you mean `-{} {}`?", e, flag, opt)),
_ => None, _ => None,
}; };

View file

@ -472,7 +472,7 @@ pub trait Labeller<'a> {
/// Escape tags in such a way that it is suitable for inclusion in a /// Escape tags in such a way that it is suitable for inclusion in a
/// Graphviz HTML label. /// Graphviz HTML label.
pub fn escape_html(s: &str) -> String { pub fn escape_html(s: &str) -> String {
s.replace("&", "&amp;").replace("\"", "&quot;").replace("<", "&lt;").replace(">", "&gt;") s.replace('&', "&amp;").replace('\"', "&quot;").replace('<', "&lt;").replace('>', "&gt;")
} }
impl<'a> LabelText<'a> { impl<'a> LabelText<'a> {

View file

@ -584,7 +584,7 @@ fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option<PathBuf> {
fn escape_dep_filename(filename: &str) -> String { fn escape_dep_filename(filename: &str) -> String {
// Apparently clang and gcc *only* escape spaces: // Apparently clang and gcc *only* escape spaces:
// https://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4 // https://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
filename.replace(" ", "\\ ") filename.replace(' ', "\\ ")
} }
// Makefile comments only need escaping newlines and `\`. // Makefile comments only need escaping newlines and `\`.

View file

@ -295,7 +295,7 @@ pub fn struct_lint_level<'s, 'd>(
Level::Allow => "-A", Level::Allow => "-A",
Level::ForceWarn => "--force-warn", Level::ForceWarn => "--force-warn",
}; };
let hyphen_case_lint_name = name.replace("_", "-"); let hyphen_case_lint_name = name.replace('_', "-");
if lint_flag_val.as_str() == name { if lint_flag_val.as_str() == name {
sess.diag_note_once( sess.diag_note_once(
&mut err, &mut err,
@ -306,7 +306,7 @@ pub fn struct_lint_level<'s, 'd>(
), ),
); );
} else { } else {
let hyphen_case_flag_val = lint_flag_val.as_str().replace("_", "-"); let hyphen_case_flag_val = lint_flag_val.as_str().replace('_', "-");
sess.diag_note_once( sess.diag_note_once(
&mut err, &mut err,
DiagnosticMessageId::from(lint), DiagnosticMessageId::from(lint),

View file

@ -126,7 +126,7 @@ impl<
write!( write!(
w, w,
r#"<tr><td align="left" balign="left">{}</td></tr>"#, r#"<tr><td align="left" balign="left">{}</td></tr>"#,
dot::escape_html(&section).replace("\n", "<br/>") dot::escape_html(&section).replace('\n', "<br/>")
)?; )?;
} }
@ -147,7 +147,7 @@ impl<
let src = self.node(source); let src = self.node(source);
let trg = self.node(target); let trg = self.node(target);
let escaped_edge_label = if let Some(edge_label) = edge_labels.get(index) { let escaped_edge_label = if let Some(edge_label) = edge_labels.get(index) {
dot::escape_html(edge_label).replace("\n", r#"<br align="left"/>"#) dot::escape_html(edge_label).replace('\n', r#"<br align="left"/>"#)
} else { } else {
"".to_owned() "".to_owned()
}; };

View file

@ -681,13 +681,13 @@ fn hir_body<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Option<&'tcx rustc_hir::B
} }
fn escape_html(s: &str) -> String { fn escape_html(s: &str) -> String {
s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;") s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;")
} }
fn escape_attr(s: &str) -> String { fn escape_attr(s: &str) -> String {
s.replace("&", "&amp;") s.replace('&', "&amp;")
.replace("\"", "&quot;") .replace('\"', "&quot;")
.replace("'", "&#39;") .replace('\'', "&#39;")
.replace("<", "&lt;") .replace('<', "&lt;")
.replace(">", "&gt;") .replace('>', "&gt;")
} }

View file

@ -1,7 +1,12 @@
//! Diagnostics related methods for `TyS`. //! Diagnostics related methods for `TyS`.
use crate::ty::subst::{GenericArg, GenericArgKind};
use crate::ty::TyKind::*; use crate::ty::TyKind::*;
use crate::ty::{InferTy, TyCtxt, TyS}; use crate::ty::{
ConstKind, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, InferTy,
ProjectionTy, TyCtxt, TyS, TypeAndMut,
};
use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_errors::{Applicability, DiagnosticBuilder};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
@ -63,16 +68,55 @@ impl<'tcx> TyS<'tcx> {
/// Whether the type can be safely suggested during error recovery. /// Whether the type can be safely suggested during error recovery.
pub fn is_suggestable(&self) -> bool { pub fn is_suggestable(&self) -> bool {
!matches!( fn generic_arg_is_suggestible(arg: GenericArg<'_>) -> bool {
self.kind(), match arg.unpack() {
GenericArgKind::Type(ty) => ty.is_suggestable(),
GenericArgKind::Const(c) => const_is_suggestable(c.val),
_ => true,
}
}
fn const_is_suggestable(kind: ConstKind<'_>) -> bool {
match kind {
ConstKind::Infer(..)
| ConstKind::Bound(..)
| ConstKind::Placeholder(..)
| ConstKind::Error(..) => false,
_ => true,
}
}
// FIXME(compiler-errors): Some types are still not good to suggest,
// specifically references with lifetimes within the function. Not
//sure we have enough information to resolve whether a region is
// temporary, so I'll leave this as a fixme.
match self.kind() {
Opaque(..) Opaque(..)
| FnDef(..) | FnDef(..)
| FnPtr(..)
| Dynamic(..)
| Closure(..) | Closure(..)
| Infer(..) | Infer(..)
| Projection(..) | Generator(..)
) | GeneratorWitness(..)
| Bound(_, _)
| Placeholder(_)
| Error(_) => false,
Dynamic(dty, _) => dty.iter().all(|pred| match pred.skip_binder() {
ExistentialPredicate::Trait(ExistentialTraitRef { substs, .. }) => {
substs.iter().all(generic_arg_is_suggestible)
}
ExistentialPredicate::Projection(ExistentialProjection { substs, ty, .. }) => {
ty.is_suggestable() && substs.iter().all(generic_arg_is_suggestible)
}
_ => true,
}),
Projection(ProjectionTy { substs: args, .. }) | Adt(_, args) | Tuple(args) => {
args.iter().all(generic_arg_is_suggestible)
}
Slice(ty) | RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => ty.is_suggestable(),
Array(ty, c) => ty.is_suggestable() && const_is_suggestable(c.val),
_ => true,
}
} }
} }

View file

@ -787,7 +787,7 @@ impl<'tcx> ExistentialPredicate<'tcx> {
tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)) tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id))
} }
(AutoTrait(ref a), AutoTrait(ref b)) => { (AutoTrait(ref a), AutoTrait(ref b)) => {
tcx.trait_def(*a).def_path_hash.cmp(&tcx.trait_def(*b).def_path_hash) tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b))
} }
(Trait(_), _) => Ordering::Less, (Trait(_), _) => Ordering::Less,
(Projection(_), Trait(_)) => Ordering::Greater, (Projection(_), Trait(_)) => Ordering::Greater,

View file

@ -148,7 +148,7 @@ impl DebugOptions {
let mut counter_format = ExpressionFormat::default(); let mut counter_format = ExpressionFormat::default();
if let Ok(env_debug_options) = std::env::var(RUSTC_COVERAGE_DEBUG_OPTIONS) { if let Ok(env_debug_options) = std::env::var(RUSTC_COVERAGE_DEBUG_OPTIONS) {
for setting_str in env_debug_options.replace(" ", "").replace("-", "_").split(',') { for setting_str in env_debug_options.replace(' ', "").replace('-', "_").split(',') {
let (option, value) = match setting_str.split_once('=') { let (option, value) = match setting_str.split_once('=') {
None => (setting_str, None), None => (setting_str, None),
Some((k, v)) => (k, Some(v)), Some((k, v)) => (k, Some(v)),

View file

@ -155,7 +155,7 @@ impl CoverageSpan {
format!( format!(
"{}\n {}", "{}\n {}",
source_range_no_file(tcx, &self.span), source_range_no_file(tcx, &self.span),
self.format_coverage_statements(tcx, mir_body).replace("\n", "\n "), self.format_coverage_statements(tcx, mir_body).replace('\n', "\n "),
) )
} }

View file

@ -2236,7 +2236,7 @@ impl<'a> Parser<'a> {
err.span_suggestion( err.span_suggestion(
seq_span, seq_span,
"...or a vertical bar to match on multiple alternatives", "...or a vertical bar to match on multiple alternatives",
seq_snippet.replace(",", " |"), seq_snippet.replace(',', " |"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} }

View file

@ -1036,7 +1036,7 @@ fn find_config(supplied: Option<Config>) -> Config {
// Helper function to escape quotes in a string // Helper function to escape quotes in a string
fn escape(s: String) -> String { fn escape(s: String) -> String {
s.replace("\"", "\"\"") s.replace('\"', "\"\"")
} }
// Helper function to determine if a span came from a // Helper function to determine if a span came from a

View file

@ -1213,7 +1213,7 @@ pub fn get_cmd_lint_options(
if lint_name == "help" { if lint_name == "help" {
describe_lints = true; describe_lints = true;
} else { } else {
lint_opts_with_position.push((arg_pos, lint_name.replace("-", "_"), level)); lint_opts_with_position.push((arg_pos, lint_name.replace('-', "_"), level));
} }
} }
} }

View file

@ -335,7 +335,7 @@ fn build_options<O: Default>(
Some((k, v)) => (k.to_string(), Some(v)), Some((k, v)) => (k.to_string(), Some(v)),
}; };
let option_to_lookup = key.replace("-", "_"); let option_to_lookup = key.replace('-', "_");
match descrs.iter().find(|(name, ..)| *name == option_to_lookup) { match descrs.iter().find(|(name, ..)| *name == option_to_lookup) {
Some((_, setter, type_desc, _)) => { Some((_, setter, type_desc, _)) => {
if !setter(&mut op, value) { if !setter(&mut op, value) {

View file

@ -85,7 +85,7 @@ pub fn find_crate_name(sess: &Session, attrs: &[ast::Attribute], input: &Input)
); );
sess.err(&msg); sess.err(&msg);
} else { } else {
return validate(s.replace("-", "_"), None); return validate(s.replace('-', "_"), None);
} }
} }
} }

View file

@ -747,7 +747,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
let msg = format!( let msg = format!(
"the trait bound `{}: {}` is not satisfied", "the trait bound `{}: {}` is not satisfied",
orig_ty.to_string(), orig_ty,
old_ref.print_only_trait_path(), old_ref.print_only_trait_path(),
); );
if has_custom_message { if has_custom_message {

View file

@ -3,7 +3,7 @@ use std::mem::MaybeUninit;
use std::ptr::NonNull; use std::ptr::NonNull;
#[test] #[test]
fn unitialized_zero_size_box() { fn uninitialized_zero_size_box() {
assert_eq!( assert_eq!(
&*Box::<()>::new_uninit() as *const _, &*Box::<()>::new_uninit() as *const _,
NonNull::<MaybeUninit<()>>::dangling().as_ptr(), NonNull::<MaybeUninit<()>>::dangling().as_ptr(),

View file

@ -162,7 +162,7 @@ fn test_join_for_different_lengths_with_long_separator() {
} }
#[test] #[test]
fn test_join_isue_80335() { fn test_join_issue_80335() {
use core::{borrow::Borrow, cell::Cell}; use core::{borrow::Borrow, cell::Cell};
struct WeirdBorrow { struct WeirdBorrow {

View file

@ -157,11 +157,11 @@ impl Layout {
/// ///
/// - If `T` is `Sized`, this function is always safe to call. /// - If `T` is `Sized`, this function is always safe to call.
/// - If the unsized tail of `T` is: /// - If the unsized tail of `T` is:
/// - a [slice], then the length of the slice tail must be an intialized /// - a [slice], then the length of the slice tail must be an initialized
/// integer, and the size of the *entire value* /// integer, and the size of the *entire value*
/// (dynamic tail length + statically sized prefix) must fit in `isize`. /// (dynamic tail length + statically sized prefix) must fit in `isize`.
/// - a [trait object], then the vtable part of the pointer must point /// - a [trait object], then the vtable part of the pointer must point
/// to a valid vtable for the type `T` acquired by an unsizing coersion, /// to a valid vtable for the type `T` acquired by an unsizing coercion,
/// and the size of the *entire value* /// and the size of the *entire value*
/// (dynamic tail length + statically sized prefix) must fit in `isize`. /// (dynamic tail length + statically sized prefix) must fit in `isize`.
/// - an (unstable) [extern type], then this function is always safe to /// - an (unstable) [extern type], then this function is always safe to

View file

@ -14,8 +14,12 @@ impl bool {
/// assert_eq!(true.then_some(0), Some(0)); /// assert_eq!(true.then_some(0), Some(0));
/// ``` /// ```
#[unstable(feature = "bool_to_option", issue = "80967")] #[unstable(feature = "bool_to_option", issue = "80967")]
#[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
#[inline] #[inline]
pub fn then_some<T>(self, t: T) -> Option<T> { pub const fn then_some<T>(self, t: T) -> Option<T>
where
T: ~const Drop,
{
if self { Some(t) } else { None } if self { Some(t) } else { None }
} }
@ -29,8 +33,13 @@ impl bool {
/// assert_eq!(true.then(|| 0), Some(0)); /// assert_eq!(true.then(|| 0), Some(0));
/// ``` /// ```
#[stable(feature = "lazy_bool_to_option", since = "1.50.0")] #[stable(feature = "lazy_bool_to_option", since = "1.50.0")]
#[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")]
#[inline] #[inline]
pub fn then<T, F: FnOnce() -> T>(self, f: F) -> Option<T> { pub const fn then<T, F>(self, f: F) -> Option<T>
where
F: ~const FnOnce() -> T,
F: ~const Drop,
{
if self { Some(f()) } else { None } if self { Some(f()) } else { None }
} }
} }

View file

@ -898,7 +898,7 @@ impl<T: ?Sized> RefCell<T> {
Ok(Ref { value: unsafe { &*self.value.get() }, borrow: b }) Ok(Ref { value: unsafe { &*self.value.get() }, borrow: b })
} }
None => Err(BorrowError { None => Err(BorrowError {
// If a borrow occured, then we must already have an outstanding borrow, // If a borrow occurred, then we must already have an outstanding borrow,
// so `borrowed_at` will be `Some` // so `borrowed_at` will be `Some`
#[cfg(feature = "debug_refcell")] #[cfg(feature = "debug_refcell")]
location: self.borrowed_at.get().unwrap(), location: self.borrowed_at.get().unwrap(),
@ -983,7 +983,7 @@ impl<T: ?Sized> RefCell<T> {
Ok(RefMut { value: unsafe { &mut *self.value.get() }, borrow: b }) Ok(RefMut { value: unsafe { &mut *self.value.get() }, borrow: b })
} }
None => Err(BorrowMutError { None => Err(BorrowMutError {
// If a borrow occured, then we must already have an outstanding borrow, // If a borrow occurred, then we must already have an outstanding borrow,
// so `borrowed_at` will be `Some` // so `borrowed_at` will be `Some`
#[cfg(feature = "debug_refcell")] #[cfg(feature = "debug_refcell")]
location: self.borrowed_at.get().unwrap(), location: self.borrowed_at.get().unwrap(),
@ -1104,7 +1104,7 @@ impl<T: ?Sized> RefCell<T> {
Ok(unsafe { &*self.value.get() }) Ok(unsafe { &*self.value.get() })
} else { } else {
Err(BorrowError { Err(BorrowError {
// If a borrow occured, then we must already have an outstanding borrow, // If a borrow occurred, then we must already have an outstanding borrow,
// so `borrowed_at` will be `Some` // so `borrowed_at` will be `Some`
#[cfg(feature = "debug_refcell")] #[cfg(feature = "debug_refcell")]
location: self.borrowed_at.get().unwrap(), location: self.borrowed_at.get().unwrap(),

View file

@ -516,7 +516,7 @@ impl<A: Debug + TrustedRandomAccessNoCoerce, B: Debug + TrustedRandomAccessNoCoe
/// * It must also be safe to drop `self` after calling `self.__iterator_get_unchecked(idx)`. /// * It must also be safe to drop `self` after calling `self.__iterator_get_unchecked(idx)`.
/// * If `T` is a subtype of `Self`, then it must be safe to coerce `self` to `T`. /// * If `T` is a subtype of `Self`, then it must be safe to coerce `self` to `T`.
// //
// FIXME: Clarify interaction with SourceIter/InPlaceIterable. Calling `SouceIter::as_inner` // FIXME: Clarify interaction with SourceIter/InPlaceIterable. Calling `SourceIter::as_inner`
// after `__iterator_get_unchecked` is supposed to be allowed. // after `__iterator_get_unchecked` is supposed to be allowed.
#[doc(hidden)] #[doc(hidden)]
#[unstable(feature = "trusted_random_access", issue = "none")] #[unstable(feature = "trusted_random_access", issue = "none")]

View file

@ -777,7 +777,7 @@ range_exact_iter_impl! {
usize u8 u16 usize u8 u16
isize i8 i16 isize i8 i16
// These are incorect per the reasoning above, // These are incorrect per the reasoning above,
// but removing them would be a breaking change as they were stabilized in Rust 1.0.0. // but removing them would be a breaking change as they were stabilized in Rust 1.0.0.
// So e.g. `(0..66_000_u32).len()` for example will compile without error or warnings // So e.g. `(0..66_000_u32).len()` for example will compile without error or warnings
// on 16-bit platforms, but continue to give a wrong result. // on 16-bit platforms, but continue to give a wrong result.
@ -805,7 +805,7 @@ range_incl_exact_iter_impl! {
u8 u8
i8 i8
// These are incorect per the reasoning above, // These are incorrect per the reasoning above,
// but removing them would be a breaking change as they were stabilized in Rust 1.26.0. // but removing them would be a breaking change as they were stabilized in Rust 1.26.0.
// So e.g. `(0..=u16::MAX).len()` for example will compile without error or warnings // So e.g. `(0..=u16::MAX).len()` for example will compile without error or warnings
// on 16-bit platforms, but continue to give a wrong result. // on 16-bit platforms, but continue to give a wrong result.

View file

@ -40,7 +40,7 @@ impl Number {
&& !self.many_digits && !self.many_digits
} }
/// The fast path algorithmn using machine-sized integers and floats. /// The fast path algorithm using machine-sized integers and floats.
/// ///
/// This is extracted into a separate function so that it can be attempted before constructing /// This is extracted into a separate function so that it can be attempted before constructing
/// a Decimal. This only works if both the mantissa and the exponent /// a Decimal. This only works if both the mantissa and the exponent

View file

@ -1,4 +1,4 @@
//! Shared utilties used by both float and integer formatting. //! Shared utilities used by both float and integer formatting.
#![doc(hidden)] #![doc(hidden)]
#![unstable( #![unstable(
feature = "numfmt", feature = "numfmt",

View file

@ -221,7 +221,7 @@ impl<'a, T> IterMut<'a, T> {
// the length, to also allows for the fast `ptr == end` check. // the length, to also allows for the fast `ptr == end` check.
// //
// See the `next_unchecked!` and `is_empty!` macros as well as the // See the `next_unchecked!` and `is_empty!` macros as well as the
// `post_inc_start` method for more informations. // `post_inc_start` method for more information.
unsafe { unsafe {
assume(!ptr.is_null()); assume(!ptr.is_null());

View file

@ -104,7 +104,7 @@ pub unsafe fn ptr_rotate<T>(mut left: usize, mut mid: *mut T, mut right: usize)
// - overflows cannot happen for `i` since the function's safety contract ask for // - overflows cannot happen for `i` since the function's safety contract ask for
// `mid+right-1 = x+left+right` to be valid for writing // `mid+right-1 = x+left+right` to be valid for writing
// - underflows cannot happen because `i` must be bigger or equal to `left` for // - underflows cannot happen because `i` must be bigger or equal to `left` for
// a substraction of `left` to happen. // a subtraction of `left` to happen.
// //
// So `x+i` is valid for reading and writing if the caller respected the contract // So `x+i` is valid for reading and writing if the caller respected the contract
tmp = unsafe { x.add(i).replace(tmp) }; tmp = unsafe { x.add(i).replace(tmp) };
@ -202,7 +202,7 @@ pub unsafe fn ptr_rotate<T>(mut left: usize, mut mid: *mut T, mut right: usize)
loop { loop {
// SAFETY: // SAFETY:
// `left >= right` so `[mid-right, mid+right)` is valid for reading and writing // `left >= right` so `[mid-right, mid+right)` is valid for reading and writing
// Substracting `right` from `mid` each turn is counterbalanced by the addition and // Subtracting `right` from `mid` each turn is counterbalanced by the addition and
// check after it. // check after it.
unsafe { unsafe {
ptr::swap_nonoverlapping(mid.sub(right), mid, right); ptr::swap_nonoverlapping(mid.sub(right), mid, right);
@ -218,7 +218,7 @@ pub unsafe fn ptr_rotate<T>(mut left: usize, mut mid: *mut T, mut right: usize)
loop { loop {
// SAFETY: `[mid-left, mid+left)` is valid for reading and writing because // SAFETY: `[mid-left, mid+left)` is valid for reading and writing because
// `left < right` so `mid+left < mid+right`. // `left < right` so `mid+left < mid+right`.
// Adding `left` to `mid` each turn is counterbalanced by the substraction and check // Adding `left` to `mid` each turn is counterbalanced by the subtraction and check
// after it. // after it.
unsafe { unsafe {
ptr::swap_nonoverlapping(mid.sub(left), mid, left); ptr::swap_nonoverlapping(mid.sub(left), mid, left);

View file

@ -748,7 +748,7 @@ generate_pattern_iterators! {
} }
impl<'a, P: Pattern<'a>> Split<'a, P> { impl<'a, P: Pattern<'a>> Split<'a, P> {
/// Returns remainder of the splitted string /// Returns remainder of the split string
/// ///
/// # Examples /// # Examples
/// ///
@ -769,7 +769,7 @@ impl<'a, P: Pattern<'a>> Split<'a, P> {
} }
impl<'a, P: Pattern<'a>> RSplit<'a, P> { impl<'a, P: Pattern<'a>> RSplit<'a, P> {
/// Returns remainder of the splitted string /// Returns remainder of the split string
/// ///
/// # Examples /// # Examples
/// ///
@ -808,7 +808,7 @@ generate_pattern_iterators! {
} }
impl<'a, P: Pattern<'a>> SplitTerminator<'a, P> { impl<'a, P: Pattern<'a>> SplitTerminator<'a, P> {
/// Returns remainder of the splitted string /// Returns remainder of the split string
/// ///
/// # Examples /// # Examples
/// ///
@ -829,7 +829,7 @@ impl<'a, P: Pattern<'a>> SplitTerminator<'a, P> {
} }
impl<'a, P: Pattern<'a>> RSplitTerminator<'a, P> { impl<'a, P: Pattern<'a>> RSplitTerminator<'a, P> {
/// Returns remainder of the splitted string /// Returns remainder of the split string
/// ///
/// # Examples /// # Examples
/// ///
@ -931,7 +931,7 @@ generate_pattern_iterators! {
} }
impl<'a, P: Pattern<'a>> SplitN<'a, P> { impl<'a, P: Pattern<'a>> SplitN<'a, P> {
/// Returns remainder of the splitted string /// Returns remainder of the split string
/// ///
/// # Examples /// # Examples
/// ///
@ -952,7 +952,7 @@ impl<'a, P: Pattern<'a>> SplitN<'a, P> {
} }
impl<'a, P: Pattern<'a>> RSplitN<'a, P> { impl<'a, P: Pattern<'a>> RSplitN<'a, P> {
/// Returns remainder of the splitted string /// Returns remainder of the split string
/// ///
/// # Examples /// # Examples
/// ///
@ -1236,7 +1236,7 @@ impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
impl FusedIterator for SplitWhitespace<'_> {} impl FusedIterator for SplitWhitespace<'_> {}
impl<'a> SplitWhitespace<'a> { impl<'a> SplitWhitespace<'a> {
/// Returns remainder of the splitted string /// Returns remainder of the split string
/// ///
/// # Examples /// # Examples
/// ///
@ -1292,7 +1292,7 @@ impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> {
impl FusedIterator for SplitAsciiWhitespace<'_> {} impl FusedIterator for SplitAsciiWhitespace<'_> {}
impl<'a> SplitAsciiWhitespace<'a> { impl<'a> SplitAsciiWhitespace<'a> {
/// Returns remainder of the splitted string /// Returns remainder of the split string
/// ///
/// # Examples /// # Examples
/// ///
@ -1360,7 +1360,7 @@ impl<'a, P: Pattern<'a, Searcher: ReverseSearcher<'a>>> DoubleEndedIterator
impl<'a, P: Pattern<'a>> FusedIterator for SplitInclusive<'a, P> {} impl<'a, P: Pattern<'a>> FusedIterator for SplitInclusive<'a, P> {}
impl<'a, P: Pattern<'a>> SplitInclusive<'a, P> { impl<'a, P: Pattern<'a>> SplitInclusive<'a, P> {
/// Returns remainder of the splitted string /// Returns remainder of the split string
/// ///
/// # Examples /// # Examples
/// ///

View file

@ -259,7 +259,7 @@ fn iterator_drops() {
// This test does not work on targets without panic=unwind support. // This test does not work on targets without panic=unwind support.
// To work around this problem, test is marked is should_panic, so it will // To work around this problem, test is marked is should_panic, so it will
// be automagically skipped on unsuitable targets, such as // be automagically skipped on unsuitable targets, such as
// wasm32-unknown-unkown. // wasm32-unknown-unknown.
// //
// It means that we use panic for indicating success. // It means that we use panic for indicating success.
#[test] #[test]

View file

@ -88,4 +88,18 @@ fn test_bool_to_option() {
assert_eq!(true.then_some(0), Some(0)); assert_eq!(true.then_some(0), Some(0));
assert_eq!(false.then(|| 0), None); assert_eq!(false.then(|| 0), None);
assert_eq!(true.then(|| 0), Some(0)); assert_eq!(true.then(|| 0), Some(0));
const fn zero() -> i32 {
0
}
const A: Option<i32> = false.then_some(0);
const B: Option<i32> = true.then_some(0);
const C: Option<i32> = false.then(zero);
const D: Option<i32> = true.then(zero);
assert_eq!(A, None);
assert_eq!(B, Some(0));
assert_eq!(C, None);
assert_eq!(D, Some(0));
} }

View file

@ -8,6 +8,7 @@
#![feature(cfg_panic)] #![feature(cfg_panic)]
#![feature(cfg_target_has_atomic)] #![feature(cfg_target_has_atomic)]
#![feature(const_assume)] #![feature(const_assume)]
#![feature(const_bool_to_option)]
#![feature(const_cell_into_inner)] #![feature(const_cell_into_inner)]
#![feature(const_convert)] #![feature(const_convert)]
#![feature(const_maybe_uninit_as_mut_ptr)] #![feature(const_maybe_uninit_as_mut_ptr)]

View file

@ -49,7 +49,7 @@ static EXCEPTION_TYPE_INFO: TypeInfo = TypeInfo {
}; };
struct Exception { struct Exception {
// This is necessary because C++ code can capture our execption with // This is necessary because C++ code can capture our exception with
// std::exception_ptr and rethrow it multiple times, possibly even in // std::exception_ptr and rethrow it multiple times, possibly even in
// another thread. // another thread.
caught: AtomicBool, caught: AtomicBool,

View file

@ -1369,7 +1369,7 @@ fn symlink_hard_link() {
// "hard_link" should appear as a symlink. // "hard_link" should appear as a symlink.
assert!(check!(fs::symlink_metadata(tmpdir.join("hard_link"))).file_type().is_symlink()); assert!(check!(fs::symlink_metadata(tmpdir.join("hard_link"))).file_type().is_symlink());
// We sould be able to open "file" via any of the above names. // We should be able to open "file" via any of the above names.
let _ = check!(fs::File::open(tmpdir.join("file"))); let _ = check!(fs::File::open(tmpdir.join("file")));
assert!(fs::File::open(tmpdir.join("file.renamed")).is_err()); assert!(fs::File::open(tmpdir.join("file.renamed")).is_err());
let _ = check!(fs::File::open(tmpdir.join("symlink"))); let _ = check!(fs::File::open(tmpdir.join("symlink")));

View file

@ -362,7 +362,7 @@ pub(crate) fn default_read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>
let start_len = buf.len(); let start_len = buf.len();
let start_cap = buf.capacity(); let start_cap = buf.capacity();
let mut initialized = 0; // Extra initalized bytes from previous loop iteration let mut initialized = 0; // Extra initialized bytes from previous loop iteration
loop { loop {
if buf.len() == buf.capacity() { if buf.len() == buf.capacity() {
buf.reserve(32); // buf is full, need more space buf.reserve(32); // buf is full, need more space
@ -370,7 +370,7 @@ pub(crate) fn default_read_to_end<R: Read + ?Sized>(r: &mut R, buf: &mut Vec<u8>
let mut read_buf = ReadBuf::uninit(buf.spare_capacity_mut()); let mut read_buf = ReadBuf::uninit(buf.spare_capacity_mut());
// SAFETY: These bytes were initalized but not filled in the previous loop // SAFETY: These bytes were initialized but not filled in the previous loop
unsafe { unsafe {
read_buf.assume_init(initialized); read_buf.assume_init(initialized);
} }

View file

@ -1179,7 +1179,7 @@ where
}) })
}) == Ok(Some(())) }) == Ok(Some(()))
{ {
// Succesfully wrote to capture buffer. // Successfully wrote to capture buffer.
return; return;
} }

View file

@ -749,7 +749,7 @@ fn ipv4_from_constructors() {
} }
#[test] #[test]
fn ipv6_from_contructors() { fn ipv6_from_constructors() {
assert_eq!(Ipv6Addr::LOCALHOST, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); assert_eq!(Ipv6Addr::LOCALHOST, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1));
assert!(Ipv6Addr::LOCALHOST.is_loopback()); assert!(Ipv6Addr::LOCALHOST.is_loopback());
assert_eq!(Ipv6Addr::UNSPECIFIED, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)); assert_eq!(Ipv6Addr::UNSPECIFIED, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0));

View file

@ -365,7 +365,7 @@ pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>>
// The call to `intrinsics::r#try` is made safe by: // The call to `intrinsics::r#try` is made safe by:
// - `do_call`, the first argument, can be called with the initial `data_ptr`. // - `do_call`, the first argument, can be called with the initial `data_ptr`.
// - `do_catch`, the second argument, can be called with the `data_ptr` as well. // - `do_catch`, the second argument, can be called with the `data_ptr` as well.
// See their safety preconditions for more informations // See their safety preconditions for more information
unsafe { unsafe {
return if intrinsics::r#try(do_call::<F, R>, data_ptr, do_catch::<F, R>) == 0 { return if intrinsics::r#try(do_call::<F, R>, data_ptr, do_catch::<F, R>) == 0 {
Ok(ManuallyDrop::into_inner(data.r)) Ok(ManuallyDrop::into_inner(data.r))
@ -398,7 +398,7 @@ pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>>
// expects normal function pointers. // expects normal function pointers.
#[inline] #[inline]
fn do_call<F: FnOnce() -> R, R>(data: *mut u8) { fn do_call<F: FnOnce() -> R, R>(data: *mut u8) {
// SAFETY: this is the responsibilty of the caller, see above. // SAFETY: this is the responsibility of the caller, see above.
unsafe { unsafe {
let data = data as *mut Data<F, R>; let data = data as *mut Data<F, R>;
let data = &mut (*data); let data = &mut (*data);
@ -420,7 +420,7 @@ pub unsafe fn r#try<R, F: FnOnce() -> R>(f: F) -> Result<R, Box<dyn Any + Send>>
// expects normal function pointers. // expects normal function pointers.
#[inline] #[inline]
fn do_catch<F: FnOnce() -> R, R>(data: *mut u8, payload: *mut u8) { fn do_catch<F: FnOnce() -> R, R>(data: *mut u8, payload: *mut u8) {
// SAFETY: this is the responsibilty of the caller, see above. // SAFETY: this is the responsibility of the caller, see above.
// //
// When `__rustc_panic_cleaner` is correctly implemented we can rely // When `__rustc_panic_cleaner` is correctly implemented we can rely
// on `obj` being the correct thing to pass to `data.p` (after wrapping // on `obj` being the correct thing to pass to `data.p` (after wrapping

View file

@ -126,7 +126,7 @@ impl Thread {
// In this case, `inner`'s ownership has been moved to us, // In this case, `inner`'s ownership has been moved to us,
// And we are responsible for dropping it. The acquire // And we are responsible for dropping it. The acquire
// ordering is not necessary because the parent thread made // ordering is not necessary because the parent thread made
// no memory acccess needing synchronization since the call // no memory access needing synchronization since the call
// to `acre_tsk`. // to `acre_tsk`.
// Safety: See above. // Safety: See above.
let _ = unsafe { Box::from_raw(inner as *const _ as *mut ThreadInner) }; let _ = unsafe { Box::from_raw(inner as *const _ as *mut ThreadInner) };
@ -264,7 +264,7 @@ impl Drop for Thread {
// one will ever join it. // one will ever join it.
// The ownership of `self.inner` is moved to the child thread. // The ownership of `self.inner` is moved to the child thread.
// However, the release ordering is not necessary because we // However, the release ordering is not necessary because we
// made no memory acccess needing synchronization since the call // made no memory access needing synchronization since the call
// to `acre_tsk`. // to `acre_tsk`.
} }
LIFECYCLE_FINISHED => { LIFECYCLE_FINISHED => {

View file

@ -104,7 +104,7 @@ impl FdMeta {
fn potential_sendfile_source(&self) -> bool { fn potential_sendfile_source(&self) -> bool {
match self { match self {
// procfs erronously shows 0 length on non-empty readable files. // procfs erroneously shows 0 length on non-empty readable files.
// and if a file is truly empty then a `read` syscall will determine that and skip the write syscall // and if a file is truly empty then a `read` syscall will determine that and skip the write syscall
// thus there would be benefit from attempting sendfile // thus there would be benefit from attempting sendfile
FdMeta::Metadata(meta) FdMeta::Metadata(meta)

View file

@ -284,7 +284,7 @@ impl ExitStatus {
// //
// The other view would be to say that the caller on Fuchsia ought to know that `into_raw` // The other view would be to say that the caller on Fuchsia ought to know that `into_raw`
// will give a raw Fuchsia status (whatever that is - I don't know, personally). That is // will give a raw Fuchsia status (whatever that is - I don't know, personally). That is
// not possible here becaause we must return a c_int because that's what Unix (including // not possible here because we must return a c_int because that's what Unix (including
// SuS and POSIX) say a wait status is, but Fuchsia apparently uses a u64, so it won't // SuS and POSIX) say a wait status is, but Fuchsia apparently uses a u64, so it won't
// necessarily fit. // necessarily fit.
// //

View file

@ -124,7 +124,7 @@ impl<F> DlsymWeak<F> {
} }
} }
// Cold because it should only happen during first-time initalization. // Cold because it should only happen during first-time initialization.
#[cold] #[cold]
unsafe fn initialize(&self) -> Option<F> { unsafe fn initialize(&self) -> Option<F> {
assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>()); assert_eq!(mem::size_of::<F>(), mem::size_of::<usize>());

View file

@ -24,7 +24,7 @@ static mut DLMALLOC: dlmalloc::Dlmalloc = dlmalloc::Dlmalloc::new();
unsafe impl GlobalAlloc for System { unsafe impl GlobalAlloc for System {
#[inline] #[inline]
unsafe fn alloc(&self, layout: Layout) -> *mut u8 { unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
// SAFETY: DLMALLOC access is guranteed to be safe because the lock gives us unique and non-reentrant access. // SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
// Calling malloc() is safe because preconditions on this function match the trait method preconditions. // Calling malloc() is safe because preconditions on this function match the trait method preconditions.
let _lock = lock::lock(); let _lock = lock::lock();
unsafe { DLMALLOC.malloc(layout.size(), layout.align()) } unsafe { DLMALLOC.malloc(layout.size(), layout.align()) }
@ -32,7 +32,7 @@ unsafe impl GlobalAlloc for System {
#[inline] #[inline]
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
// SAFETY: DLMALLOC access is guranteed to be safe because the lock gives us unique and non-reentrant access. // SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
// Calling calloc() is safe because preconditions on this function match the trait method preconditions. // Calling calloc() is safe because preconditions on this function match the trait method preconditions.
let _lock = lock::lock(); let _lock = lock::lock();
unsafe { DLMALLOC.calloc(layout.size(), layout.align()) } unsafe { DLMALLOC.calloc(layout.size(), layout.align()) }
@ -40,7 +40,7 @@ unsafe impl GlobalAlloc for System {
#[inline] #[inline]
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
// SAFETY: DLMALLOC access is guranteed to be safe because the lock gives us unique and non-reentrant access. // SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
// Calling free() is safe because preconditions on this function match the trait method preconditions. // Calling free() is safe because preconditions on this function match the trait method preconditions.
let _lock = lock::lock(); let _lock = lock::lock();
unsafe { DLMALLOC.free(ptr, layout.size(), layout.align()) } unsafe { DLMALLOC.free(ptr, layout.size(), layout.align()) }
@ -48,7 +48,7 @@ unsafe impl GlobalAlloc for System {
#[inline] #[inline]
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
// SAFETY: DLMALLOC access is guranteed to be safe because the lock gives us unique and non-reentrant access. // SAFETY: DLMALLOC access is guaranteed to be safe because the lock gives us unique and non-reentrant access.
// Calling realloc() is safe because preconditions on this function match the trait method preconditions. // Calling realloc() is safe because preconditions on this function match the trait method preconditions.
let _lock = lock::lock(); let _lock = lock::lock();
unsafe { DLMALLOC.realloc(ptr, layout.size(), layout.align(), new_size) } unsafe { DLMALLOC.realloc(ptr, layout.size(), layout.align(), new_size) }

View file

@ -73,7 +73,7 @@ pub struct ReentrantMutex {
unsafe impl Send for ReentrantMutex {} unsafe impl Send for ReentrantMutex {}
unsafe impl Sync for ReentrantMutex {} unsafe impl Sync for ReentrantMutex {}
// Reentrant mutexes are similarly implemented to mutexs above except that // Reentrant mutexes are similarly implemented to mutexes above except that
// instead of "1" meaning unlocked we use the id of a thread to represent // instead of "1" meaning unlocked we use the id of a thread to represent
// whether it has locked a mutex. That way we have an atomic counter which // whether it has locked a mutex. That way we have an atomic counter which
// always holds the id of the thread that currently holds the lock (or 0 if the // always holds the id of the thread that currently holds the lock (or 0 if the
@ -96,7 +96,7 @@ impl ReentrantMutex {
pub unsafe fn lock(&self) { pub unsafe fn lock(&self) {
let me = thread::my_id(); let me = thread::my_id();
while let Err(owner) = self._try_lock(me) { while let Err(owner) = self._try_lock(me) {
// SAFETY: the caller must gurantee that `self.ptr()` and `owner` are valid i32. // SAFETY: the caller must guarantee that `self.ptr()` and `owner` are valid i32.
let val = unsafe { wasm32::memory_atomic_wait32(self.ptr(), owner as i32, -1) }; let val = unsafe { wasm32::memory_atomic_wait32(self.ptr(), owner as i32, -1) };
debug_assert!(val == 0 || val == 1); debug_assert!(val == 0 || val == 1);
} }
@ -136,7 +136,7 @@ impl ReentrantMutex {
match *self.recursions.get() { match *self.recursions.get() {
0 => { 0 => {
self.owner.swap(0, SeqCst); self.owner.swap(0, SeqCst);
// SAFETY: the caller must gurantee that `self.ptr()` is valid i32. // SAFETY: the caller must guarantee that `self.ptr()` is valid i32.
unsafe { unsafe {
wasm32::memory_atomic_notify(self.ptr() as *mut i32, 1); wasm32::memory_atomic_notify(self.ptr() as *mut i32, 1);
} // wake up one waiter, if any } // wake up one waiter, if any

View file

@ -124,7 +124,7 @@ fn write(
// //
// If the data is not valid UTF-8 we write out as many bytes as are valid. // If the data is not valid UTF-8 we write out as many bytes as are valid.
// If the first byte is invalid it is either first byte of a multi-byte sequence but the // If the first byte is invalid it is either first byte of a multi-byte sequence but the
// provided byte slice is too short or it is the first byte of an invalide multi-byte sequence. // provided byte slice is too short or it is the first byte of an invalid multi-byte sequence.
let len = cmp::min(data.len(), MAX_BUFFER_SIZE / 2); let len = cmp::min(data.len(), MAX_BUFFER_SIZE / 2);
let utf8 = match str::from_utf8(&data[..len]) { let utf8 = match str::from_utf8(&data[..len]) {
Ok(s) => s, Ok(s) => s,

View file

@ -22,7 +22,7 @@
// //
// Unlike WaitOnAddress, NtWaitForKeyedEvent/NtReleaseKeyedEvent operate on a // Unlike WaitOnAddress, NtWaitForKeyedEvent/NtReleaseKeyedEvent operate on a
// HANDLE (created with NtCreateKeyedEvent). This means that we can be sure // HANDLE (created with NtCreateKeyedEvent). This means that we can be sure
// a succesfully awoken park() was awoken by unpark() and not a // a successfully awoken park() was awoken by unpark() and not a
// NtReleaseKeyedEvent call from some other code, as these events are not only // NtReleaseKeyedEvent call from some other code, as these events are not only
// matched by the key (address of the parker (state)), but also by this HANDLE. // matched by the key (address of the parker (state)), but also by this HANDLE.
// We lazily allocate this handle the first time it is needed. // We lazily allocate this handle the first time it is needed.

View file

@ -1,4 +1,4 @@
//! Parker implementaiton based on a Mutex and Condvar. //! Parker implementation based on a Mutex and Condvar.
use crate::sync::atomic::AtomicUsize; use crate::sync::atomic::AtomicUsize;
use crate::sync::atomic::Ordering::SeqCst; use crate::sync::atomic::Ordering::SeqCst;
@ -20,7 +20,7 @@ impl Parker {
Parker { state: AtomicUsize::new(EMPTY), lock: Mutex::new(()), cvar: Condvar::new() } Parker { state: AtomicUsize::new(EMPTY), lock: Mutex::new(()), cvar: Condvar::new() }
} }
// This implementaiton doesn't require `unsafe`, but other implementations // This implementation doesn't require `unsafe`, but other implementations
// may assume this is only called by the thread that owns the Parker. // may assume this is only called by the thread that owns the Parker.
pub unsafe fn park(&self) { pub unsafe fn park(&self) {
// If we were previously notified then we consume this notification and // If we were previously notified then we consume this notification and
@ -55,7 +55,7 @@ impl Parker {
} }
} }
// This implementaiton doesn't require `unsafe`, but other implementations // This implementation doesn't require `unsafe`, but other implementations
// may assume this is only called by the thread that owns the Parker. // may assume this is only called by the thread that owns the Parker.
pub unsafe fn park_timeout(&self, dur: Duration) { pub unsafe fn park_timeout(&self, dur: Duration) {
// Like `park` above we have a fast path for an already-notified thread, and // Like `park` above we have a fast path for an already-notified thread, and

View file

@ -582,7 +582,7 @@ pub mod fast {
Key { inner: LazyKeyInner::new(), dtor_state: Cell::new(DtorState::Unregistered) } Key { inner: LazyKeyInner::new(), dtor_state: Cell::new(DtorState::Unregistered) }
} }
// note that this is just a publically-callable function only for the // note that this is just a publicly-callable function only for the
// const-initialized form of thread locals, basically a way to call the // const-initialized form of thread locals, basically a way to call the
// free `register_dtor` function defined elsewhere in libstd. // free `register_dtor` function defined elsewhere in libstd.
pub unsafe fn register_dtor(a: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { pub unsafe fn register_dtor(a: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) {
@ -593,7 +593,7 @@ pub mod fast {
pub unsafe fn get<F: FnOnce() -> T>(&self, init: F) -> Option<&'static T> { pub unsafe fn get<F: FnOnce() -> T>(&self, init: F) -> Option<&'static T> {
// SAFETY: See the definitions of `LazyKeyInner::get` and // SAFETY: See the definitions of `LazyKeyInner::get` and
// `try_initialize` for more informations. // `try_initialize` for more information.
// //
// The caller must ensure no mutable references are ever active to // The caller must ensure no mutable references are ever active to
// the inner cell or the inner T when this is called. // the inner cell or the inner T when this is called.

View file

@ -273,7 +273,7 @@ impl Instant {
// While issues have been seen on arm64 platforms the Arm architecture // While issues have been seen on arm64 platforms the Arm architecture
// requires that the counter monotonically increases and that it must // requires that the counter monotonically increases and that it must
// provide a uniform view of system time (e.g. it must not be possible // provide a uniform view of system time (e.g. it must not be possible
// for a core to recieve a message from another core with a time stamp // for a core to receive a message from another core with a time stamp
// and observe time going backwards (ARM DDI 0487G.b D11.1.2). While // and observe time going backwards (ARM DDI 0487G.b D11.1.2). While
// there have been a few 64bit SoCs that have bugs which cause time to // there have been a few 64bit SoCs that have bugs which cause time to
// not monoticially increase, these have been fixed in the Linux kernel // not monoticially increase, these have been fixed in the Linux kernel

View file

@ -184,8 +184,8 @@ crate fn build_index<'tcx>(krate: &clean::Crate, cache: &mut Cache, tcx: TyCtxt<
}) })
.expect("failed serde conversion") .expect("failed serde conversion")
// All these `replace` calls are because we have to go through JS string for JSON content. // All these `replace` calls are because we have to go through JS string for JSON content.
.replace(r"\", r"\\") .replace(r#"\"#, r"\\")
.replace("'", r"\'") .replace(r#"'"#, r"\'")
// We need to escape double quotes for the JSON. // We need to escape double quotes for the JSON.
.replace("\\\"", "\\\\\"") .replace("\\\"", "\\\\\"")
) )

View file

@ -989,7 +989,7 @@ fn attributes(it: &clean::Item) -> Vec<String> {
.iter() .iter()
.filter_map(|attr| { .filter_map(|attr| {
if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) { if ALLOWED_ATTRIBUTES.contains(&attr.name_or_empty()) {
Some(pprust::attribute_to_string(attr).replace("\n", "").replace(" ", " ")) Some(pprust::attribute_to_string(attr).replace('\n', "").replace(" ", " "))
} else { } else {
None None
} }

View file

@ -963,7 +963,7 @@ fn preprocess_link<'a>(
return None; return None;
} }
let stripped = ori_link.link.replace("`", ""); let stripped = ori_link.link.replace('`', "");
let mut parts = stripped.split('#'); let mut parts = stripped.split('#');
let link = parts.next().unwrap(); let link = parts.next().unwrap();

View file

@ -173,11 +173,11 @@ fn build_rule(v: &[u8], positions: &[usize]) -> String {
.map(|x| ::std::str::from_utf8(&v[x[0]..x[1]]).unwrap_or("")) .map(|x| ::std::str::from_utf8(&v[x[0]..x[1]]).unwrap_or(""))
.collect::<String>() .collect::<String>()
.trim() .trim()
.replace("\n", " ") .replace('\n', " ")
.replace("/", "") .replace('/', "")
.replace("\t", " ") .replace('\t', " ")
.replace("{", "") .replace('{', "")
.replace("}", "") .replace('}', "")
.split(' ') .split(' ')
.filter(|s| !s.is_empty()) .filter(|s| !s.is_empty())
.collect::<Vec<&str>>() .collect::<Vec<&str>>()

View file

@ -10,6 +10,7 @@ trait Tr {
//~^ ERROR mismatched types //~^ ERROR mismatched types
//~| NOTE expected associated type, found `()` //~| NOTE expected associated type, found `()`
//~| NOTE expected associated type `<Self as Tr>::A` //~| NOTE expected associated type `<Self as Tr>::A`
//~| NOTE this expression has type `<Self as Tr>::A`
} }
} }

View file

@ -5,13 +5,15 @@ LL | type A = ();
| ------------ associated type defaults can't be assumed inside the trait defining them | ------------ associated type defaults can't be assumed inside the trait defining them
... ...
LL | let () = p; LL | let () = p;
| ^^ expected associated type, found `()` | ^^ - this expression has type `<Self as Tr>::A`
| |
| expected associated type, found `()`
| |
= note: expected associated type `<Self as Tr>::A` = note: expected associated type `<Self as Tr>::A`
found unit type `()` found unit type `()`
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/defaults-in-other-trait-items.rs:35:25 --> $DIR/defaults-in-other-trait-items.rs:36:25
| |
LL | type Ty = u8; LL | type Ty = u8;
| ------------- associated type defaults can't be assumed inside the trait defining them | ------------- associated type defaults can't be assumed inside the trait defining them

View file

@ -2,9 +2,7 @@ error[E0308]: mismatched types
--> $DIR/default-match-bindings-forbidden.rs:4:5 --> $DIR/default-match-bindings-forbidden.rs:4:5
| |
LL | (x, y) = &(1, 2); LL | (x, y) = &(1, 2);
| ^^^^^^ ------- this expression has type `&({integer}, {integer})` | ^^^^^^ expected reference, found tuple
| |
| expected reference, found tuple
| |
= note: expected type `&({integer}, {integer})` = note: expected type `&({integer}, {integer})`
found tuple `(_, _)` found tuple `(_, _)`

View file

@ -10,9 +10,7 @@ error[E0308]: mismatched types
--> $DIR/tuple_destructure_fail.rs:6:5 --> $DIR/tuple_destructure_fail.rs:6:5
| |
LL | (a, a, b) = (1, 2); LL | (a, a, b) = (1, 2);
| ^^^^^^^^^ ------ this expression has type `({integer}, {integer})` | ^^^^^^^^^ expected a tuple with 2 elements, found one with 3 elements
| |
| expected a tuple with 2 elements, found one with 3 elements
| |
= note: expected type `({integer}, {integer})` = note: expected type `({integer}, {integer})`
found tuple `(_, _, _)` found tuple `(_, _, _)`
@ -29,9 +27,7 @@ error[E0308]: mismatched types
--> $DIR/tuple_destructure_fail.rs:8:5 --> $DIR/tuple_destructure_fail.rs:8:5
| |
LL | (_,) = (1, 2); LL | (_,) = (1, 2);
| ^^^^ ------ this expression has type `({integer}, {integer})` | ^^^^ expected a tuple with 2 elements, found one with 1 element
| |
| expected a tuple with 2 elements, found one with 1 element
| |
= note: expected type `({integer}, {integer})` = note: expected type `({integer}, {integer})`
found tuple `(_,)` found tuple `(_,)`

View file

@ -0,0 +1,25 @@
// check-fail
// See issue #91899. If we treat unnormalized args as WF, `Self` can also be a
// source of unsoundness.
pub trait Yokeable<'a>: 'static {
type Output: 'a;
}
impl<'a, T: 'static + ?Sized> Yokeable<'a> for &'static T {
type Output = &'a T;
}
pub trait ZeroCopyFrom<C: ?Sized>: for<'a> Yokeable<'a> {
/// Clone the cart `C` into a [`Yokeable`] struct, which may retain references into `C`.
fn zero_copy_from<'b>(cart: &'b C) -> <Self as Yokeable<'b>>::Output;
}
impl<T> ZeroCopyFrom<[T]> for &'static [T] {
fn zero_copy_from<'b>(cart: &'b [T]) -> &'b [T] {
//~^ the parameter
cart
}
}
fn main() {}

View file

@ -0,0 +1,12 @@
error[E0310]: the parameter type `T` may not live long enough
--> $DIR/implied-bounds-unnorm-associated-type-3.rs:19:5
|
LL | fn zero_copy_from<'b>(cart: &'b [T]) -> &'b [T] {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
= help: consider adding an explicit lifetime bound `T: 'static`...
= note: ...so that the type `[T]` will meet its required lifetime bounds
error: aborting due to previous error
For more information about this error, try `rustc --explain E0310`.

View file

@ -1,8 +1,6 @@
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/exclusive_range_pattern_syntax_collision.rs:6:13 --> $DIR/exclusive_range_pattern_syntax_collision.rs:6:13
| |
LL | match [5..4, 99..105, 43..44] {
| ----------------------- this expression has type `[std::ops::Range<{integer}>; 3]`
LL | [_, 99.., _] => {}, LL | [_, 99.., _] => {},
| ^^ expected struct `std::ops::Range`, found integer | ^^ expected struct `std::ops::Range`, found integer
| |

View file

@ -7,8 +7,6 @@ LL | [_, 99..] => {},
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/exclusive_range_pattern_syntax_collision2.rs:6:13 --> $DIR/exclusive_range_pattern_syntax_collision2.rs:6:13
| |
LL | match [5..4, 99..105, 43..44] {
| ----------------------- this expression has type `[std::ops::Range<{integer}>; 3]`
LL | [_, 99..] => {}, LL | [_, 99..] => {},
| ^^ expected struct `std::ops::Range`, found integer | ^^ expected struct `std::ops::Range`, found integer
| |

View file

@ -1,8 +1,6 @@
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/exclusive_range_pattern_syntax_collision3.rs:6:12 --> $DIR/exclusive_range_pattern_syntax_collision3.rs:6:12
| |
LL | match [5..4, 99..105, 43..44] {
| ----------------------- this expression has type `[std::ops::Range<{integer}>; 3]`
LL | [..9, 99..100, _] => {}, LL | [..9, 99..100, _] => {},
| ^ expected struct `std::ops::Range`, found integer | ^ expected struct `std::ops::Range`, found integer
| |
@ -12,8 +10,6 @@ LL | [..9, 99..100, _] => {},
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/exclusive_range_pattern_syntax_collision3.rs:6:15 --> $DIR/exclusive_range_pattern_syntax_collision3.rs:6:15
| |
LL | match [5..4, 99..105, 43..44] {
| ----------------------- this expression has type `[std::ops::Range<{integer}>; 3]`
LL | [..9, 99..100, _] => {}, LL | [..9, 99..100, _] => {},
| ^^ --- this is of type `{integer}` | ^^ --- this is of type `{integer}`
| | | |
@ -25,8 +21,6 @@ LL | [..9, 99..100, _] => {},
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/exclusive_range_pattern_syntax_collision3.rs:6:19 --> $DIR/exclusive_range_pattern_syntax_collision3.rs:6:19
| |
LL | match [5..4, 99..105, 43..44] {
| ----------------------- this expression has type `[std::ops::Range<{integer}>; 3]`
LL | [..9, 99..100, _] => {}, LL | [..9, 99..100, _] => {},
| -- ^^^ expected struct `std::ops::Range`, found integer | -- ^^^ expected struct `std::ops::Range`, found integer
| | | |

View file

@ -1,8 +1,6 @@
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/pat-tuple-5.rs:8:10 --> $DIR/pat-tuple-5.rs:8:10
| |
LL | match (0, 1) {
| ------ this expression has type `({integer}, {integer})`
LL | (PAT ..) => {} LL | (PAT ..) => {}
| ^^^ expected tuple, found `u8` | ^^^ expected tuple, found `u8`
| |

View file

@ -1,8 +1,6 @@
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/issue-11844.rs:6:9 --> $DIR/issue-11844.rs:6:9
| |
LL | match a {
| - this expression has type `Option<Box<{integer}>>`
LL | Ok(a) => LL | Ok(a) =>
| ^^^^^ expected enum `Option`, found enum `Result` | ^^^^^ expected enum `Option`, found enum `Result`
| |

View file

@ -1,8 +1,6 @@
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/issue-12552.rs:6:5 --> $DIR/issue-12552.rs:6:5
| |
LL | match t {
| - this expression has type `Result<_, {integer}>`
LL | Some(k) => match k { LL | Some(k) => match k {
| ^^^^^^^ expected enum `Result`, found enum `Option` | ^^^^^^^ expected enum `Result`, found enum `Option`
| |
@ -12,9 +10,6 @@ LL | Some(k) => match k {
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/issue-12552.rs:9:5 --> $DIR/issue-12552.rs:9:5
| |
LL | match t {
| - this expression has type `Result<_, {integer}>`
...
LL | None => () LL | None => ()
| ^^^^ expected enum `Result`, found enum `Option` | ^^^^ expected enum `Result`, found enum `Option`
| |

View file

@ -1,8 +1,6 @@
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/issue-13466.rs:8:9 --> $DIR/issue-13466.rs:8:9
| |
LL | let _x: usize = match Some(1) {
| ------- this expression has type `Option<{integer}>`
LL | Ok(u) => u, LL | Ok(u) => u,
| ^^^^^ expected enum `Option`, found enum `Result` | ^^^^^ expected enum `Option`, found enum `Result`
| |
@ -12,9 +10,6 @@ LL | Ok(u) => u,
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/issue-13466.rs:14:9 --> $DIR/issue-13466.rs:14:9
| |
LL | let _x: usize = match Some(1) {
| ------- this expression has type `Option<{integer}>`
...
LL | Err(e) => panic!(e) LL | Err(e) => panic!(e)
| ^^^^^^ expected enum `Option`, found enum `Result` | ^^^^^^ expected enum `Option`, found enum `Result`
| |

View file

@ -1,8 +1,6 @@
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/issue-3680.rs:3:9 --> $DIR/issue-3680.rs:3:9
| |
LL | match None {
| ---- this expression has type `Option<_>`
LL | Err(_) => () LL | Err(_) => ()
| ^^^^^^ expected enum `Option`, found enum `Result` | ^^^^^^ expected enum `Option`, found enum `Result`
| |

View file

@ -36,7 +36,7 @@ error[E0308]: mismatched types
--> $DIR/issue-66706.rs:2:5 --> $DIR/issue-66706.rs:2:5
| |
LL | fn a() { LL | fn a() {
| - help: try adding a return type: `-> [{integer}; _]` | - possibly return type missing here?
LL | [0; [|_: _ &_| ()].len()] LL | [0; [|_: _ &_| ()].len()]
| ^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found array `[{integer}; _]` | ^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found array `[{integer}; _]`
@ -44,7 +44,7 @@ error[E0308]: mismatched types
--> $DIR/issue-66706.rs:14:5 --> $DIR/issue-66706.rs:14:5
| |
LL | fn c() { LL | fn c() {
| - help: try adding a return type: `-> [{integer}; _]` | - possibly return type missing here?
LL | [0; [|&_: _ &_| {}; 0 ].len()] LL | [0; [|&_: _ &_| {}; 0 ].len()]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found array `[{integer}; _]` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found array `[{integer}; _]`
@ -52,7 +52,7 @@ error[E0308]: mismatched types
--> $DIR/issue-66706.rs:20:5 --> $DIR/issue-66706.rs:20:5
| |
LL | fn d() { LL | fn d() {
| - help: try adding a return type: `-> [{integer}; _]` | - possibly return type missing here?
LL | [0; match [|f @ &ref _| () ] {} ] LL | [0; match [|f @ &ref _| () ] {} ]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found array `[{integer}; _]` | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found array `[{integer}; _]`

View file

@ -21,8 +21,6 @@ LL | (_a, _x @ ..) => {}
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/issue-72574-1.rs:4:9 --> $DIR/issue-72574-1.rs:4:9
| |
LL | match x {
| - this expression has type `({integer}, {integer}, {integer})`
LL | (_a, _x @ ..) => {} LL | (_a, _x @ ..) => {}
| ^^^^^^^^^^^^^ expected a tuple with 3 elements, found one with 2 elements | ^^^^^^^^^^^^^ expected a tuple with 3 elements, found one with 2 elements
| |

View file

@ -9,8 +9,6 @@ LL | (0, ref y) | (y, 0) => {}
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/E0409.rs:5:23 --> $DIR/E0409.rs:5:23
| |
LL | match x {
| - this expression has type `({integer}, {integer})`
LL | (0, ref y) | (y, 0) => {} LL | (0, ref y) | (y, 0) => {}
| ----- ^ expected `&{integer}`, found integer | ----- ^ expected `&{integer}`, found integer
| | | |

View file

@ -3,9 +3,6 @@ error[E0308]: mismatched types
| |
LL | let &_ LL | let &_
| ^^ types differ in mutability | ^^ types differ in mutability
...
LL | = foo;
| --- this expression has type `&mut {integer}`
| |
= note: expected mutable reference `&mut {integer}` = note: expected mutable reference `&mut {integer}`
found reference `&_` found reference `&_`
@ -15,9 +12,6 @@ error[E0308]: mismatched types
| |
LL | let &mut _ LL | let &mut _
| ^^^^^^ types differ in mutability | ^^^^^^ types differ in mutability
...
LL | = bar;
| --- this expression has type `&{integer}`
| |
= note: expected reference `&{integer}` = note: expected reference `&{integer}`
found mutable reference `&mut _` found mutable reference `&mut _`

View file

@ -1,15 +1,13 @@
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/diverging-tuple-parts-39485.rs:8:5 --> $DIR/diverging-tuple-parts-39485.rs:8:5
| |
LL | fn g() {
| - possibly return type missing here?
LL | &panic!() LL | &panic!()
| ^^^^^^^^^ expected `()`, found reference | ^^^^^^^^^ expected `()`, found reference
| |
= note: expected unit type `()` = note: expected unit type `()`
found reference `&_` found reference `&_`
help: try adding a return type
|
LL | fn g() -> &_ {
| +++++
help: consider removing the borrow help: consider removing the borrow
| |
LL - &panic!() LL - &panic!()

View file

@ -86,9 +86,8 @@ error[E0308]: mismatched types
--> $DIR/already-bound-name.rs:30:32 --> $DIR/already-bound-name.rs:30:32
| |
LL | let (B(A(a, _) | B(a)) | A(a, A(a, _) | B(a))) = B(B(1)); LL | let (B(A(a, _) | B(a)) | A(a, A(a, _) | B(a))) = B(B(1));
| - ^ ------- this expression has type `E<E<{integer}>>` | - ^ expected integer, found enum `E`
| | | | |
| | expected integer, found enum `E`
| first introduced with type `{integer}` here | first introduced with type `{integer}` here
| |
= note: expected type `{integer}` = note: expected type `{integer}`

View file

@ -65,9 +65,8 @@ error[E0308]: mismatched types
--> $DIR/inconsistent-modes.rs:13:32 --> $DIR/inconsistent-modes.rs:13:32
| |
LL | let (Ok((ref a, b)) | Err((ref mut a, ref b))) = Ok((0, &0)); LL | let (Ok((ref a, b)) | Err((ref mut a, ref b))) = Ok((0, &0));
| ----- ^^^^^^^^^ ----------- this expression has type `Result<({integer}, &{integer}), (_, _)>` | ----- ^^^^^^^^^ types differ in mutability
| | | | |
| | types differ in mutability
| first introduced with type `&{integer}` here | first introduced with type `&{integer}` here
| |
= note: expected type `&{integer}` = note: expected type `&{integer}`

View file

@ -22,9 +22,7 @@ error[E0308]: mismatched types
--> $DIR/issue-74702.rs:2:9 --> $DIR/issue-74702.rs:2:9
| |
LL | let (foo @ ..,) = (0, 0); LL | let (foo @ ..,) = (0, 0);
| ^^^^^^^^^^^ ------ this expression has type `({integer}, {integer})` | ^^^^^^^^^^^ expected a tuple with 2 elements, found one with 1 element
| |
| expected a tuple with 2 elements, found one with 1 element
| |
= note: expected tuple `({integer}, {integer})` = note: expected tuple `({integer}, {integer})`
found tuple `(_,)` found tuple `(_,)`

View file

@ -150,8 +150,6 @@ LL | E1::Z0 => {}
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/pat-tuple-overfield.rs:19:9 --> $DIR/pat-tuple-overfield.rs:19:9
| |
LL | match (1, 2, 3) {
| --------- this expression has type `({integer}, {integer}, {integer})`
LL | (1, 2, 3, 4) => {} LL | (1, 2, 3, 4) => {}
| ^^^^^^^^^^^^ expected a tuple with 3 elements, found one with 4 elements | ^^^^^^^^^^^^ expected a tuple with 3 elements, found one with 4 elements
| |
@ -161,9 +159,6 @@ LL | (1, 2, 3, 4) => {}
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/pat-tuple-overfield.rs:20:9 --> $DIR/pat-tuple-overfield.rs:20:9
| |
LL | match (1, 2, 3) {
| --------- this expression has type `({integer}, {integer}, {integer})`
LL | (1, 2, 3, 4) => {}
LL | (1, 2, .., 3, 4) => {} LL | (1, 2, .., 3, 4) => {}
| ^^^^^^^^^^^^^^^^ expected a tuple with 3 elements, found one with 4 elements | ^^^^^^^^^^^^^^^^ expected a tuple with 3 elements, found one with 4 elements
| |

View file

@ -1,19 +1,15 @@
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/return-type.rs:10:5 --> $DIR/return-type.rs:10:5
| |
LL | fn bar() {
| - possibly return type missing here?
LL | foo(4 as usize) LL | foo(4 as usize)
| ^^^^^^^^^^^^^^^ expected `()`, found struct `S` | ^^^^^^^^^^^^^^^- help: consider using a semicolon here: `;`
| |
| expected `()`, found struct `S`
| |
= note: expected unit type `()` = note: expected unit type `()`
found struct `S<usize>` found struct `S<usize>`
help: consider using a semicolon here
|
LL | foo(4 as usize);
| +
help: try adding a return type
|
LL | fn bar() -> S<usize> {
| +++++++++++
error: aborting due to previous error error: aborting due to previous error

View file

@ -644,7 +644,9 @@ error[E0308]: mismatched types
--> $DIR/disallowed-positions.rs:76:12 --> $DIR/disallowed-positions.rs:76:12
| |
LL | if let Range { start: F, end } = F..|| true {} LL | if let Range { start: F, end } = F..|| true {}
| ^^^^^^^^^^^^^^^^^^^^^^^ expected fn pointer, found struct `std::ops::Range` | ^^^^^^^^^^^^^^^^^^^^^^^ - this expression has type `fn() -> bool`
| |
| expected fn pointer, found struct `std::ops::Range`
| |
= note: expected fn pointer `fn() -> bool` = note: expected fn pointer `fn() -> bool`
found struct `std::ops::Range<_>` found struct `std::ops::Range<_>`
@ -832,7 +834,9 @@ error[E0308]: mismatched types
--> $DIR/disallowed-positions.rs:140:15 --> $DIR/disallowed-positions.rs:140:15
| |
LL | while let Range { start: F, end } = F..|| true {} LL | while let Range { start: F, end } = F..|| true {}
| ^^^^^^^^^^^^^^^^^^^^^^^ expected fn pointer, found struct `std::ops::Range` | ^^^^^^^^^^^^^^^^^^^^^^^ - this expression has type `fn() -> bool`
| |
| expected fn pointer, found struct `std::ops::Range`
| |
= note: expected fn pointer `fn() -> bool` = note: expected fn pointer `fn() -> bool`
found struct `std::ops::Range<_>` found struct `std::ops::Range<_>`

View file

@ -1,8 +1,6 @@
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/slightly-nice-generic-literal-messages.rs:7:9 --> $DIR/slightly-nice-generic-literal-messages.rs:7:9
| |
LL | match Foo(1.1, marker::PhantomData) {
| ----------------------------- this expression has type `Foo<{float}, _>`
LL | 1 => {} LL | 1 => {}
| ^ expected struct `Foo`, found integer | ^ expected struct `Foo`, found integer
| |

View file

@ -101,8 +101,6 @@ LL | type PointF = Point<f32>;
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/structure-constructor-type-mismatch.rs:54:9 --> $DIR/structure-constructor-type-mismatch.rs:54:9
| |
LL | match (Point { x: 1, y: 2 }) {
| ---------------------- this expression has type `Point<{integer}>`
LL | PointF::<u32> { .. } => {} LL | PointF::<u32> { .. } => {}
| ^^^^^^^^^^^^^^^^^^^^ expected integer, found `f32` | ^^^^^^^^^^^^^^^^^^^^ expected integer, found `f32`
| |
@ -112,8 +110,6 @@ LL | PointF::<u32> { .. } => {}
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/structure-constructor-type-mismatch.rs:59:9 --> $DIR/structure-constructor-type-mismatch.rs:59:9
| |
LL | match (Point { x: 1, y: 2 }) {
| ---------------------- this expression has type `Point<{integer}>`
LL | PointF { .. } => {} LL | PointF { .. } => {}
| ^^^^^^^^^^^^^ expected integer, found `f32` | ^^^^^^^^^^^^^ expected integer, found `f32`
| |
@ -123,8 +119,6 @@ LL | PointF { .. } => {}
error[E0308]: mismatched types error[E0308]: mismatched types
--> $DIR/structure-constructor-type-mismatch.rs:67:9 --> $DIR/structure-constructor-type-mismatch.rs:67:9
| |
LL | match (Pair { x: 1, y: 2 }) {
| --------------------- this expression has type `Pair<{integer}, {integer}>`
LL | PairF::<u32> { .. } => {} LL | PairF::<u32> { .. } => {}
| ^^^^^^^^^^^^^^^^^^^ expected integer, found `f32` | ^^^^^^^^^^^^^^^^^^^ expected integer, found `f32`
| |

View file

@ -2,7 +2,7 @@ error[E0308]: mismatched types
--> $DIR/issue-57673-ice-on-deref-of-boxed-trait.rs:5:5 --> $DIR/issue-57673-ice-on-deref-of-boxed-trait.rs:5:5
| |
LL | fn ice(x: Box<dyn Iterator<Item=()>>) { LL | fn ice(x: Box<dyn Iterator<Item=()>>) {
| - possibly return type missing here? | - help: try adding a return type: `-> (dyn Iterator<Item = ()> + 'static)`
LL | *x LL | *x
| ^^ expected `()`, found trait object `dyn Iterator` | ^^ expected `()`, found trait object `dyn Iterator`
| |

View file

@ -40,7 +40,7 @@ error[E0308]: mismatched types
LL | fn f(){||yield(((){), LL | fn f(){||yield(((){),
| -^^^^^^^^^^^^^^^ expected `()`, found generator | -^^^^^^^^^^^^^^^ expected `()`, found generator
| | | |
| help: try adding a return type: `-> [generator@$DIR/issue-91334.rs:10:8: 10:23]` | possibly return type missing here?
| |
= note: expected unit type `()` = note: expected unit type `()`
found generator `[generator@$DIR/issue-91334.rs:10:8: 10:23]` found generator `[generator@$DIR/issue-91334.rs:10:8: 10:23]`

View file

@ -0,0 +1,10 @@
#[allow(unused)]
fn foo() {
//~^ NOTE possibly return type missing here?
vec!['a'].iter().map(|c| c)
//~^ ERROR mismatched types [E0308]
//~| NOTE expected `()`, found struct `Map`
//~| NOTE expected unit type `()`
}
fn main() {}

View file

@ -0,0 +1,17 @@
error[E0308]: mismatched types
--> $DIR/return_type_containing_closure.rs:4:5
|
LL | fn foo() {
| - possibly return type missing here?
LL |
LL | vec!['a'].iter().map(|c| c)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^- help: consider using a semicolon here: `;`
| |
| expected `()`, found struct `Map`
|
= note: expected unit type `()`
found struct `Map<std::slice::Iter<'_, char>, [closure@$DIR/return_type_containing_closure.rs:4:26: 4:31]>`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.