From 97e844a032c47d4b3e70d2043f809767e437ac24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Mon, 13 Dec 2021 22:58:58 +0100 Subject: [PATCH 1/7] fix clippy::single_char_pattern perf findings --- compiler/rustc_codegen_ssa/src/back/link.rs | 4 ++-- compiler/rustc_driver/src/lib.rs | 10 +++++----- compiler/rustc_graphviz/src/lib.rs | 2 +- compiler/rustc_interface/src/passes.rs | 2 +- compiler/rustc_middle/src/lint.rs | 4 ++-- compiler/rustc_middle/src/mir/generic_graphviz.rs | 4 ++-- compiler/rustc_middle/src/mir/spanview.rs | 12 ++++++------ compiler/rustc_mir_transform/src/coverage/debug.rs | 2 +- compiler/rustc_mir_transform/src/coverage/spans.rs | 2 +- compiler/rustc_parse/src/parser/diagnostics.rs | 2 +- compiler/rustc_save_analysis/src/lib.rs | 2 +- compiler/rustc_session/src/config.rs | 2 +- compiler/rustc_session/src/options.rs | 2 +- compiler/rustc_session/src/output.rs | 2 +- .../src/traits/error_reporting/suggestions.rs | 2 +- src/librustdoc/html/render/cache.rs | 4 ++-- src/librustdoc/html/render/mod.rs | 2 +- src/librustdoc/passes/collect_intra_doc_links.rs | 2 +- src/librustdoc/theme.rs | 10 +++++----- 19 files changed, 36 insertions(+), 36 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index bf45810de7708..e29c109f12d59 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -2226,8 +2226,8 @@ fn add_upstream_rust_crates<'a, B: ArchiveBuilder<'a>>( continue; } - let canonical = f.replace("-", "_"); - let canonical_name = name.replace("-", "_"); + let canonical = f.replace('-', "_"); + let canonical_name = name.replace('-', "_"); let is_rust_object = canonical.starts_with(&canonical_name) && looks_like_rust_object_file(&f); diff --git a/compiler/rustc_driver/src/lib.rs b/compiler/rustc_driver/src/lib.rs index 6ff94341142fd..12e0b7a4977e1 100644 --- a/compiler/rustc_driver/src/lib.rs +++ b/compiler/rustc_driver/src/lib.rs @@ -872,7 +872,7 @@ Available lint options: let print_lints = |lints: Vec<&Lint>| { for lint in lints { - let name = lint.name_lower().replace("_", "-"); + let name = lint.name_lower().replace('_', "-"); println!( " {} {:7.7} {}", padded(&name), @@ -908,10 +908,10 @@ Available lint options: let print_lint_groups = |lints: Vec<(&'static str, Vec)>| { for (name, to) in lints { - let name = name.to_lowercase().replace("_", "-"); + let name = name.to_lowercase().replace('_', "-"); let desc = to .into_iter() - .map(|x| x.to_string().replace("_", "-")) + .map(|x| x.to_string().replace('_', "-")) .collect::>() .join(", "); println!(" {} {}", padded(&name), desc); @@ -960,7 +960,7 @@ fn print_flag_list( println!( " {} {:>width$}=val -- {}", cmdline_opt, - name.replace("_", "-"), + name.replace('_', "-"), desc, width = max_len ); @@ -1015,7 +1015,7 @@ pub fn handle_options(args: &[String]) -> Option { .iter() .map(|&(name, ..)| ('C', 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)), _ => None, }; diff --git a/compiler/rustc_graphviz/src/lib.rs b/compiler/rustc_graphviz/src/lib.rs index edb8bd503e1d0..e318090ebe15a 100644 --- a/compiler/rustc_graphviz/src/lib.rs +++ b/compiler/rustc_graphviz/src/lib.rs @@ -472,7 +472,7 @@ pub trait Labeller<'a> { /// Escape tags in such a way that it is suitable for inclusion in a /// Graphviz HTML label. pub fn escape_html(s: &str) -> String { - s.replace("&", "&").replace("\"", """).replace("<", "<").replace(">", ">") + s.replace('&', "&").replace('\"', """).replace('<', "<").replace('>', ">") } impl<'a> LabelText<'a> { diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index da76f221269fe..34865900495c7 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -584,7 +584,7 @@ fn output_conflicts_with_dir(output_paths: &[PathBuf]) -> Option { fn escape_dep_filename(filename: &str) -> String { // Apparently clang and gcc *only* escape spaces: // https://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4 - filename.replace(" ", "\\ ") + filename.replace(' ', "\\ ") } // Makefile comments only need escaping newlines and `\`. diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index 881b14278e99e..a6432b301743a 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -295,7 +295,7 @@ pub fn struct_lint_level<'s, 'd>( Level::Allow => "-A", 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 { sess.diag_note_once( &mut err, @@ -306,7 +306,7 @@ pub fn struct_lint_level<'s, 'd>( ), ); } 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( &mut err, DiagnosticMessageId::from(lint), diff --git a/compiler/rustc_middle/src/mir/generic_graphviz.rs b/compiler/rustc_middle/src/mir/generic_graphviz.rs index 21c18b28e258b..c907680bda14a 100644 --- a/compiler/rustc_middle/src/mir/generic_graphviz.rs +++ b/compiler/rustc_middle/src/mir/generic_graphviz.rs @@ -126,7 +126,7 @@ impl< write!( w, r#"{}"#, - dot::escape_html(§ion).replace("\n", "
") + dot::escape_html(§ion).replace('\n', "
") )?; } @@ -147,7 +147,7 @@ impl< let src = self.node(source); let trg = self.node(target); let escaped_edge_label = if let Some(edge_label) = edge_labels.get(index) { - dot::escape_html(edge_label).replace("\n", r#"
"#) + dot::escape_html(edge_label).replace('\n', r#"
"#) } else { "".to_owned() }; diff --git a/compiler/rustc_middle/src/mir/spanview.rs b/compiler/rustc_middle/src/mir/spanview.rs index 1260c691e7844..507f9971981b0 100644 --- a/compiler/rustc_middle/src/mir/spanview.rs +++ b/compiler/rustc_middle/src/mir/spanview.rs @@ -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 { - s.replace("&", "&").replace("<", "<").replace(">", ">") + s.replace('&', "&").replace('<', "<").replace('>', ">") } fn escape_attr(s: &str) -> String { - s.replace("&", "&") - .replace("\"", """) - .replace("'", "'") - .replace("<", "<") - .replace(">", ">") + s.replace('&', "&") + .replace('\"', """) + .replace('\'', "'") + .replace('<', "<") + .replace('>', ">") } diff --git a/compiler/rustc_mir_transform/src/coverage/debug.rs b/compiler/rustc_mir_transform/src/coverage/debug.rs index 588103ca43dd0..c61ee6f7e6cb7 100644 --- a/compiler/rustc_mir_transform/src/coverage/debug.rs +++ b/compiler/rustc_mir_transform/src/coverage/debug.rs @@ -148,7 +148,7 @@ impl DebugOptions { let mut counter_format = ExpressionFormat::default(); 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('=') { None => (setting_str, None), Some((k, v)) => (k, Some(v)), diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs index 01e72a6c1588d..b5356a817f7ac 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -155,7 +155,7 @@ impl CoverageSpan { format!( "{}\n {}", 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 "), ) } diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 25beed1ecf9c7..9677e7642b88c 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -2236,7 +2236,7 @@ impl<'a> Parser<'a> { err.span_suggestion( seq_span, "...or a vertical bar to match on multiple alternatives", - seq_snippet.replace(",", " |"), + seq_snippet.replace(',', " |"), Applicability::MachineApplicable, ); } diff --git a/compiler/rustc_save_analysis/src/lib.rs b/compiler/rustc_save_analysis/src/lib.rs index c7f8fe3a88a64..6f86bafbe4581 100644 --- a/compiler/rustc_save_analysis/src/lib.rs +++ b/compiler/rustc_save_analysis/src/lib.rs @@ -1036,7 +1036,7 @@ fn find_config(supplied: Option) -> Config { // Helper function to escape quotes in a string fn escape(s: String) -> String { - s.replace("\"", "\"\"") + s.replace('\"', "\"\"") } // Helper function to determine if a span came from a diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 5df8a4103b74f..50a8f0336728e 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -1213,7 +1213,7 @@ pub fn get_cmd_lint_options( if lint_name == "help" { describe_lints = true; } else { - lint_opts_with_position.push((arg_pos, lint_name.replace("-", "_"), level)); + lint_opts_with_position.push((arg_pos, lint_name.replace('-', "_"), level)); } } } diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index bd7b1639613eb..dc5f4ee0ece0c 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -335,7 +335,7 @@ fn build_options( 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) { Some((_, setter, type_desc, _)) => { if !setter(&mut op, value) { diff --git a/compiler/rustc_session/src/output.rs b/compiler/rustc_session/src/output.rs index cc1e4bb198a3b..5689b723ad610 100644 --- a/compiler/rustc_session/src/output.rs +++ b/compiler/rustc_session/src/output.rs @@ -85,7 +85,7 @@ pub fn find_crate_name(sess: &Session, attrs: &[ast::Attribute], input: &Input) ); sess.err(&msg); } else { - return validate(s.replace("-", "_"), None); + return validate(s.replace('-', "_"), None); } } } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 286c9c9900b95..1396d1e606af4 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -741,7 +741,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { let msg = format!( "the trait bound `{}: {}` is not satisfied", - orig_ty.to_string(), + orig_ty, old_ref.print_only_trait_path(), ); if has_custom_message { diff --git a/src/librustdoc/html/render/cache.rs b/src/librustdoc/html/render/cache.rs index 2f7214e958ea7..631eacc961828 100644 --- a/src/librustdoc/html/render/cache.rs +++ b/src/librustdoc/html/render/cache.rs @@ -184,8 +184,8 @@ crate fn build_index<'tcx>(krate: &clean::Crate, cache: &mut Cache, tcx: TyCtxt< }) .expect("failed serde conversion") // All these `replace` calls are because we have to go through JS string for JSON content. - .replace(r"\", r"\\") - .replace("'", r"\'") + .replace(r#"\"#, r"\\") + .replace(r#"'"#, r"\'") // We need to escape double quotes for the JSON. .replace("\\\"", "\\\\\"") ) diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 166e084012724..c67fe1fef40cd 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -989,7 +989,7 @@ fn attributes(it: &clean::Item) -> Vec { .iter() .filter_map(|attr| { 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 { None } diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 4e5812d7f8429..2faf7781807d4 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -963,7 +963,7 @@ fn preprocess_link<'a>( return None; } - let stripped = ori_link.link.replace("`", ""); + let stripped = ori_link.link.replace('`', ""); let mut parts = stripped.split('#'); let link = parts.next().unwrap(); diff --git a/src/librustdoc/theme.rs b/src/librustdoc/theme.rs index b8b3f9634e582..1e9a65e1d2fc4 100644 --- a/src/librustdoc/theme.rs +++ b/src/librustdoc/theme.rs @@ -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("")) .collect::() .trim() - .replace("\n", " ") - .replace("/", "") - .replace("\t", " ") - .replace("{", "") - .replace("}", "") + .replace('\n', " ") + .replace('/', "") + .replace('\t', " ") + .replace('{', "") + .replace('}', "") .split(' ') .filter(|s| !s.is_empty()) .collect::>() From f0c0732a36f798876b855df909b98f100e541a16 Mon Sep 17 00:00:00 2001 From: Jack Huey <31162821+jackh726@users.noreply.github.com> Date: Tue, 14 Dec 2021 10:35:31 -0500 Subject: [PATCH 2/7] Add another regression test for unnormalized fn args with Self --- ...implied-bounds-unnorm-associated-type-3.rs | 25 +++++++++++++++++++ ...ied-bounds-unnorm-associated-type-3.stderr | 12 +++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/test/ui/fn/implied-bounds-unnorm-associated-type-3.rs create mode 100644 src/test/ui/fn/implied-bounds-unnorm-associated-type-3.stderr diff --git a/src/test/ui/fn/implied-bounds-unnorm-associated-type-3.rs b/src/test/ui/fn/implied-bounds-unnorm-associated-type-3.rs new file mode 100644 index 0000000000000..dc25ac086137a --- /dev/null +++ b/src/test/ui/fn/implied-bounds-unnorm-associated-type-3.rs @@ -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: 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) -> >::Output; +} + +impl ZeroCopyFrom<[T]> for &'static [T] { + fn zero_copy_from<'b>(cart: &'b [T]) -> &'b [T] { + //~^ the parameter + cart + } +} + +fn main() {} diff --git a/src/test/ui/fn/implied-bounds-unnorm-associated-type-3.stderr b/src/test/ui/fn/implied-bounds-unnorm-associated-type-3.stderr new file mode 100644 index 0000000000000..26eecf6a21d3d --- /dev/null +++ b/src/test/ui/fn/implied-bounds-unnorm-associated-type-3.stderr @@ -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`. From a957cefda63c76c7a91a705f683be45c684d4303 Mon Sep 17 00:00:00 2001 From: Frank Steffahn Date: Tue, 14 Dec 2021 15:23:34 +0100 Subject: [PATCH 3/7] Fix a bunch of typos --- library/alloc/tests/boxed.rs | 2 +- library/alloc/tests/str.rs | 2 +- library/core/src/alloc/layout.rs | 4 ++-- library/core/src/cell.rs | 6 +++--- library/core/src/iter/adapters/zip.rs | 2 +- library/core/src/iter/range.rs | 4 ++-- library/core/src/num/dec2flt/number.rs | 2 +- library/core/src/num/fmt.rs | 2 +- library/core/src/slice/iter.rs | 2 +- library/core/src/slice/rotate.rs | 6 +++--- library/core/src/str/iter.rs | 18 +++++++++--------- library/core/tests/array.rs | 2 +- library/panic_unwind/src/emcc.rs | 2 +- library/std/src/fs/tests.rs | 2 +- library/std/src/io/mod.rs | 4 ++-- library/std/src/io/stdio.rs | 2 +- library/std/src/net/ip/tests.rs | 2 +- library/std/src/panicking.rs | 6 +++--- library/std/src/sys/itron/thread.rs | 4 ++-- library/std/src/sys/unix/kernel_copy.rs | 2 +- .../src/sys/unix/process/process_fuchsia.rs | 2 +- library/std/src/sys/unix/weak.rs | 2 +- library/std/src/sys/wasm/alloc.rs | 8 ++++---- library/std/src/sys/wasm/atomics/mutex.rs | 6 +++--- library/std/src/sys/windows/stdio.rs | 2 +- library/std/src/sys/windows/thread_parker.rs | 2 +- .../src/sys_common/thread_parker/generic.rs | 6 +++--- library/std/src/thread/local.rs | 4 ++-- library/std/src/time.rs | 2 +- 29 files changed, 55 insertions(+), 55 deletions(-) diff --git a/library/alloc/tests/boxed.rs b/library/alloc/tests/boxed.rs index a38b5c471bf06..bfe66b2687ef4 100644 --- a/library/alloc/tests/boxed.rs +++ b/library/alloc/tests/boxed.rs @@ -3,7 +3,7 @@ use std::mem::MaybeUninit; use std::ptr::NonNull; #[test] -fn unitialized_zero_size_box() { +fn uninitialized_zero_size_box() { assert_eq!( &*Box::<()>::new_uninit() as *const _, NonNull::>::dangling().as_ptr(), diff --git a/library/alloc/tests/str.rs b/library/alloc/tests/str.rs index 1b741f174fb12..7bd0abbad0192 100644 --- a/library/alloc/tests/str.rs +++ b/library/alloc/tests/str.rs @@ -162,7 +162,7 @@ fn test_join_for_different_lengths_with_long_separator() { } #[test] -fn test_join_isue_80335() { +fn test_join_issue_80335() { use core::{borrow::Borrow, cell::Cell}; struct WeirdBorrow { diff --git a/library/core/src/alloc/layout.rs b/library/core/src/alloc/layout.rs index 9df0b5c551915..ea639268652c3 100644 --- a/library/core/src/alloc/layout.rs +++ b/library/core/src/alloc/layout.rs @@ -157,11 +157,11 @@ impl Layout { /// /// - If `T` is `Sized`, this function is always safe to call. /// - 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* /// (dynamic tail length + statically sized prefix) must fit in `isize`. /// - 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* /// (dynamic tail length + statically sized prefix) must fit in `isize`. /// - an (unstable) [extern type], then this function is always safe to diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index 06dc5ecf2ffa6..bc3f7167fac3a 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -898,7 +898,7 @@ impl RefCell { Ok(Ref { value: unsafe { &*self.value.get() }, borrow: b }) } 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` #[cfg(feature = "debug_refcell")] location: self.borrowed_at.get().unwrap(), @@ -983,7 +983,7 @@ impl RefCell { Ok(RefMut { value: unsafe { &mut *self.value.get() }, borrow: b }) } 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` #[cfg(feature = "debug_refcell")] location: self.borrowed_at.get().unwrap(), @@ -1104,7 +1104,7 @@ impl RefCell { Ok(unsafe { &*self.value.get() }) } else { 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` #[cfg(feature = "debug_refcell")] location: self.borrowed_at.get().unwrap(), diff --git a/library/core/src/iter/adapters/zip.rs b/library/core/src/iter/adapters/zip.rs index 920fa59c8ad6e..b8c3cd847e454 100644 --- a/library/core/src/iter/adapters/zip.rs +++ b/library/core/src/iter/adapters/zip.rs @@ -517,7 +517,7 @@ impl IterMut<'a, T> { // the length, to also allows for the fast `ptr == end` check. // // 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 { assume(!ptr.is_null()); diff --git a/library/core/src/slice/rotate.rs b/library/core/src/slice/rotate.rs index 7528927ef33b9..4589c6c0f04a5 100644 --- a/library/core/src/slice/rotate.rs +++ b/library/core/src/slice/rotate.rs @@ -104,7 +104,7 @@ pub unsafe fn ptr_rotate(mut left: usize, mut mid: *mut T, mut right: usize) // - overflows cannot happen for `i` since the function's safety contract ask for // `mid+right-1 = x+left+right` to be valid for writing // - 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 tmp = unsafe { x.add(i).replace(tmp) }; @@ -202,7 +202,7 @@ pub unsafe fn ptr_rotate(mut left: usize, mut mid: *mut T, mut right: usize) loop { // SAFETY: // `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. unsafe { ptr::swap_nonoverlapping(mid.sub(right), mid, right); @@ -218,7 +218,7 @@ pub unsafe fn ptr_rotate(mut left: usize, mut mid: *mut T, mut right: usize) loop { // SAFETY: `[mid-left, mid+left)` is valid for reading and writing because // `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. unsafe { ptr::swap_nonoverlapping(mid.sub(left), mid, left); diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index 4841044671659..de6e6d52b3625 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -748,7 +748,7 @@ generate_pattern_iterators! { } impl<'a, P: Pattern<'a>> Split<'a, P> { - /// Returns remainder of the splitted string + /// Returns remainder of the split string /// /// # Examples /// @@ -769,7 +769,7 @@ impl<'a, P: Pattern<'a>> Split<'a, P> { } impl<'a, P: Pattern<'a>> RSplit<'a, P> { - /// Returns remainder of the splitted string + /// Returns remainder of the split string /// /// # Examples /// @@ -808,7 +808,7 @@ generate_pattern_iterators! { } impl<'a, P: Pattern<'a>> SplitTerminator<'a, P> { - /// Returns remainder of the splitted string + /// Returns remainder of the split string /// /// # Examples /// @@ -829,7 +829,7 @@ impl<'a, P: Pattern<'a>> SplitTerminator<'a, P> { } impl<'a, P: Pattern<'a>> RSplitTerminator<'a, P> { - /// Returns remainder of the splitted string + /// Returns remainder of the split string /// /// # Examples /// @@ -931,7 +931,7 @@ generate_pattern_iterators! { } impl<'a, P: Pattern<'a>> SplitN<'a, P> { - /// Returns remainder of the splitted string + /// Returns remainder of the split string /// /// # Examples /// @@ -952,7 +952,7 @@ impl<'a, P: Pattern<'a>> SplitN<'a, P> { } impl<'a, P: Pattern<'a>> RSplitN<'a, P> { - /// Returns remainder of the splitted string + /// Returns remainder of the split string /// /// # Examples /// @@ -1236,7 +1236,7 @@ impl<'a> DoubleEndedIterator for SplitWhitespace<'a> { impl FusedIterator for SplitWhitespace<'_> {} impl<'a> SplitWhitespace<'a> { - /// Returns remainder of the splitted string + /// Returns remainder of the split string /// /// # Examples /// @@ -1292,7 +1292,7 @@ impl<'a> DoubleEndedIterator for SplitAsciiWhitespace<'a> { impl FusedIterator for SplitAsciiWhitespace<'_> {} impl<'a> SplitAsciiWhitespace<'a> { - /// Returns remainder of the splitted string + /// Returns remainder of the split string /// /// # 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>> SplitInclusive<'a, P> { - /// Returns remainder of the splitted string + /// Returns remainder of the split string /// /// # Examples /// diff --git a/library/core/tests/array.rs b/library/core/tests/array.rs index ceb6720079665..fe4fef749904e 100644 --- a/library/core/tests/array.rs +++ b/library/core/tests/array.rs @@ -259,7 +259,7 @@ fn iterator_drops() { // 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 // be automagically skipped on unsuitable targets, such as -// wasm32-unknown-unkown. +// wasm32-unknown-unknown. // // It means that we use panic for indicating success. #[test] diff --git a/library/panic_unwind/src/emcc.rs b/library/panic_unwind/src/emcc.rs index e428f2fdaaa39..12f0fe9c3c3a9 100644 --- a/library/panic_unwind/src/emcc.rs +++ b/library/panic_unwind/src/emcc.rs @@ -49,7 +49,7 @@ static EXCEPTION_TYPE_INFO: TypeInfo = TypeInfo { }; 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 // another thread. caught: AtomicBool, diff --git a/library/std/src/fs/tests.rs b/library/std/src/fs/tests.rs index 9a8f1e44f1f1c..2293fb6b55812 100644 --- a/library/std/src/fs/tests.rs +++ b/library/std/src/fs/tests.rs @@ -1369,7 +1369,7 @@ fn symlink_hard_link() { // "hard_link" should appear as a 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"))); assert!(fs::File::open(tmpdir.join("file.renamed")).is_err()); let _ = check!(fs::File::open(tmpdir.join("symlink"))); diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs index dd182c059b9cb..ecc9e91b6bdb2 100644 --- a/library/std/src/io/mod.rs +++ b/library/std/src/io/mod.rs @@ -362,7 +362,7 @@ pub(crate) fn default_read_to_end(r: &mut R, buf: &mut Vec let start_len = buf.len(); 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 { if buf.len() == buf.capacity() { buf.reserve(32); // buf is full, need more space @@ -370,7 +370,7 @@ pub(crate) fn default_read_to_end(r: &mut R, buf: &mut Vec 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 { read_buf.assume_init(initialized); } diff --git a/library/std/src/io/stdio.rs b/library/std/src/io/stdio.rs index 9888d3a09c48d..c072f0cafe47b 100644 --- a/library/std/src/io/stdio.rs +++ b/library/std/src/io/stdio.rs @@ -1179,7 +1179,7 @@ where }) }) == Ok(Some(())) { - // Succesfully wrote to capture buffer. + // Successfully wrote to capture buffer. return; } diff --git a/library/std/src/net/ip/tests.rs b/library/std/src/net/ip/tests.rs index 17581f330266d..632d4683b4159 100644 --- a/library/std/src/net/ip/tests.rs +++ b/library/std/src/net/ip/tests.rs @@ -749,7 +749,7 @@ fn ipv4_from_constructors() { } #[test] -fn ipv6_from_contructors() { +fn ipv6_from_constructors() { assert_eq!(Ipv6Addr::LOCALHOST, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); assert!(Ipv6Addr::LOCALHOST.is_loopback()); assert_eq!(Ipv6Addr::UNSPECIFIED, Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)); diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs index 6fc6b8daec0a6..87854fe4f2970 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -365,7 +365,7 @@ pub unsafe fn r#try R>(f: F) -> Result> // The call to `intrinsics::r#try` is made safe by: // - `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. - // See their safety preconditions for more informations + // See their safety preconditions for more information unsafe { return if intrinsics::r#try(do_call::, data_ptr, do_catch::) == 0 { Ok(ManuallyDrop::into_inner(data.r)) @@ -398,7 +398,7 @@ pub unsafe fn r#try R>(f: F) -> Result> // expects normal function pointers. #[inline] fn do_call 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 { let data = data as *mut Data; let data = &mut (*data); @@ -420,7 +420,7 @@ pub unsafe fn r#try R>(f: F) -> Result> // expects normal function pointers. #[inline] fn do_catch 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 // on `obj` being the correct thing to pass to `data.p` (after wrapping diff --git a/library/std/src/sys/itron/thread.rs b/library/std/src/sys/itron/thread.rs index bb9fa54d02ea4..ebcc9ab26e088 100644 --- a/library/std/src/sys/itron/thread.rs +++ b/library/std/src/sys/itron/thread.rs @@ -126,7 +126,7 @@ impl Thread { // In this case, `inner`'s ownership has been moved to us, // And we are responsible for dropping it. The acquire // 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`. // Safety: See above. let _ = unsafe { Box::from_raw(inner as *const _ as *mut ThreadInner) }; @@ -264,7 +264,7 @@ impl Drop for Thread { // one will ever join it. // The ownership of `self.inner` is moved to the child thread. // 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`. } LIFECYCLE_FINISHED => { diff --git a/library/std/src/sys/unix/kernel_copy.rs b/library/std/src/sys/unix/kernel_copy.rs index 241cf89d3145c..e85e4c5d618ce 100644 --- a/library/std/src/sys/unix/kernel_copy.rs +++ b/library/std/src/sys/unix/kernel_copy.rs @@ -104,7 +104,7 @@ impl FdMeta { fn potential_sendfile_source(&self) -> bool { 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 // thus there would be benefit from attempting sendfile FdMeta::Metadata(meta) diff --git a/library/std/src/sys/unix/process/process_fuchsia.rs b/library/std/src/sys/unix/process/process_fuchsia.rs index 507abb27871bf..ce77c210a6220 100644 --- a/library/std/src/sys/unix/process/process_fuchsia.rs +++ b/library/std/src/sys/unix/process/process_fuchsia.rs @@ -284,7 +284,7 @@ impl ExitStatus { // // 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 - // 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 // necessarily fit. // diff --git a/library/std/src/sys/unix/weak.rs b/library/std/src/sys/unix/weak.rs index 32072affe8af4..55719b87c7e06 100644 --- a/library/std/src/sys/unix/weak.rs +++ b/library/std/src/sys/unix/weak.rs @@ -124,7 +124,7 @@ impl DlsymWeak { } } - // Cold because it should only happen during first-time initalization. + // Cold because it should only happen during first-time initialization. #[cold] unsafe fn initialize(&self) -> Option { assert_eq!(mem::size_of::(), mem::size_of::()); diff --git a/library/std/src/sys/wasm/alloc.rs b/library/std/src/sys/wasm/alloc.rs index 3223e8941024c..6dceb1689a8b7 100644 --- a/library/std/src/sys/wasm/alloc.rs +++ b/library/std/src/sys/wasm/alloc.rs @@ -24,7 +24,7 @@ static mut DLMALLOC: dlmalloc::Dlmalloc = dlmalloc::Dlmalloc::new(); unsafe impl GlobalAlloc for System { #[inline] 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. let _lock = lock::lock(); unsafe { DLMALLOC.malloc(layout.size(), layout.align()) } @@ -32,7 +32,7 @@ unsafe impl GlobalAlloc for System { #[inline] 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. let _lock = lock::lock(); unsafe { DLMALLOC.calloc(layout.size(), layout.align()) } @@ -40,7 +40,7 @@ unsafe impl GlobalAlloc for System { #[inline] 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. let _lock = lock::lock(); unsafe { DLMALLOC.free(ptr, layout.size(), layout.align()) } @@ -48,7 +48,7 @@ unsafe impl GlobalAlloc for System { #[inline] 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. let _lock = lock::lock(); unsafe { DLMALLOC.realloc(ptr, layout.size(), layout.align(), new_size) } diff --git a/library/std/src/sys/wasm/atomics/mutex.rs b/library/std/src/sys/wasm/atomics/mutex.rs index 5ff0ec052b6f4..3a09f0bf9bb4c 100644 --- a/library/std/src/sys/wasm/atomics/mutex.rs +++ b/library/std/src/sys/wasm/atomics/mutex.rs @@ -73,7 +73,7 @@ pub struct ReentrantMutex { unsafe impl Send 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 // 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 @@ -96,7 +96,7 @@ impl ReentrantMutex { pub unsafe fn lock(&self) { let me = thread::my_id(); 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) }; debug_assert!(val == 0 || val == 1); } @@ -136,7 +136,7 @@ impl ReentrantMutex { match *self.recursions.get() { 0 => { 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 { wasm32::memory_atomic_notify(self.ptr() as *mut i32, 1); } // wake up one waiter, if any diff --git a/library/std/src/sys/windows/stdio.rs b/library/std/src/sys/windows/stdio.rs index a4fe5f67f699a..eb0925b3fda7d 100644 --- a/library/std/src/sys/windows/stdio.rs +++ b/library/std/src/sys/windows/stdio.rs @@ -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 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 utf8 = match str::from_utf8(&data[..len]) { Ok(s) => s, diff --git a/library/std/src/sys/windows/thread_parker.rs b/library/std/src/sys/windows/thread_parker.rs index 4f59d4dd452be..5a8011a958808 100644 --- a/library/std/src/sys/windows/thread_parker.rs +++ b/library/std/src/sys/windows/thread_parker.rs @@ -22,7 +22,7 @@ // // Unlike WaitOnAddress, NtWaitForKeyedEvent/NtReleaseKeyedEvent operate on a // 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 // 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. diff --git a/library/std/src/sys_common/thread_parker/generic.rs b/library/std/src/sys_common/thread_parker/generic.rs index 14cfa958e5e53..d99e901bb5f83 100644 --- a/library/std/src/sys_common/thread_parker/generic.rs +++ b/library/std/src/sys_common/thread_parker/generic.rs @@ -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::Ordering::SeqCst; @@ -20,7 +20,7 @@ impl Parker { 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. pub unsafe fn park(&self) { // 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. pub unsafe fn park_timeout(&self, dur: Duration) { // Like `park` above we have a fast path for an already-notified thread, and diff --git a/library/std/src/thread/local.rs b/library/std/src/thread/local.rs index c03fe116320aa..1d2f6e976800b 100644 --- a/library/std/src/thread/local.rs +++ b/library/std/src/thread/local.rs @@ -582,7 +582,7 @@ pub mod fast { 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 // free `register_dtor` function defined elsewhere in libstd. 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 T>(&self, init: F) -> Option<&'static T> { // 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 inner cell or the inner T when this is called. diff --git a/library/std/src/time.rs b/library/std/src/time.rs index a5e3bd0c29030..86cc93c445376 100644 --- a/library/std/src/time.rs +++ b/library/std/src/time.rs @@ -273,7 +273,7 @@ impl Instant { // While issues have been seen on arm64 platforms the Arm architecture // requires that the counter monotonically increases and that it must // 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 // 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 From 4f4b2c7271d3090b6b63bf1ce8373a47b5b30d86 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Wed, 15 Dec 2021 00:11:23 +0800 Subject: [PATCH 4/7] Constify `bool::then{,_some}` --- library/core/src/bool.rs | 13 +++++++++++-- library/core/tests/bool.rs | 14 ++++++++++++++ library/core/tests/lib.rs | 1 + 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/library/core/src/bool.rs b/library/core/src/bool.rs index f14c2a4641627..d5119d0b7c328 100644 --- a/library/core/src/bool.rs +++ b/library/core/src/bool.rs @@ -14,8 +14,12 @@ impl bool { /// assert_eq!(true.then_some(0), Some(0)); /// ``` #[unstable(feature = "bool_to_option", issue = "80967")] + #[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")] #[inline] - pub fn then_some(self, t: T) -> Option { + pub const fn then_some(self, t: T) -> Option + where + T: ~const Drop, + { if self { Some(t) } else { None } } @@ -29,8 +33,13 @@ impl bool { /// assert_eq!(true.then(|| 0), Some(0)); /// ``` #[stable(feature = "lazy_bool_to_option", since = "1.50.0")] + #[rustc_const_unstable(feature = "const_bool_to_option", issue = "91917")] #[inline] - pub fn then T>(self, f: F) -> Option { + pub const fn then(self, f: F) -> Option + where + F: ~const FnOnce() -> T, + F: ~const Drop, + { if self { Some(f()) } else { None } } } diff --git a/library/core/tests/bool.rs b/library/core/tests/bool.rs index e40f0482aee3e..4819ce911d618 100644 --- a/library/core/tests/bool.rs +++ b/library/core/tests/bool.rs @@ -88,4 +88,18 @@ fn test_bool_to_option() { assert_eq!(true.then_some(0), Some(0)); assert_eq!(false.then(|| 0), None); assert_eq!(true.then(|| 0), Some(0)); + + const fn zero() -> i32 { + 0 + } + + const A: Option = false.then_some(0); + const B: Option = true.then_some(0); + const C: Option = false.then(zero); + const D: Option = true.then(zero); + + assert_eq!(A, None); + assert_eq!(B, Some(0)); + assert_eq!(C, None); + assert_eq!(D, Some(0)); } diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index b41d3e09df876..dacb33619f8c3 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -8,6 +8,7 @@ #![feature(cfg_panic)] #![feature(cfg_target_has_atomic)] #![feature(const_assume)] +#![feature(const_bool_to_option)] #![feature(const_cell_into_inner)] #![feature(const_convert)] #![feature(const_maybe_uninit_as_mut_ptr)] From 4d1d66b812efe27cc460921fcc6b24622444800d Mon Sep 17 00:00:00 2001 From: Aaron Hill Date: Tue, 14 Dec 2021 11:27:41 -0500 Subject: [PATCH 5/7] Use `tcx.def_path_hash` in `ExistentialPredicate.stable_cmp` This avoids a needless query invocation --- compiler/rustc_middle/src/ty/sty.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index a80fe6a3362b4..1c525fb55e1b5 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -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)) } (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, (Projection(_), Trait(_)) => Ordering::Greater, From f29fb4792b1fa344817d95e997ef8de4befee302 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 13 Dec 2021 21:22:02 -0800 Subject: [PATCH 6/7] Make TyS::is_suggestable more structual --- compiler/rustc_middle/src/ty/diagnostics.rs | 64 ++++++++++++++++--- .../defaults-in-other-trait-items.rs | 1 + .../defaults-in-other-trait-items.stderr | 6 +- .../default-match-bindings-forbidden.stderr | 4 +- .../tuple_destructure_fail.stderr | 8 +-- ...sive_range_pattern_syntax_collision.stderr | 2 - ...ive_range_pattern_syntax_collision2.stderr | 2 - ...ive_range_pattern_syntax_collision3.stderr | 6 -- .../pat-tuple-5.stderr | 2 - src/test/ui/issues/issue-11844.stderr | 2 - src/test/ui/issues/issue-12552.stderr | 5 -- src/test/ui/issues/issue-13466.stderr | 5 -- src/test/ui/issues/issue-3680.stderr | 2 - src/test/ui/issues/issue-66706.stderr | 6 +- src/test/ui/issues/issue-72574-1.stderr | 2 - src/test/ui/mismatched_types/E0409.stderr | 2 - src/test/ui/mut/mut-pattern-mismatched.stderr | 6 -- .../diverging-tuple-parts-39485.stderr | 6 +- .../ui/or-patterns/already-bound-name.stderr | 5 +- .../ui/or-patterns/inconsistent-modes.stderr | 5 +- src/test/ui/pattern/issue-74702.stderr | 4 +- .../ui/pattern/pat-tuple-overfield.stderr | 5 -- src/test/ui/return/return-type.stderr | 14 ++-- .../disallowed-positions.stderr | 8 ++- ...ghtly-nice-generic-literal-messages.stderr | 2 - ...structure-constructor-type-mismatch.stderr | 6 -- ...e-57673-ice-on-deref-of-boxed-trait.stderr | 2 +- src/test/ui/typeck/issue-91334.stderr | 2 +- .../typeck/return_type_containing_closure.rs | 10 +++ .../return_type_containing_closure.stderr | 17 +++++ 30 files changed, 112 insertions(+), 99 deletions(-) create mode 100644 src/test/ui/typeck/return_type_containing_closure.rs create mode 100644 src/test/ui/typeck/return_type_containing_closure.stderr diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index 1acb3ec57dea6..ee00f6c62f345 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -1,7 +1,12 @@ //! Diagnostics related methods for `TyS`. +use crate::ty::subst::{GenericArg, GenericArgKind}; 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_hir as hir; use rustc_hir::def_id::DefId; @@ -63,16 +68,55 @@ impl<'tcx> TyS<'tcx> { /// Whether the type can be safely suggested during error recovery. pub fn is_suggestable(&self) -> bool { - !matches!( - self.kind(), + fn generic_arg_is_suggestible(arg: GenericArg<'_>) -> bool { + 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(..) - | FnDef(..) - | FnPtr(..) - | Dynamic(..) - | Closure(..) - | Infer(..) - | Projection(..) - ) + | FnDef(..) + | Closure(..) + | Infer(..) + | 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, + } } } diff --git a/src/test/ui/associated-types/defaults-in-other-trait-items.rs b/src/test/ui/associated-types/defaults-in-other-trait-items.rs index 4014f46285d70..505751969b623 100644 --- a/src/test/ui/associated-types/defaults-in-other-trait-items.rs +++ b/src/test/ui/associated-types/defaults-in-other-trait-items.rs @@ -10,6 +10,7 @@ trait Tr { //~^ ERROR mismatched types //~| NOTE expected associated type, found `()` //~| NOTE expected associated type `::A` + //~| NOTE this expression has type `::A` } } diff --git a/src/test/ui/associated-types/defaults-in-other-trait-items.stderr b/src/test/ui/associated-types/defaults-in-other-trait-items.stderr index 493df30a64daf..71d421926e702 100644 --- a/src/test/ui/associated-types/defaults-in-other-trait-items.stderr +++ b/src/test/ui/associated-types/defaults-in-other-trait-items.stderr @@ -5,13 +5,15 @@ LL | type A = (); | ------------ associated type defaults can't be assumed inside the trait defining them ... LL | let () = p; - | ^^ expected associated type, found `()` + | ^^ - this expression has type `::A` + | | + | expected associated type, found `()` | = note: expected associated type `::A` found unit type `()` 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; | ------------- associated type defaults can't be assumed inside the trait defining them diff --git a/src/test/ui/destructuring-assignment/default-match-bindings-forbidden.stderr b/src/test/ui/destructuring-assignment/default-match-bindings-forbidden.stderr index e6161fdfa2441..9ea78bd097485 100644 --- a/src/test/ui/destructuring-assignment/default-match-bindings-forbidden.stderr +++ b/src/test/ui/destructuring-assignment/default-match-bindings-forbidden.stderr @@ -2,9 +2,7 @@ error[E0308]: mismatched types --> $DIR/default-match-bindings-forbidden.rs:6:5 | LL | (x, y) = &(1, 2); - | ^^^^^^ ------- this expression has type `&({integer}, {integer})` - | | - | expected reference, found tuple + | ^^^^^^ expected reference, found tuple | = note: expected type `&({integer}, {integer})` found tuple `(_, _)` diff --git a/src/test/ui/destructuring-assignment/tuple_destructure_fail.stderr b/src/test/ui/destructuring-assignment/tuple_destructure_fail.stderr index 1146b88278d49..79ac15187665b 100644 --- a/src/test/ui/destructuring-assignment/tuple_destructure_fail.stderr +++ b/src/test/ui/destructuring-assignment/tuple_destructure_fail.stderr @@ -10,9 +10,7 @@ error[E0308]: mismatched types --> $DIR/tuple_destructure_fail.rs:8:5 | 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})` found tuple `(_, _, _)` @@ -29,9 +27,7 @@ error[E0308]: mismatched types --> $DIR/tuple_destructure_fail.rs:10:5 | 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})` found tuple `(_,)` diff --git a/src/test/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision.stderr b/src/test/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision.stderr index a6f8563a04785..241485db49bc9 100644 --- a/src/test/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision.stderr +++ b/src/test/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision.stderr @@ -1,8 +1,6 @@ error[E0308]: mismatched types --> $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.., _] => {}, | ^^ expected struct `std::ops::Range`, found integer | diff --git a/src/test/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision2.stderr b/src/test/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision2.stderr index 4e0102c930da8..777d029d7dd7b 100644 --- a/src/test/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision2.stderr +++ b/src/test/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision2.stderr @@ -7,8 +7,6 @@ LL | [_, 99..] => {}, error[E0308]: mismatched types --> $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..] => {}, | ^^ expected struct `std::ops::Range`, found integer | diff --git a/src/test/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision3.stderr b/src/test/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision3.stderr index 665eef2fcb96c..6119733a7d84b 100644 --- a/src/test/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision3.stderr +++ b/src/test/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision3.stderr @@ -1,8 +1,6 @@ error[E0308]: mismatched types --> $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, _] => {}, | ^ expected struct `std::ops::Range`, found integer | @@ -12,8 +10,6 @@ LL | [..9, 99..100, _] => {}, error[E0308]: mismatched types --> $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, _] => {}, | ^^ --- this is of type `{integer}` | | @@ -25,8 +21,6 @@ LL | [..9, 99..100, _] => {}, error[E0308]: mismatched types --> $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, _] => {}, | -- ^^^ expected struct `std::ops::Range`, found integer | | diff --git a/src/test/ui/half-open-range-patterns/pat-tuple-5.stderr b/src/test/ui/half-open-range-patterns/pat-tuple-5.stderr index 307ad711b74d9..31ea3a17871a5 100644 --- a/src/test/ui/half-open-range-patterns/pat-tuple-5.stderr +++ b/src/test/ui/half-open-range-patterns/pat-tuple-5.stderr @@ -1,8 +1,6 @@ error[E0308]: mismatched types --> $DIR/pat-tuple-5.rs:8:10 | -LL | match (0, 1) { - | ------ this expression has type `({integer}, {integer})` LL | (PAT ..) => {} | ^^^ expected tuple, found `u8` | diff --git a/src/test/ui/issues/issue-11844.stderr b/src/test/ui/issues/issue-11844.stderr index 9d7470e7af9aa..ecab1074a295f 100644 --- a/src/test/ui/issues/issue-11844.stderr +++ b/src/test/ui/issues/issue-11844.stderr @@ -1,8 +1,6 @@ error[E0308]: mismatched types --> $DIR/issue-11844.rs:6:9 | -LL | match a { - | - this expression has type `Option>` LL | Ok(a) => | ^^^^^ expected enum `Option`, found enum `Result` | diff --git a/src/test/ui/issues/issue-12552.stderr b/src/test/ui/issues/issue-12552.stderr index 3d8852ca748af..1ba6852b17c06 100644 --- a/src/test/ui/issues/issue-12552.stderr +++ b/src/test/ui/issues/issue-12552.stderr @@ -1,8 +1,6 @@ error[E0308]: mismatched types --> $DIR/issue-12552.rs:6:5 | -LL | match t { - | - this expression has type `Result<_, {integer}>` LL | Some(k) => match k { | ^^^^^^^ expected enum `Result`, found enum `Option` | @@ -12,9 +10,6 @@ LL | Some(k) => match k { error[E0308]: mismatched types --> $DIR/issue-12552.rs:9:5 | -LL | match t { - | - this expression has type `Result<_, {integer}>` -... LL | None => () | ^^^^ expected enum `Result`, found enum `Option` | diff --git a/src/test/ui/issues/issue-13466.stderr b/src/test/ui/issues/issue-13466.stderr index c78466f4e8ce1..15ee49a5fdd25 100644 --- a/src/test/ui/issues/issue-13466.stderr +++ b/src/test/ui/issues/issue-13466.stderr @@ -1,8 +1,6 @@ error[E0308]: mismatched types --> $DIR/issue-13466.rs:8:9 | -LL | let _x: usize = match Some(1) { - | ------- this expression has type `Option<{integer}>` LL | Ok(u) => u, | ^^^^^ expected enum `Option`, found enum `Result` | @@ -12,9 +10,6 @@ LL | Ok(u) => u, error[E0308]: mismatched types --> $DIR/issue-13466.rs:14:9 | -LL | let _x: usize = match Some(1) { - | ------- this expression has type `Option<{integer}>` -... LL | Err(e) => panic!(e) | ^^^^^^ expected enum `Option`, found enum `Result` | diff --git a/src/test/ui/issues/issue-3680.stderr b/src/test/ui/issues/issue-3680.stderr index e8fafa76b919b..8dc0dfa2356f4 100644 --- a/src/test/ui/issues/issue-3680.stderr +++ b/src/test/ui/issues/issue-3680.stderr @@ -1,8 +1,6 @@ error[E0308]: mismatched types --> $DIR/issue-3680.rs:3:9 | -LL | match None { - | ---- this expression has type `Option<_>` LL | Err(_) => () | ^^^^^^ expected enum `Option`, found enum `Result` | diff --git a/src/test/ui/issues/issue-66706.stderr b/src/test/ui/issues/issue-66706.stderr index f0b93ac91111a..3e933a0f01b75 100644 --- a/src/test/ui/issues/issue-66706.stderr +++ b/src/test/ui/issues/issue-66706.stderr @@ -36,7 +36,7 @@ error[E0308]: mismatched types --> $DIR/issue-66706.rs:2:5 | LL | fn a() { - | - help: try adding a return type: `-> [{integer}; _]` + | - possibly return type missing here? LL | [0; [|_: _ &_| ()].len()] | ^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found array `[{integer}; _]` @@ -44,7 +44,7 @@ error[E0308]: mismatched types --> $DIR/issue-66706.rs:14:5 | LL | fn c() { - | - help: try adding a return type: `-> [{integer}; _]` + | - possibly return type missing here? LL | [0; [|&_: _ &_| {}; 0 ].len()] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found array `[{integer}; _]` @@ -52,7 +52,7 @@ error[E0308]: mismatched types --> $DIR/issue-66706.rs:20:5 | LL | fn d() { - | - help: try adding a return type: `-> [{integer}; _]` + | - possibly return type missing here? LL | [0; match [|f @ &ref _| () ] {} ] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `()`, found array `[{integer}; _]` diff --git a/src/test/ui/issues/issue-72574-1.stderr b/src/test/ui/issues/issue-72574-1.stderr index 653869a237d88..5d3d390a95ded 100644 --- a/src/test/ui/issues/issue-72574-1.stderr +++ b/src/test/ui/issues/issue-72574-1.stderr @@ -21,8 +21,6 @@ LL | (_a, _x @ ..) => {} error[E0308]: mismatched types --> $DIR/issue-72574-1.rs:4:9 | -LL | match x { - | - this expression has type `({integer}, {integer}, {integer})` LL | (_a, _x @ ..) => {} | ^^^^^^^^^^^^^ expected a tuple with 3 elements, found one with 2 elements | diff --git a/src/test/ui/mismatched_types/E0409.stderr b/src/test/ui/mismatched_types/E0409.stderr index ef03b67b1b0b1..eb884bcc6226f 100644 --- a/src/test/ui/mismatched_types/E0409.stderr +++ b/src/test/ui/mismatched_types/E0409.stderr @@ -9,8 +9,6 @@ LL | (0, ref y) | (y, 0) => {} error[E0308]: mismatched types --> $DIR/E0409.rs:5:23 | -LL | match x { - | - this expression has type `({integer}, {integer})` LL | (0, ref y) | (y, 0) => {} | ----- ^ expected `&{integer}`, found integer | | diff --git a/src/test/ui/mut/mut-pattern-mismatched.stderr b/src/test/ui/mut/mut-pattern-mismatched.stderr index cad1cef5155d5..ccc8ac1278c63 100644 --- a/src/test/ui/mut/mut-pattern-mismatched.stderr +++ b/src/test/ui/mut/mut-pattern-mismatched.stderr @@ -3,9 +3,6 @@ error[E0308]: mismatched types | LL | let &_ | ^^ types differ in mutability -... -LL | = foo; - | --- this expression has type `&mut {integer}` | = note: expected mutable reference `&mut {integer}` found reference `&_` @@ -15,9 +12,6 @@ error[E0308]: mismatched types | LL | let &mut _ | ^^^^^^ types differ in mutability -... -LL | = bar; - | --- this expression has type `&{integer}` | = note: expected reference `&{integer}` found mutable reference `&mut _` diff --git a/src/test/ui/never_type/diverging-tuple-parts-39485.stderr b/src/test/ui/never_type/diverging-tuple-parts-39485.stderr index 32967b376ca9c..e99a38aaaee95 100644 --- a/src/test/ui/never_type/diverging-tuple-parts-39485.stderr +++ b/src/test/ui/never_type/diverging-tuple-parts-39485.stderr @@ -1,15 +1,13 @@ error[E0308]: mismatched types --> $DIR/diverging-tuple-parts-39485.rs:8:5 | +LL | fn g() { + | - possibly return type missing here? LL | &panic!() | ^^^^^^^^^ expected `()`, found reference | = note: expected unit type `()` found reference `&_` -help: try adding a return type - | -LL | fn g() -> &_ { - | +++++ help: consider removing the borrow | LL - &panic!() diff --git a/src/test/ui/or-patterns/already-bound-name.stderr b/src/test/ui/or-patterns/already-bound-name.stderr index 66112165622b9..92416a0d5cbf0 100644 --- a/src/test/ui/or-patterns/already-bound-name.stderr +++ b/src/test/ui/or-patterns/already-bound-name.stderr @@ -86,9 +86,8 @@ error[E0308]: mismatched types --> $DIR/already-bound-name.rs:30:32 | LL | let (B(A(a, _) | B(a)) | A(a, A(a, _) | B(a))) = B(B(1)); - | - ^ ------- this expression has type `E>` - | | | - | | expected integer, found enum `E` + | - ^ expected integer, found enum `E` + | | | first introduced with type `{integer}` here | = note: expected type `{integer}` diff --git a/src/test/ui/or-patterns/inconsistent-modes.stderr b/src/test/ui/or-patterns/inconsistent-modes.stderr index dae6bb41e74e2..95e8618808c08 100644 --- a/src/test/ui/or-patterns/inconsistent-modes.stderr +++ b/src/test/ui/or-patterns/inconsistent-modes.stderr @@ -65,9 +65,8 @@ error[E0308]: mismatched types --> $DIR/inconsistent-modes.rs:13:32 | 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 | = note: expected type `&{integer}` diff --git a/src/test/ui/pattern/issue-74702.stderr b/src/test/ui/pattern/issue-74702.stderr index f2e2c8f021bad..53dcf97f81c6a 100644 --- a/src/test/ui/pattern/issue-74702.stderr +++ b/src/test/ui/pattern/issue-74702.stderr @@ -22,9 +22,7 @@ error[E0308]: mismatched types --> $DIR/issue-74702.rs:2:9 | 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})` found tuple `(_,)` diff --git a/src/test/ui/pattern/pat-tuple-overfield.stderr b/src/test/ui/pattern/pat-tuple-overfield.stderr index 1c44f7e5f6f1f..64b6e5eec5562 100644 --- a/src/test/ui/pattern/pat-tuple-overfield.stderr +++ b/src/test/ui/pattern/pat-tuple-overfield.stderr @@ -150,8 +150,6 @@ LL | E1::Z0 => {} error[E0308]: mismatched types --> $DIR/pat-tuple-overfield.rs:19:9 | -LL | match (1, 2, 3) { - | --------- this expression has type `({integer}, {integer}, {integer})` LL | (1, 2, 3, 4) => {} | ^^^^^^^^^^^^ expected a tuple with 3 elements, found one with 4 elements | @@ -161,9 +159,6 @@ LL | (1, 2, 3, 4) => {} error[E0308]: mismatched types --> $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) => {} | ^^^^^^^^^^^^^^^^ expected a tuple with 3 elements, found one with 4 elements | diff --git a/src/test/ui/return/return-type.stderr b/src/test/ui/return/return-type.stderr index 5af136e601123..f86209a651d13 100644 --- a/src/test/ui/return/return-type.stderr +++ b/src/test/ui/return/return-type.stderr @@ -1,19 +1,15 @@ error[E0308]: mismatched types --> $DIR/return-type.rs:10:5 | +LL | fn bar() { + | - possibly return type missing here? LL | foo(4 as usize) - | ^^^^^^^^^^^^^^^ expected `()`, found struct `S` + | ^^^^^^^^^^^^^^^- help: consider using a semicolon here: `;` + | | + | expected `()`, found struct `S` | = note: expected unit type `()` found struct `S` -help: consider using a semicolon here - | -LL | foo(4 as usize); - | + -help: try adding a return type - | -LL | fn bar() -> S { - | +++++++++++ error: aborting due to previous error diff --git a/src/test/ui/rfc-2497-if-let-chains/disallowed-positions.stderr b/src/test/ui/rfc-2497-if-let-chains/disallowed-positions.stderr index 3fc5cb1b07973..1433a16d7274a 100644 --- a/src/test/ui/rfc-2497-if-let-chains/disallowed-positions.stderr +++ b/src/test/ui/rfc-2497-if-let-chains/disallowed-positions.stderr @@ -644,7 +644,9 @@ error[E0308]: mismatched types --> $DIR/disallowed-positions.rs:76:12 | 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` found struct `std::ops::Range<_>` @@ -832,7 +834,9 @@ error[E0308]: mismatched types --> $DIR/disallowed-positions.rs:140:15 | 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` found struct `std::ops::Range<_>` diff --git a/src/test/ui/slightly-nice-generic-literal-messages.stderr b/src/test/ui/slightly-nice-generic-literal-messages.stderr index 14f01f0ebdf73..61eabed950423 100644 --- a/src/test/ui/slightly-nice-generic-literal-messages.stderr +++ b/src/test/ui/slightly-nice-generic-literal-messages.stderr @@ -1,8 +1,6 @@ error[E0308]: mismatched types --> $DIR/slightly-nice-generic-literal-messages.rs:7:9 | -LL | match Foo(1.1, marker::PhantomData) { - | ----------------------------- this expression has type `Foo<{float}, _>` LL | 1 => {} | ^ expected struct `Foo`, found integer | diff --git a/src/test/ui/structs/structure-constructor-type-mismatch.stderr b/src/test/ui/structs/structure-constructor-type-mismatch.stderr index 3d64fc601df98..98972a1215996 100644 --- a/src/test/ui/structs/structure-constructor-type-mismatch.stderr +++ b/src/test/ui/structs/structure-constructor-type-mismatch.stderr @@ -101,8 +101,6 @@ LL | type PointF = Point; error[E0308]: mismatched types --> $DIR/structure-constructor-type-mismatch.rs:54:9 | -LL | match (Point { x: 1, y: 2 }) { - | ---------------------- this expression has type `Point<{integer}>` LL | PointF:: { .. } => {} | ^^^^^^^^^^^^^^^^^^^^ expected integer, found `f32` | @@ -112,8 +110,6 @@ LL | PointF:: { .. } => {} error[E0308]: mismatched types --> $DIR/structure-constructor-type-mismatch.rs:59:9 | -LL | match (Point { x: 1, y: 2 }) { - | ---------------------- this expression has type `Point<{integer}>` LL | PointF { .. } => {} | ^^^^^^^^^^^^^ expected integer, found `f32` | @@ -123,8 +119,6 @@ LL | PointF { .. } => {} error[E0308]: mismatched types --> $DIR/structure-constructor-type-mismatch.rs:67:9 | -LL | match (Pair { x: 1, y: 2 }) { - | --------------------- this expression has type `Pair<{integer}, {integer}>` LL | PairF:: { .. } => {} | ^^^^^^^^^^^^^^^^^^^ expected integer, found `f32` | diff --git a/src/test/ui/typeck/issue-57673-ice-on-deref-of-boxed-trait.stderr b/src/test/ui/typeck/issue-57673-ice-on-deref-of-boxed-trait.stderr index b4d7dfe06be54..b92a6f2ec2b48 100644 --- a/src/test/ui/typeck/issue-57673-ice-on-deref-of-boxed-trait.stderr +++ b/src/test/ui/typeck/issue-57673-ice-on-deref-of-boxed-trait.stderr @@ -2,7 +2,7 @@ error[E0308]: mismatched types --> $DIR/issue-57673-ice-on-deref-of-boxed-trait.rs:5:5 | LL | fn ice(x: Box>) { - | - possibly return type missing here? + | - help: try adding a return type: `-> (dyn Iterator + 'static)` LL | *x | ^^ expected `()`, found trait object `dyn Iterator` | diff --git a/src/test/ui/typeck/issue-91334.stderr b/src/test/ui/typeck/issue-91334.stderr index 358cc771b7c45..0872e83ea2e7e 100644 --- a/src/test/ui/typeck/issue-91334.stderr +++ b/src/test/ui/typeck/issue-91334.stderr @@ -40,7 +40,7 @@ error[E0308]: mismatched types LL | fn f(){||yield(((){), | -^^^^^^^^^^^^^^^ 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 `()` found generator `[generator@$DIR/issue-91334.rs:10:8: 10:23]` diff --git a/src/test/ui/typeck/return_type_containing_closure.rs b/src/test/ui/typeck/return_type_containing_closure.rs new file mode 100644 index 0000000000000..aee9769b28038 --- /dev/null +++ b/src/test/ui/typeck/return_type_containing_closure.rs @@ -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() {} diff --git a/src/test/ui/typeck/return_type_containing_closure.stderr b/src/test/ui/typeck/return_type_containing_closure.stderr new file mode 100644 index 0000000000000..b08152d63318e --- /dev/null +++ b/src/test/ui/typeck/return_type_containing_closure.stderr @@ -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, [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`. From eaf39cbd9e37e705664dcf0e1ca1042913cf521a Mon Sep 17 00:00:00 2001 From: LegionMammal978 Date: Mon, 13 Dec 2021 21:52:35 -0500 Subject: [PATCH 7/7] Remove `in_band_lifetimes` from `rustc_codegen_ssa` See #91867 for more information. --- .../rustc_codegen_ssa/src/back/symbol_export.rs | 2 +- compiler/rustc_codegen_ssa/src/base.rs | 2 +- compiler/rustc_codegen_ssa/src/coverageinfo/map.rs | 14 +++++++------- .../rustc_codegen_ssa/src/debuginfo/type_names.rs | 6 +++--- compiler/rustc_codegen_ssa/src/lib.rs | 1 - compiler/rustc_codegen_ssa/src/mir/analyze.rs | 2 +- compiler/rustc_codegen_ssa/src/mir/operand.rs | 2 +- compiler/rustc_codegen_ssa/src/traits/type_.rs | 4 ++-- 8 files changed, 16 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs index f80f9965f4d8a..baafa74b13146 100644 --- a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs +++ b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs @@ -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) } -fn exported_symbols_provider_local( +fn exported_symbols_provider_local<'tcx>( tcx: TyCtxt<'tcx>, cnum: CrateNum, ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportLevel)] { diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index d82aa6915452b..1dac528481d8c 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -486,7 +486,7 @@ fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( pub fn codegen_crate( backend: B, - tcx: TyCtxt<'tcx>, + tcx: TyCtxt<'_>, target_cpu: String, metadata: EncodedMetadata, need_metadata_module: bool, diff --git a/compiler/rustc_codegen_ssa/src/coverageinfo/map.rs b/compiler/rustc_codegen_ssa/src/coverageinfo/map.rs index c1dfe1ef85600..1a6495cb15cf2 100644 --- a/compiler/rustc_codegen_ssa/src/coverageinfo/map.rs +++ b/compiler/rustc_codegen_ssa/src/coverageinfo/map.rs @@ -150,9 +150,9 @@ impl<'tcx> FunctionCoverage<'tcx> { /// Generate an array of CounterExpressions, and an iterator over all `Counter`s and their /// associated `Regions` (from which the LLVM-specific `CoverageMapGenerator` will create /// `CounterMappingRegion`s. - pub fn get_expressions_and_counter_regions<'a>( - &'a self, - ) -> (Vec, impl Iterator) { + pub fn get_expressions_and_counter_regions( + &self, + ) -> (Vec, impl Iterator) { assert!( self.source_hash != 0 || !self.is_used, "No counters provided the source_hash for used function: {:?}", @@ -168,7 +168,7 @@ impl<'tcx> FunctionCoverage<'tcx> { (counter_expressions, counter_regions) } - fn counter_regions<'a>(&'a self) -> impl Iterator { + fn counter_regions(&self) -> impl Iterator { self.counters.iter_enumerated().filter_map(|(index, entry)| { // 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. @@ -177,8 +177,8 @@ impl<'tcx> FunctionCoverage<'tcx> { } fn expressions_with_regions( - &'a self, - ) -> (Vec, impl Iterator) { + &self, + ) -> (Vec, impl Iterator) { let mut counter_expressions = 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()); @@ -336,7 +336,7 @@ impl<'tcx> FunctionCoverage<'tcx> { (counter_expressions, expression_regions.into_iter()) } - fn unreachable_regions<'a>(&'a self) -> impl Iterator { + fn unreachable_regions(&self) -> impl Iterator { self.unreachable_regions.iter().map(|region| (Counter::zero(), region)) } diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index ab119ae25f5e8..b03124769a06f 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -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 // debugger. For more information, look in `src/etc/natvis/intrinsic.natvis` and // `EnumMemberDescriptionFactor::create_member_descriptions`. - fn msvc_enum_fallback( + fn msvc_enum_fallback<'tcx>( tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, def: &AdtDef, @@ -496,7 +496,7 @@ pub fn compute_debuginfo_vtable_name<'tcx>( 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); if qualified { 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( - tcx: TyCtxt<'tcx>, + tcx: TyCtxt<'_>, def_id: DefId, disambiguated_data: DisambiguatedDefPathData, output: &mut String, diff --git a/compiler/rustc_codegen_ssa/src/lib.rs b/compiler/rustc_codegen_ssa/src/lib.rs index 4c87d4d896e2e..350199f4e98c2 100644 --- a/compiler/rustc_codegen_ssa/src/lib.rs +++ b/compiler/rustc_codegen_ssa/src/lib.rs @@ -2,7 +2,6 @@ #![feature(bool_to_option)] #![feature(box_patterns)] #![feature(try_blocks)] -#![feature(in_band_lifetimes)] #![feature(let_else)] #![feature(once_cell)] #![feature(nll)] diff --git a/compiler/rustc_codegen_ssa/src/mir/analyze.rs b/compiler/rustc_codegen_ssa/src/mir/analyze.rs index 0447c02fdecc4..b1b3f1d6d81b9 100644 --- a/compiler/rustc_codegen_ssa/src/mir/analyze.rs +++ b/compiler/rustc_codegen_ssa/src/mir/analyze.rs @@ -73,7 +73,7 @@ struct LocalAnalyzer<'mir, 'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> { locals: IndexVec, } -impl> 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) { let kind = &mut self.locals[local]; match *kind { diff --git a/compiler/rustc_codegen_ssa/src/mir/operand.rs b/compiler/rustc_codegen_ssa/src/mir/operand.rs index bea55bbc87965..0c526ff13f2ba 100644 --- a/compiler/rustc_codegen_ssa/src/mir/operand.rs +++ b/compiler/rustc_codegen_ssa/src/mir/operand.rs @@ -47,7 +47,7 @@ pub struct OperandRef<'tcx, V> { pub layout: TyAndLayout<'tcx>, } -impl fmt::Debug for OperandRef<'tcx, V> { +impl fmt::Debug for OperandRef<'_, V> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "OperandRef({:?} @ {:?})", self.val, self.layout) } diff --git a/compiler/rustc_codegen_ssa/src/traits/type_.rs b/compiler/rustc_codegen_ssa/src/traits/type_.rs index b94fb1e10db01..5d3f07317a37b 100644 --- a/compiler/rustc_codegen_ssa/src/traits/type_.rs +++ b/compiler/rustc_codegen_ssa/src/traits/type_.rs @@ -97,7 +97,7 @@ pub trait DerivedTypeMethods<'tcx>: BaseTypeMethods<'tcx> + MiscMethods<'tcx> { } } -impl 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> { 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> {} -impl TypeMethods<'tcx> for T where Self: DerivedTypeMethods<'tcx> + LayoutTypeMethods<'tcx> {} +impl<'tcx, T> TypeMethods<'tcx> for T where Self: DerivedTypeMethods<'tcx> + LayoutTypeMethods<'tcx> {}