diff --git a/Cargo.lock b/Cargo.lock index 7e4db4fdd53eb..e5b5543b367fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -512,6 +512,28 @@ dependencies = [ "windows-targets 0.52.4", ] +[[package]] +name = "chrono-tz" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93698b29de5e97ad0ae26447b344c482a7284c737d9ddc5f9e52b74a336671bb" +dependencies = [ + "chrono", + "chrono-tz-build", + "phf 0.11.2", +] + +[[package]] +name = "chrono-tz-build" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c088aee841df9c3041febbb73934cfc39708749bf96dc827e3359cd39ef11b1" +dependencies = [ + "parse-zoneinfo", + "phf 0.11.2", + "phf_codegen 0.11.2", +] + [[package]] name = "cipher" version = "0.4.4" @@ -2197,7 +2219,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c2a198fb6b0eada2a8df47933734e6d35d350665a33a3593d7164fa52c75c19" dependencies = [ "cfg-if", - "windows-targets 0.52.4", + "windows-targets 0.48.5", ] [[package]] @@ -2318,8 +2340,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a2629bb1404f3d34c2e921f21fd34ba00b206124c81f65c50b43b6aaefeb016" dependencies = [ "log", - "phf", - "phf_codegen", + "phf 0.10.1", + "phf_codegen 0.10.0", "string_cache", "string_cache_codegen", "tendril", @@ -2480,6 +2502,7 @@ version = "0.1.0" dependencies = [ "aes", "chrono", + "chrono-tz", "colored", "ctrlc", "directories", @@ -2835,6 +2858,15 @@ dependencies = [ "windows-targets 0.48.5", ] +[[package]] +name = "parse-zoneinfo" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f2a05b18d44e2957b88f96ba460715e295bc1d7510468a2f3d3b44535d26c24" +dependencies = [ + "regex", +] + [[package]] name = "pathdiff" version = "0.2.1" @@ -2907,7 +2939,16 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" dependencies = [ - "phf_shared", + "phf_shared 0.10.0", +] + +[[package]] +name = "phf" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" +dependencies = [ + "phf_shared 0.11.2", ] [[package]] @@ -2916,8 +2957,18 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4fb1c3a8bc4dd4e5cfce29b44ffc14bedd2ee294559a294e2a4d4c9e9a6a13cd" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.10.0", + "phf_shared 0.10.0", +] + +[[package]] +name = "phf_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a" +dependencies = [ + "phf_generator 0.11.2", + "phf_shared 0.11.2", ] [[package]] @@ -2926,7 +2977,17 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" dependencies = [ - "phf_shared", + "phf_shared 0.10.0", + "rand", +] + +[[package]] +name = "phf_generator" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" +dependencies = [ + "phf_shared 0.11.2", "rand", ] @@ -2939,6 +3000,15 @@ dependencies = [ "siphasher", ] +[[package]] +name = "phf_shared" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project-lite" version = "0.2.14" @@ -3354,9 +3424,9 @@ dependencies = [ [[package]] name = "rustc-build-sysroot" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9bf37423495cd3a6a9ef8c75fc4566de0d26de0ab75f36f67a426e58df5768c" +checksum = "ab1dbbd1bdf65fdac44c885f6cca147ba179108ce284b60a08ccc04b1f1dbac0" dependencies = [ "anyhow", "rustc_version", @@ -3824,7 +3894,6 @@ dependencies = [ "rustc_session", "rustc_smir", "rustc_span", - "rustc_symbol_mangling", "rustc_target", "rustc_trait_selection", "rustc_ty_utils", @@ -3907,7 +3976,6 @@ dependencies = [ "rustc_session", "rustc_span", "smallvec", - "termcolor", "thin-vec", "tracing", ] @@ -4008,7 +4076,6 @@ dependencies = [ "rustc_data_structures", "rustc_errors", "rustc_fluent_macro", - "rustc_graphviz", "rustc_hir", "rustc_hir_analysis", "rustc_hir_pretty", @@ -4396,6 +4463,7 @@ dependencies = [ "rustc_macros", "rustc_session", "rustc_span", + "termcolor", "thin-vec", "tracing", "unicode-normalization", @@ -4468,7 +4536,6 @@ dependencies = [ "rustc_errors", "rustc_fluent_macro", "rustc_hir", - "rustc_hir_analysis", "rustc_macros", "rustc_middle", "rustc_session", @@ -4515,7 +4582,6 @@ dependencies = [ "rustc_session", "rustc_span", "rustc_target", - "rustc_type_ir", "smallvec", "thin-vec", "tracing", @@ -5289,7 +5355,7 @@ dependencies = [ "new_debug_unreachable", "once_cell", "parking_lot", - "phf_shared", + "phf_shared 0.10.0", "precomputed-hash", "serde", ] @@ -5300,8 +5366,8 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6bb30289b722be4ff74a408c3cc27edeaad656e06cb1fe8fa9231fa59c728988" dependencies = [ - "phf_generator", - "phf_shared", + "phf_generator 0.10.0", + "phf_shared 0.10.0", "proc-macro2", "quote", ] @@ -5601,9 +5667,9 @@ version = "0.1.0" [[package]] name = "time" -version = "0.3.34" +version = "0.3.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8248b6521bb14bc45b4067159b9b6ad792e2d6d754d6c41fb50e29fefe38749" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" dependencies = [ "deranged", "itoa", @@ -5622,9 +5688,9 @@ checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.17" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ba3a3ef41e6672a2f0f001392bb5dcd3ff0a9992d618ca761a11c3121547774" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" dependencies = [ "num-conv", "time-core", diff --git a/RELEASES.md b/RELEASES.md index 104ea497ba499..3080f03c7210b 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -102,6 +102,10 @@ Compatibility Notes - [Change equality of higher ranked types to not rely on subtyping](https://github.com/rust-lang/rust/pull/118247) - [When called, additionally check bounds on normalized function return type](https://github.com/rust-lang/rust/pull/118882) - [Expand coverage for `arithmetic_overflow` lint](https://github.com/rust-lang/rust/pull/119432/) +- [Fix detection of potential interior mutability in `const` initializers](https://github.com/rust-lang/rust/issues/121250) + This code was accidentally accepted. The fix can break generic code that borrows a value of unknown type, + as there is currently no way to declare "this type has no interior mutability". In the future, stabilizing + the [`Freeze` trait](https://github.com/rust-lang/rust/issues/121675) will allow proper support for such code. diff --git a/compiler/rustc/src/main.rs b/compiler/rustc/src/main.rs index 434b978ae3151..7ba58406ef1ad 100644 --- a/compiler/rustc/src/main.rs +++ b/compiler/rustc/src/main.rs @@ -1,5 +1,3 @@ -#![feature(unix_sigpipe)] - // A note about jemalloc: rustc uses jemalloc when built for CI and // distribution. The obvious way to do this is with the `#[global_allocator]` // mechanism. However, for complicated reasons (see @@ -34,7 +32,6 @@ // https://github.com/rust-lang/rust/commit/b90cfc887c31c3e7a9e6d462e2464db1fe506175#diff-43914724af6e464c1da2171e4a9b6c7e607d5bc1203fa95c0ab85be4122605ef // for an example of how to do so. -#[unix_sigpipe = "sig_dfl"] fn main() { // See the comment at the top of this file for an explanation of this. #[cfg(feature = "jemalloc-sys")] diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 6a2943da4a3fb..5e3f64540e4aa 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -21,6 +21,8 @@ use rustc_macros::{Decodable_Generic, Encodable_Generic}; use std::iter::Step; mod layout; +#[cfg(test)] +mod tests; pub use layout::LayoutCalculator; diff --git a/compiler/rustc_abi/src/tests.rs b/compiler/rustc_abi/src/tests.rs new file mode 100644 index 0000000000000..d993012378c81 --- /dev/null +++ b/compiler/rustc_abi/src/tests.rs @@ -0,0 +1,7 @@ +use super::*; + +#[test] +fn align_constants() { + assert_eq!(Align::ONE, Align::from_bytes(1).unwrap()); + assert_eq!(Align::EIGHT, Align::from_bytes(8).unwrap()); +} diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 12dcbd6d17fd7..fa378e19f71ab 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -1390,7 +1390,7 @@ pub struct StructExpr { // Adding a new variant? Please update `test_expr` in `tests/ui/macros/stringify.rs`. #[derive(Clone, Encodable, Decodable, Debug)] pub enum ExprKind { - /// An array (`[a, b, c, d]`) + /// An array (e.g, `[a, b, c, d]`). Array(ThinVec>), /// Allow anonymous constants from an inline `const` block ConstBlock(AnonConst), @@ -1401,7 +1401,7 @@ pub enum ExprKind { /// This also represents calling the constructor of /// tuple-like ADTs such as tuple structs and enum variants. Call(P, ThinVec>), - /// A method call (e.g. `x.foo::(a, b, c)`). + /// A method call (e.g., `x.foo::(a, b, c)`). MethodCall(Box), /// A tuple (e.g., `(a, b, c, d)`). Tup(ThinVec>), @@ -1413,7 +1413,10 @@ pub enum ExprKind { Lit(token::Lit), /// A cast (e.g., `foo as f64`). Cast(P, P), - /// A type ascription (e.g., `42: usize`). + /// A type ascription (e.g., `builtin # type_ascribe(42, usize)`). + /// + /// Usually not written directly in user code but + /// indirectly via the macro `type_ascribe!(...)`. Type(P, P), /// A `let pat = expr` expression that is only semantically allowed in the condition /// of `if` / `while` expressions. (e.g., `if let 0 = x { .. }`). @@ -1488,7 +1491,10 @@ pub enum ExprKind { /// Output of the `asm!()` macro. InlineAsm(P), - /// Output of the `offset_of!()` macro. + /// An `offset_of` expression (e.g., `builtin # offset_of(Struct, field)`). + /// + /// Usually not written directly in user code but + /// indirectly via the macro `core::mem::offset_of!(...)`. OffsetOf(P, P<[Ident]>), /// A macro invocation; pre-expansion. diff --git a/compiler/rustc_ast/src/entry.rs b/compiler/rustc_ast/src/entry.rs index cd8a5a6692000..dd231e286d591 100644 --- a/compiler/rustc_ast/src/entry.rs +++ b/compiler/rustc_ast/src/entry.rs @@ -4,11 +4,35 @@ use rustc_span::Symbol; #[derive(Debug)] pub enum EntryPointType { + /// This function is not an entrypoint. None, + /// This is a function called `main` at the root level. + /// ``` + /// fn main() {} + /// ``` MainNamed, + /// This is a function with the `#[rustc_main]` attribute. + /// Used by the testing harness to create the test entrypoint. + /// ```ignore (clashes with test entrypoint) + /// #[rustc_main] + /// fn main() {} + /// ``` RustcMainAttr, + /// This is a function with the `#[start]` attribute. + /// ```ignore (clashes with test entrypoint) + /// #[start] + /// fn main() {} + /// ``` Start, - OtherMain, // Not an entry point, but some other function named main + /// This function is **not** an entrypoint but simply named `main` (not at the root). + /// This is only used for diagnostics. + /// ``` + /// #[allow(dead_code)] + /// mod meow { + /// fn main() {} + /// } + /// ``` + OtherMain, } pub fn entry_point_type( diff --git a/compiler/rustc_ast_lowering/src/index.rs b/compiler/rustc_ast_lowering/src/index.rs index be6c7da4108cb..7254be2b2f42a 100644 --- a/compiler/rustc_ast_lowering/src/index.rs +++ b/compiler/rustc_ast_lowering/src/index.rs @@ -62,7 +62,7 @@ pub(super) fn index_hir<'hir>( if let Node::Err(span) = node.node { let hir_id = HirId { owner: item.def_id(), local_id }; let msg = format!("ID {hir_id} not encountered when visiting item HIR"); - tcx.dcx().span_delayed_bug(*span, msg); + tcx.dcx().span_delayed_bug(span, msg); } } @@ -376,7 +376,7 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> { } } - fn visit_array_length(&mut self, len: &'hir ArrayLen) { + fn visit_array_length(&mut self, len: &'hir ArrayLen<'hir>) { match len { ArrayLen::Infer(inf) => self.insert(inf.span, inf.hir_id, Node::ArrayLenInfer(inf)), ArrayLen::Body(..) => intravisit::walk_array_len(self, len), diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index dcd8f5d5f150c..156e369c45852 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1589,11 +1589,12 @@ impl<'hir> LoweringContext<'_, 'hir> { }), )), )), - default: Some(hir::AnonConst { + default: Some(self.arena.alloc(hir::AnonConst { def_id: anon_const, hir_id: const_id, body: const_body, - }), + span, + })), is_host_effect: true, }, colon_span: None, diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index dd8c09ce485e6..6c54363e306d0 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1178,14 +1178,17 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { tokens: None, }; - let ct = self.with_new_scopes(span, |this| hir::AnonConst { - def_id, - hir_id: this.lower_node_id(node_id), - body: this.lower_const_body(path_expr.span, Some(&path_expr)), + let ct = self.with_new_scopes(span, |this| { + self.arena.alloc(hir::AnonConst { + def_id, + hir_id: this.lower_node_id(node_id), + body: this + .lower_const_body(path_expr.span, Some(&path_expr)), + span, + }) }); return GenericArg::Const(ConstArg { value: ct, - span, is_desugared_from_effects: false, }); } @@ -1197,7 +1200,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } ast::GenericArg::Const(ct) => GenericArg::Const(ConstArg { value: self.lower_anon_const(ct), - span: self.lower_span(ct.value.span), is_desugared_from_effects: false, }), } @@ -2315,7 +2317,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } #[allow(rustc::untranslatable_diagnostic)] // FIXME: make this translatable - fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen { + fn lower_array_length(&mut self, c: &AnonConst) -> hir::ArrayLen<'hir> { match c.value.kind { ExprKind::Underscore => { if self.tcx.features().generic_arg_infer { @@ -2338,12 +2340,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { } } - fn lower_anon_const(&mut self, c: &AnonConst) -> hir::AnonConst { - self.with_new_scopes(c.value.span, |this| hir::AnonConst { + fn lower_anon_const(&mut self, c: &AnonConst) -> &'hir hir::AnonConst { + self.arena.alloc(self.with_new_scopes(c.value.span, |this| hir::AnonConst { def_id: this.local_def_id(c.id), hir_id: this.lower_node_id(c.id), body: this.lower_const_body(c.value.span, Some(&c.value)), - }) + span: this.lower_span(c.value.span), + })) } fn lower_unsafe_source(&mut self, u: UnsafeSource) -> hir::UnsafeSource { @@ -2650,8 +2653,7 @@ impl<'hir> GenericArgsCtor<'hir> { lcx.children.push((def_id, hir::MaybeOwner::NonOwner(hir_id))); self.args.push(hir::GenericArg::Const(hir::ConstArg { - value: hir::AnonConst { def_id, hir_id, body }, - span, + value: lcx.arena.alloc(hir::AnonConst { def_id, hir_id, body, span }), is_desugared_from_effects: true, })) } diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index e0000e354ca5f..6622caaaab412 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -1,7 +1,7 @@ use rustc_ast as ast; use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor}; use rustc_ast::{attr, AssocConstraint, AssocConstraintKind, NodeId}; -use rustc_ast::{token, PatKind, RangeEnd}; +use rustc_ast::{token, PatKind}; use rustc_feature::{AttributeGate, BuiltinAttribute, Features, GateIssue, BUILTIN_ATTRIBUTE_MAP}; use rustc_session::parse::{feature_err, feature_err_issue, feature_warn}; use rustc_session::Session; @@ -418,15 +418,6 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { PatKind::Box(..) => { gate!(&self, box_patterns, pattern.span, "box pattern syntax is experimental"); } - PatKind::Range(_, Some(_), Spanned { node: RangeEnd::Excluded, .. }) => { - gate!( - &self, - exclusive_range_pattern, - pattern.span, - "exclusive range pattern syntax is experimental", - "use an inclusive range pattern, like N..=M" - ); - } _ => {} } visit::walk_pat(self, pattern) @@ -619,10 +610,6 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) { // be too. gate_all_legacy_dont_use!(return_type_notation, "return type notation is experimental"); gate_all_legacy_dont_use!(decl_macro, "`macro` is experimental"); - gate_all_legacy_dont_use!( - exclusive_range_pattern, - "exclusive range pattern syntax is experimental" - ); gate_all_legacy_dont_use!(try_blocks, "`try` blocks are unstable"); gate_all_legacy_dont_use!(auto_traits, "`auto` traits are unstable"); diff --git a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs index b5bb781acdfe0..93400c67949d9 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs @@ -422,7 +422,8 @@ impl<'a> State<'a> { self.print_type(ty); } ast::ExprKind::Type(expr, ty) => { - self.word("type_ascribe!("); + self.word("builtin # type_ascribe"); + self.popen(); self.ibox(0); self.print_expr(expr, FixupContext::default()); @@ -431,7 +432,7 @@ impl<'a> State<'a> { self.print_type(ty); self.end(); - self.word(")"); + self.pclose(); } ast::ExprKind::Let(pat, scrutinee, _, _) => { self.print_let(pat, scrutinee, fixup); @@ -657,15 +658,15 @@ impl<'a> State<'a> { ); } ast::ExprKind::InlineAsm(a) => { - // FIXME: This should have its own syntax, distinct from a macro invocation. + // FIXME: Print `builtin # asm` once macro `asm` uses `builtin_syntax`. self.word("asm!"); self.print_inline_asm(a); } ast::ExprKind::FormatArgs(fmt) => { - // FIXME: This should have its own syntax, distinct from a macro invocation. + // FIXME: Print `builtin # format_args` once macro `format_args` uses `builtin_syntax`. self.word("format_args!"); self.popen(); - self.rbox(0, Inconsistent); + self.ibox(0); self.word(reconstruct_format_args_template_string(&fmt.template)); for arg in fmt.arguments.all_args() { self.word_space(","); @@ -677,7 +678,7 @@ impl<'a> State<'a> { ast::ExprKind::OffsetOf(container, fields) => { self.word("builtin # offset_of"); self.popen(); - self.rbox(0, Inconsistent); + self.ibox(0); self.print_type(container); self.word(","); self.space(); @@ -690,8 +691,8 @@ impl<'a> State<'a> { self.print_ident(field); } } - self.pclose(); self.end(); + self.pclose(); } ast::ExprKind::MacCall(m) => self.print_mac(m), ast::ExprKind::Paren(e) => { diff --git a/compiler/rustc_ast_pretty/src/pprust/state/item.rs b/compiler/rustc_ast_pretty/src/pprust/state/item.rs index b90182c2b3e6b..61398f7d60579 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/item.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/item.rs @@ -238,6 +238,7 @@ impl<'a> State<'a> { self.bclose(item.span, empty); } ast::ItemKind::GlobalAsm(asm) => { + // FIXME: Print `builtin # global_asm` once macro `global_asm` uses `builtin_syntax`. self.head(visibility_qualified(&item.vis, "global_asm!")); self.print_inline_asm(asm); self.word(";"); diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index 2c717661a1c43..2450ac8f4b338 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -307,7 +307,7 @@ fn make_format_args( return ExpandResult::Ready(Err(guar)); } - let to_span = |inner_span: rustc_parse_format::InnerSpan| { + let to_span = |inner_span: parse::InnerSpan| { is_source_literal.then(|| { fmt_span.from_inner(InnerSpan { start: inner_span.start, end: inner_span.end }) }) @@ -577,7 +577,7 @@ fn make_format_args( fn invalid_placeholder_type_error( ecx: &ExtCtxt<'_>, ty: &str, - ty_span: Option, + ty_span: Option, fmt_span: Span, ) { let sp = ty_span.map(|sp| fmt_span.from_inner(InnerSpan::new(sp.start, sp.end))); diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index a2015445b42c9..8cf431482ff73 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -266,7 +266,7 @@ fn generate_test_harness( /// /// By default this expands to /// -/// ```ignore UNSOLVED (I think I still need guidance for this one. Is it correct? Do we try to make it run? How do we nicely fill it out?) +/// ```ignore (messes with test internals) /// #[rustc_main] /// pub fn main() { /// extern crate test; diff --git a/compiler/rustc_codegen_gcc/src/context.rs b/compiler/rustc_codegen_gcc/src/context.rs index 16a85b4e8fa09..4a1f5188a8013 100644 --- a/compiler/rustc_codegen_gcc/src/context.rs +++ b/compiler/rustc_codegen_gcc/src/context.rs @@ -6,7 +6,8 @@ use gccjit::{ use rustc_codegen_ssa::base::wants_msvc_seh; use rustc_codegen_ssa::errors as ssa_errors; use rustc_codegen_ssa::traits::{BackendTypes, BaseTypeMethods, MiscMethods}; -use rustc_data_structures::base_n; +use rustc_data_structures::base_n::ToBaseN; +use rustc_data_structures::base_n::ALPHANUMERIC_ONLY; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_middle::mir::mono::CodegenUnit; use rustc_middle::span_bug; @@ -621,7 +622,7 @@ impl<'b, 'tcx> CodegenCx<'b, 'tcx> { let mut name = String::with_capacity(prefix.len() + 6); name.push_str(prefix); name.push_str("."); - base_n::push_str(idx as u128, base_n::ALPHANUMERIC_ONLY, &mut name); + name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY)); name } } diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 5c8f358d03a1f..1a1b4ae383133 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -17,7 +17,7 @@ use rustc_data_structures::small_c_str::SmallCStr; use rustc_hir::def_id::DefId; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; use rustc_middle::ty::layout::{ - FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasTyCtxt, LayoutError, LayoutOfHelpers, TyAndLayout, + FnAbiError, FnAbiOfHelpers, FnAbiRequest, LayoutError, LayoutOfHelpers, TyAndLayout, }; use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_sanitizers::{cfi, kcfi}; @@ -27,7 +27,6 @@ use rustc_target::abi::{self, call::FnAbi, Align, Size, WrappingRange}; use rustc_target::spec::{HasTargetSpec, SanitizerSet, Target}; use smallvec::SmallVec; use std::borrow::Cow; -use std::ffi::CString; use std::iter; use std::ops::Deref; use std::ptr; @@ -1705,13 +1704,21 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { kcfi_bundle } + /// Emits a call to `llvm.instrprof.mcdc.parameters`. + /// + /// This doesn't produce any code directly, but is used as input by + /// the LLVM pass that handles coverage instrumentation. + /// + /// (See clang's [`CodeGenPGO::emitMCDCParameters`] for comparison.) + /// + /// [`CodeGenPGO::emitMCDCParameters`]: + /// https://github.com/rust-lang/llvm-project/blob/5399a24/clang/lib/CodeGen/CodeGenPGO.cpp#L1124 pub(crate) fn mcdc_parameters( &mut self, fn_name: &'ll Value, hash: &'ll Value, bitmap_bytes: &'ll Value, - max_decision_depth: u32, - ) -> Vec<&'ll Value> { + ) { debug!("mcdc_parameters() with args ({:?}, {:?}, {:?})", fn_name, hash, bitmap_bytes); assert!(llvm_util::get_version() >= (18, 0, 0), "MCDC intrinsics require LLVM 18 or later"); @@ -1724,8 +1731,6 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { let args = &[fn_name, hash, bitmap_bytes]; let args = self.check_call("call", llty, llfn, args); - let mut cond_bitmaps = vec![]; - unsafe { let _ = llvm::LLVMRustBuildCall( self.llbuilder, @@ -1736,23 +1741,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { [].as_ptr(), 0 as c_uint, ); - // Create condition bitmap named `mcdc.addr`. - for i in 0..=max_decision_depth { - let mut bx = Builder::with_cx(self.cx); - bx.position_at_start(llvm::LLVMGetFirstBasicBlock(self.llfn())); - - let name = CString::new(format!("mcdc.addr.{i}")).unwrap(); - let cond_bitmap = { - let alloca = - llvm::LLVMBuildAlloca(bx.llbuilder, bx.cx.type_i32(), name.as_ptr()); - llvm::LLVMSetAlignment(alloca, 4); - alloca - }; - bx.store(self.const_i32(0), cond_bitmap, self.tcx().data_layout.i32_align.abi); - cond_bitmaps.push(cond_bitmap); - } } - cond_bitmaps } pub(crate) fn mcdc_tvbitmap_update( @@ -1794,8 +1783,7 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { 0 as c_uint, ); } - let i32_align = self.tcx().data_layout.i32_align.abi; - self.store(self.const_i32(0), mcdc_temp, i32_align); + self.store(self.const_i32(0), mcdc_temp, self.tcx.data_layout.i32_align.abi); } pub(crate) fn mcdc_condbitmap_update( diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index d32baa6dc02a6..653abb4e41b3d 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -11,7 +11,8 @@ use crate::value::Value; use rustc_codegen_ssa::base::{wants_msvc_seh, wants_wasm_eh}; use rustc_codegen_ssa::errors as ssa_errors; use rustc_codegen_ssa::traits::*; -use rustc_data_structures::base_n; +use rustc_data_structures::base_n::ToBaseN; +use rustc_data_structures::base_n::ALPHANUMERIC_ONLY; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::small_c_str::SmallCStr; use rustc_hir::def_id::DefId; @@ -1015,7 +1016,7 @@ impl CodegenCx<'_, '_> { let mut name = String::with_capacity(prefix.len() + 6); name.push_str(prefix); name.push('.'); - base_n::push_str(idx as u128, base_n::ALPHANUMERIC_ONLY, &mut name); + name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY)); name } } diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index 679c6e1a2ff83..c51a7744a30a3 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -13,10 +13,10 @@ use rustc_codegen_ssa::traits::{ use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_llvm::RustString; use rustc_middle::bug; -use rustc_middle::mir::coverage::{CoverageKind, FunctionCoverageInfo}; +use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::ty::layout::HasTyCtxt; use rustc_middle::ty::Instance; -use rustc_target::abi::Align; +use rustc_target::abi::{Align, Size}; use std::cell::RefCell; @@ -91,6 +91,42 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { } impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> { + fn init_coverage(&mut self, instance: Instance<'tcx>) { + let Some(function_coverage_info) = + self.tcx.instance_mir(instance.def).function_coverage_info.as_deref() + else { + return; + }; + + // If there are no MC/DC bitmaps to set up, return immediately. + if function_coverage_info.mcdc_bitmap_bytes == 0 { + return; + } + + let fn_name = self.get_pgo_func_name_var(instance); + let hash = self.const_u64(function_coverage_info.function_source_hash); + let bitmap_bytes = self.const_u32(function_coverage_info.mcdc_bitmap_bytes); + self.mcdc_parameters(fn_name, hash, bitmap_bytes); + + // Create pointers named `mcdc.addr.{i}` to stack-allocated condition bitmaps. + let mut cond_bitmaps = vec![]; + for i in 0..function_coverage_info.mcdc_num_condition_bitmaps { + // MC/DC intrinsics will perform loads/stores that use the ABI default + // alignment for i32, so our variable declaration should match. + let align = self.tcx.data_layout.i32_align.abi; + let cond_bitmap = self.alloca(Size::from_bytes(4), align); + llvm::set_value_name(cond_bitmap, format!("mcdc.addr.{i}").as_bytes()); + self.store(self.const_i32(0), cond_bitmap, align); + cond_bitmaps.push(cond_bitmap); + } + + self.coverage_context() + .expect("always present when coverage is enabled") + .mcdc_condition_bitmap_map + .borrow_mut() + .insert(instance, cond_bitmaps); + } + #[instrument(level = "debug", skip(self))] fn add_coverage(&mut self, instance: Instance<'tcx>, kind: &CoverageKind) { // Our caller should have already taken care of inlining subtleties, @@ -109,10 +145,6 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> { return; }; - if function_coverage_info.mcdc_bitmap_bytes > 0 { - ensure_mcdc_parameters(bx, instance, function_coverage_info); - } - let Some(coverage_context) = bx.coverage_context() else { return }; let mut coverage_map = coverage_context.function_coverage_map.borrow_mut(); let func_coverage = coverage_map @@ -193,28 +225,6 @@ impl<'tcx> CoverageInfoBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> { } } -fn ensure_mcdc_parameters<'ll, 'tcx>( - bx: &mut Builder<'_, 'll, 'tcx>, - instance: Instance<'tcx>, - function_coverage_info: &FunctionCoverageInfo, -) { - let Some(cx) = bx.coverage_context() else { return }; - if cx.mcdc_condition_bitmap_map.borrow().contains_key(&instance) { - return; - } - - let fn_name = bx.get_pgo_func_name_var(instance); - let hash = bx.const_u64(function_coverage_info.function_source_hash); - let bitmap_bytes = bx.const_u32(function_coverage_info.mcdc_bitmap_bytes); - let max_decision_depth = function_coverage_info.mcdc_max_decision_depth; - let cond_bitmap = bx.mcdc_parameters(fn_name, hash, bitmap_bytes, max_decision_depth as u32); - bx.coverage_context() - .expect("already checked above") - .mcdc_condition_bitmap_map - .borrow_mut() - .insert(instance, cond_bitmap); -} - /// Calls llvm::createPGOFuncNameVar() with the given function instance's /// mangled function name. The LLVM API returns an llvm::GlobalVariable /// containing the function name, with the specific variable name and linkage diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index be5458523d1ca..2f57695ac290e 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -540,7 +540,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // \-------/ // let virtual_drop = Instance { - def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0), + def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0), // idx 0: the drop function args: drop_fn.args, }; debug!("ty = {:?}", ty); @@ -581,7 +581,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { // // SO THEN WE CAN USE THE ABOVE CODE. let virtual_drop = Instance { - def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0), + def: ty::InstanceDef::Virtual(drop_fn.def_id(), 0), // idx 0: the drop function args: drop_fn.args, }; debug!("ty = {:?}", ty); @@ -649,8 +649,8 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { return helper.funclet_br(self, bx, target, mergeable_succ); } - // Pass the condition through llvm.expect for branch hinting. - let cond = bx.expect(cond, expected); + // Because we're branching to a panic block (either a `#[cold]` one + // or an inlined abort), there's no need to `expect` it. // Create the failure block and the conditional branch to it. let lltarget = helper.llbb_with_cleanup(self, target); diff --git a/compiler/rustc_codegen_ssa/src/mir/mod.rs b/compiler/rustc_codegen_ssa/src/mir/mod.rs index 0064c16f5d9f6..cf6e2e8d14c6c 100644 --- a/compiler/rustc_codegen_ssa/src/mir/mod.rs +++ b/compiler/rustc_codegen_ssa/src/mir/mod.rs @@ -259,6 +259,10 @@ pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( // Apply debuginfo to the newly allocated locals. fx.debug_introduce_locals(&mut start_bx); + // If the backend supports coverage, and coverage is enabled for this function, + // do any necessary start-of-function codegen (e.g. locals for MC/DC bitmaps). + start_bx.init_coverage(instance); + // The builders will be created separately for each basic block at `codegen_block`. // So drop the builder of `start_llbb` to avoid having two at the same time. drop(start_bx); diff --git a/compiler/rustc_codegen_ssa/src/traits/coverageinfo.rs b/compiler/rustc_codegen_ssa/src/traits/coverageinfo.rs index d1d813bd38922..906d8b87d3bc9 100644 --- a/compiler/rustc_codegen_ssa/src/traits/coverageinfo.rs +++ b/compiler/rustc_codegen_ssa/src/traits/coverageinfo.rs @@ -3,6 +3,11 @@ use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::ty::Instance; pub trait CoverageInfoBuilderMethods<'tcx>: BackendTypes { + /// Performs any start-of-function codegen needed for coverage instrumentation. + /// + /// Can be a no-op in backends that don't support coverage instrumentation. + fn init_coverage(&mut self, _instance: Instance<'tcx>) {} + /// Handle the MIR coverage info in a backend-specific way. /// /// This can potentially be a no-op in backends that don't support diff --git a/compiler/rustc_const_eval/src/const_eval/dummy_machine.rs b/compiler/rustc_const_eval/src/const_eval/dummy_machine.rs index 7b6828c6e1828..afc60d33647a7 100644 --- a/compiler/rustc_const_eval/src/const_eval/dummy_machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/dummy_machine.rs @@ -105,7 +105,7 @@ impl<'mir, 'tcx: 'mir> interpret::Machine<'mir, 'tcx> for DummyMachine { _destination: &interpret::MPlaceTy<'tcx, Self::Provenance>, _target: Option, _unwind: UnwindAction, - ) -> interpret::InterpResult<'tcx> { + ) -> interpret::InterpResult<'tcx, Option>> { unimplemented!() } diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index dd835279df331..6e6fa70107b7e 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -459,17 +459,14 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, dest: &MPlaceTy<'tcx, Self::Provenance>, target: Option, _unwind: mir::UnwindAction, - ) -> InterpResult<'tcx> { + ) -> InterpResult<'tcx, Option>> { // Shared intrinsics. if ecx.emulate_intrinsic(instance, args, dest, target)? { - return Ok(()); + return Ok(None); } let intrinsic_name = ecx.tcx.item_name(instance.def_id()); // CTFE-specific intrinsics. - let Some(ret) = target else { - throw_unsup_format!("intrinsic `{intrinsic_name}` is not supported at compile-time"); - }; match intrinsic_name { sym::ptr_guaranteed_cmp => { let a = ecx.read_scalar(&args[0])?; @@ -536,14 +533,22 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, // not the optimization stage.) sym::is_val_statically_known => ecx.write_scalar(Scalar::from_bool(false), dest)?, _ => { - throw_unsup_format!( - "intrinsic `{intrinsic_name}` is not supported at compile-time" - ); + // We haven't handled the intrinsic, let's see if we can use a fallback body. + if ecx.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden { + throw_unsup_format!( + "intrinsic `{intrinsic_name}` is not supported at compile-time" + ); + } + return Ok(Some(ty::Instance { + def: ty::InstanceDef::Item(instance.def_id()), + args: instance.args, + })); } } - ecx.go_to_block(ret); - Ok(()) + // Intrinsic is done, jump to next block. + ecx.return_to_block(target)?; + Ok(None) } fn assert_panic( diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 4d37c3c22cd7c..88ce5a7cbebba 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -113,10 +113,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ) -> InterpResult<'tcx, bool> { let instance_args = instance.args; let intrinsic_name = self.tcx.item_name(instance.def_id()); - let Some(ret) = ret else { - // We don't support any intrinsic without return place. - return Ok(false); - }; match intrinsic_name { sym::caller_location => { @@ -376,7 +372,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { }; M::panic_nounwind(self, &msg)?; - // Skip the `go_to_block` at the end. + // Skip the `return_to_block` at the end (we panicked, we do not return). return Ok(true); } } @@ -414,7 +410,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } self.copy_op(&self.project_index(&input, index)?, dest)?; } - sym::likely | sym::unlikely | sym::black_box => { + sym::black_box => { // These just return their argument self.copy_op(&args[0], dest)?; } @@ -437,11 +433,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { self.write_scalar(Scalar::from_target_usize(align.bytes(), self), dest)?; } + // Unsupported intrinsic: skip the return_to_block below. _ => return Ok(false), } trace!("{:?}", self.dump_place(&dest.clone().into())); - self.go_to_block(ret); + self.return_to_block(ret)?; Ok(true) } diff --git a/compiler/rustc_const_eval/src/interpret/machine.rs b/compiler/rustc_const_eval/src/interpret/machine.rs index 8bc569bed54c5..8405d0746dfd1 100644 --- a/compiler/rustc_const_eval/src/interpret/machine.rs +++ b/compiler/rustc_const_eval/src/interpret/machine.rs @@ -216,6 +216,9 @@ pub trait Machine<'mir, 'tcx: 'mir>: Sized { /// Directly process an intrinsic without pushing a stack frame. It is the hook's /// responsibility to advance the instruction pointer as appropriate. + /// + /// Returns `None` if the intrinsic was fully handled. + /// Otherwise, returns an `Instance` of the function that implements the intrinsic. fn call_intrinsic( ecx: &mut InterpCx<'mir, 'tcx, Self>, instance: ty::Instance<'tcx>, @@ -223,7 +226,7 @@ pub trait Machine<'mir, 'tcx: 'mir>: Sized { destination: &MPlaceTy<'tcx, Self::Provenance>, target: Option, unwind: mir::UnwindAction, - ) -> InterpResult<'tcx>; + ) -> InterpResult<'tcx, Option>>; /// Called to evaluate `Assert` MIR terminators that trigger a panic. fn assert_panic( diff --git a/compiler/rustc_const_eval/src/interpret/terminator.rs b/compiler/rustc_const_eval/src/interpret/terminator.rs index 9c31532a9ce49..b474003087ba3 100644 --- a/compiler/rustc_const_eval/src/interpret/terminator.rs +++ b/compiler/rustc_const_eval/src/interpret/terminator.rs @@ -169,10 +169,8 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { } Drop { place, target, unwind, replace: _ } => { - let frame = self.frame(); - let ty = place.ty(&frame.body.local_decls, *self.tcx).ty; - let ty = self.instantiate_from_frame_and_normalize_erasing_regions(frame, ty)?; - let instance = Instance::resolve_drop_in_place(*self.tcx, ty); + let place = self.eval_place(place)?; + let instance = Instance::resolve_drop_in_place(*self.tcx, place.layout.ty); if let ty::InstanceDef::DropGlue(_, None) = instance.def { // This is the branch we enter if and only if the dropped type has no drop glue // whatsoever. This can happen as a result of monomorphizing a drop of a @@ -181,8 +179,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { self.go_to_block(target); return Ok(()); } - let place = self.eval_place(place)?; - trace!("TerminatorKind::drop: {:?}, type {}", place, ty); + trace!("TerminatorKind::drop: {:?}, type {}", place, place.layout.ty); self.drop_in_place(&place, instance, target, unwind)?; } @@ -539,14 +536,28 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { ty::InstanceDef::Intrinsic(def_id) => { assert!(self.tcx.intrinsic(def_id).is_some()); // FIXME: Should `InPlace` arguments be reset to uninit? - M::call_intrinsic( + if let Some(fallback) = M::call_intrinsic( self, instance, &self.copy_fn_args(args), destination, target, unwind, - ) + )? { + assert!(!self.tcx.intrinsic(fallback.def_id()).unwrap().must_be_overridden); + assert!(matches!(fallback.def, ty::InstanceDef::Item(_))); + return self.eval_fn_call( + FnVal::Instance(fallback), + (caller_abi, caller_fn_abi), + args, + with_caller_location, + destination, + target, + unwind, + ); + } else { + Ok(()) + } } ty::InstanceDef::VTableShim(..) | ty::InstanceDef::ReifyShim(..) @@ -938,6 +949,12 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { // implementation fail -- a problem shared by rustc. let place = self.force_allocation(place)?; + // We behave a bit different from codegen here. + // Codegen creates an `InstanceDef::Virtual` with index 0 (the slot of the drop method) and + // then dispatches that to the normal call machinery. However, our call machinery currently + // only supports calling `VtblEntry::Method`; it would choke on a `MetadataDropInPlace`. So + // instead we do the virtual call stuff ourselves. It's easier here than in `eval_fn_call` + // since we can just get a place of the underlying type and use `mplace_to_ref`. let place = match place.layout.ty.kind() { ty::Dynamic(data, _, ty::Dyn) => { // Dropping a trait object. Need to find actual drop fn. diff --git a/compiler/rustc_data_structures/src/base_n.rs b/compiler/rustc_data_structures/src/base_n.rs index a3eb2b9c416fc..aed89fadc4c86 100644 --- a/compiler/rustc_data_structures/src/base_n.rs +++ b/compiler/rustc_data_structures/src/base_n.rs @@ -1,6 +1,7 @@ /// Converts unsigned integers into a string representation with some base. /// Bases up to and including 36 can be used for case-insensitive things. -use std::str; +use std::ascii; +use std::fmt; #[cfg(test)] mod tests; @@ -9,36 +10,101 @@ pub const MAX_BASE: usize = 64; pub const ALPHANUMERIC_ONLY: usize = 62; pub const CASE_INSENSITIVE: usize = 36; -const BASE_64: &[u8; MAX_BASE] = - b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$"; +const BASE_64: [ascii::Char; MAX_BASE] = { + let bytes = b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ@$"; + let Some(ascii) = bytes.as_ascii() else { panic!() }; + *ascii +}; -#[inline] -pub fn push_str(mut n: u128, base: usize, output: &mut String) { - debug_assert!(base >= 2 && base <= MAX_BASE); - let mut s = [0u8; 128]; - let mut index = s.len(); +pub struct BaseNString { + start: usize, + buf: [ascii::Char; 128], +} + +impl std::ops::Deref for BaseNString { + type Target = str; - let base = base as u128; + fn deref(&self) -> &str { + self.buf[self.start..].as_str() + } +} + +impl AsRef for BaseNString { + fn as_ref(&self) -> &str { + self.buf[self.start..].as_str() + } +} + +impl fmt::Display for BaseNString { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self) + } +} + +// This trait just lets us reserve the exact right amount of space when doing fixed-length +// case-insensitve encoding. Add any impls you need. +pub trait ToBaseN: Into { + fn encoded_len(base: usize) -> usize; + + fn to_base_fixed_len(self, base: usize) -> BaseNString { + let mut encoded = self.to_base(base); + encoded.start = encoded.buf.len() - Self::encoded_len(base); + encoded + } - loop { - index -= 1; - s[index] = BASE_64[(n % base) as usize]; - n /= base; + fn to_base(self, base: usize) -> BaseNString { + let mut output = [ascii::Char::Digit0; 128]; - if n == 0 { - break; + let mut n: u128 = self.into(); + + let mut index = output.len(); + loop { + index -= 1; + output[index] = BASE_64[(n % base as u128) as usize]; + n /= base as u128; + + if n == 0 { + break; + } + } + assert_eq!(n, 0); + + BaseNString { start: index, buf: output } + } +} + +impl ToBaseN for u128 { + fn encoded_len(base: usize) -> usize { + let mut max = u128::MAX; + let mut len = 0; + while max > 0 { + len += 1; + max /= base as u128; } + len } +} - output.push_str(unsafe { - // SAFETY: `s` is populated using only valid utf8 characters from `BASE_64` - str::from_utf8_unchecked(&s[index..]) - }); +impl ToBaseN for u64 { + fn encoded_len(base: usize) -> usize { + let mut max = u64::MAX; + let mut len = 0; + while max > 0 { + len += 1; + max /= base as u64; + } + len + } } -#[inline] -pub fn encode(n: u128, base: usize) -> String { - let mut s = String::new(); - push_str(n, base, &mut s); - s +impl ToBaseN for u32 { + fn encoded_len(base: usize) -> usize { + let mut max = u32::MAX; + let mut len = 0; + while max > 0 { + len += 1; + max /= base as u32; + } + len + } } diff --git a/compiler/rustc_data_structures/src/base_n/tests.rs b/compiler/rustc_data_structures/src/base_n/tests.rs index 2be2f0532c99c..148d8dde02af1 100644 --- a/compiler/rustc_data_structures/src/base_n/tests.rs +++ b/compiler/rustc_data_structures/src/base_n/tests.rs @@ -1,9 +1,17 @@ use super::*; #[test] -fn test_encode() { +fn limits() { + assert_eq!(Ok(u128::MAX), u128::from_str_radix(&u128::MAX.to_base(36), 36)); + assert_eq!(Ok(u64::MAX), u64::from_str_radix(&u64::MAX.to_base(36), 36)); + assert_eq!(Ok(u32::MAX), u32::from_str_radix(&u32::MAX.to_base(36), 36)); +} + +#[test] +fn test_to_base() { fn test(n: u128, base: usize) { - assert_eq!(Ok(n), u128::from_str_radix(&encode(n, base), base as u32)); + assert_eq!(Ok(n), u128::from_str_radix(&n.to_base(base), base as u32)); + assert_eq!(Ok(n), u128::from_str_radix(&n.to_base_fixed_len(base), base as u32)); } for base in 2..37 { diff --git a/compiler/rustc_data_structures/src/lib.rs b/compiler/rustc_data_structures/src/lib.rs index cf54e700e2b98..8dd85b25e0e21 100644 --- a/compiler/rustc_data_structures/src/lib.rs +++ b/compiler/rustc_data_structures/src/lib.rs @@ -16,6 +16,8 @@ #![doc(rust_logo)] #![feature(allocator_api)] #![feature(array_windows)] +#![feature(ascii_char)] +#![feature(ascii_char_variants)] #![feature(auto_traits)] #![feature(cfg_match)] #![feature(core_intrinsics)] diff --git a/compiler/rustc_driver_impl/Cargo.toml b/compiler/rustc_driver_impl/Cargo.toml index a8bba3afb7e70..5f7504add8d6a 100644 --- a/compiler/rustc_driver_impl/Cargo.toml +++ b/compiler/rustc_driver_impl/Cargo.toml @@ -42,15 +42,14 @@ rustc_privacy = { path = "../rustc_privacy" } rustc_query_system = { path = "../rustc_query_system" } rustc_resolve = { path = "../rustc_resolve" } rustc_session = { path = "../rustc_session" } -rustc_smir ={ path = "../rustc_smir" } +rustc_smir = { path = "../rustc_smir" } rustc_span = { path = "../rustc_span" } -rustc_symbol_mangling = { path = "../rustc_symbol_mangling" } rustc_target = { path = "../rustc_target" } rustc_trait_selection = { path = "../rustc_trait_selection" } rustc_ty_utils = { path = "../rustc_ty_utils" } serde_json = "1.0.59" shlex = "1.0" -time = { version = "0.3", default-features = false, features = ["alloc", "formatting", "parsing", "macros"] } +time = { version = "0.3.36", default-features = false, features = ["alloc", "formatting", "parsing", "macros"] } tracing = { version = "0.1.35" } # tidy-alphabetical-end diff --git a/compiler/rustc_error_codes/src/error_codes/E0579.md b/compiler/rustc_error_codes/src/error_codes/E0579.md index e7e6fb682566e..decf810b8c618 100644 --- a/compiler/rustc_error_codes/src/error_codes/E0579.md +++ b/compiler/rustc_error_codes/src/error_codes/E0579.md @@ -3,7 +3,6 @@ A lower range wasn't less than the upper range. Erroneous code example: ```compile_fail,E0579 -#![feature(exclusive_range_pattern)] fn main() { match 5u32 { diff --git a/compiler/rustc_errors/src/diagnostic_impls.rs b/compiler/rustc_errors/src/diagnostic_impls.rs index b3a1e29f8e2cb..4696917554ffb 100644 --- a/compiler/rustc_errors/src/diagnostic_impls.rs +++ b/compiler/rustc_errors/src/diagnostic_impls.rs @@ -13,7 +13,7 @@ use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent, Symbol}; use rustc_span::Span; use rustc_target::abi::TargetDataLayoutErrors; use rustc_target::spec::{PanicStrategy, SplitDebuginfo, StackProtector, TargetTriple}; -use rustc_type_ir as type_ir; +use rustc_type_ir::{ClosureKind, FloatTy}; use std::backtrace::Backtrace; use std::borrow::Cow; use std::fmt; @@ -196,7 +196,7 @@ impl IntoDiagArg for ast::token::TokenKind { } } -impl IntoDiagArg for type_ir::FloatTy { +impl IntoDiagArg for FloatTy { fn into_diag_arg(self) -> DiagArgValue { DiagArgValue::Str(Cow::Borrowed(self.name_str())) } @@ -252,7 +252,7 @@ impl IntoDiagArg for Level { } } -impl IntoDiagArg for type_ir::ClosureKind { +impl IntoDiagArg for ClosureKind { fn into_diag_arg(self) -> DiagArgValue { DiagArgValue::Str(self.as_str().into()) } diff --git a/compiler/rustc_expand/Cargo.toml b/compiler/rustc_expand/Cargo.toml index 63247f9d0519c..ce014364b0d01 100644 --- a/compiler/rustc_expand/Cargo.toml +++ b/compiler/rustc_expand/Cargo.toml @@ -25,7 +25,6 @@ rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } -termcolor = "1.2" thin-vec = "0.2.12" tracing = "0.1" # tidy-alphabetical-end diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 6fe74edbd70a8..12868a666056d 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -21,7 +21,7 @@ use rustc_session::config::CollapseMacroDebuginfo; use rustc_session::{parse::ParseSess, Limit, Session}; use rustc_span::def_id::{CrateNum, DefId, LocalDefId}; use rustc_span::edition::Edition; -use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId}; +use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind}; use rustc_span::source_map::SourceMap; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::{FileName, Span, DUMMY_SP}; @@ -32,8 +32,6 @@ use std::path::{Path, PathBuf}; use std::rc::Rc; use thin_vec::ThinVec; -pub(crate) use rustc_span::hygiene::MacroKind; - // When adding new variants, make sure to // adjust the `visit_*` / `flat_map_*` calls in `InvocationCollector` // to use `assign_id!` @@ -573,35 +571,6 @@ impl DummyResult { tokens: None, }) } - - /// A plain dummy pattern. - pub fn raw_pat(sp: Span) -> ast::Pat { - ast::Pat { id: ast::DUMMY_NODE_ID, kind: PatKind::Wild, span: sp, tokens: None } - } - - /// A plain dummy type. - pub fn raw_ty(sp: Span) -> P { - // FIXME(nnethercote): you might expect `ast::TyKind::Dummy` to be used here, but some - // values produced here end up being lowered to HIR, which `ast::TyKind::Dummy` does not - // support, so we use an empty tuple instead. - P(ast::Ty { - id: ast::DUMMY_NODE_ID, - kind: ast::TyKind::Tup(ThinVec::new()), - span: sp, - tokens: None, - }) - } - - /// A plain dummy crate. - pub fn raw_crate() -> ast::Crate { - ast::Crate { - attrs: Default::default(), - items: Default::default(), - spans: Default::default(), - id: ast::DUMMY_NODE_ID, - is_placeholder: Default::default(), - } - } } impl MacResult for DummyResult { @@ -610,7 +579,12 @@ impl MacResult for DummyResult { } fn make_pat(self: Box) -> Option> { - Some(P(DummyResult::raw_pat(self.span))) + Some(P(ast::Pat { + id: ast::DUMMY_NODE_ID, + kind: PatKind::Wild, + span: self.span, + tokens: None, + })) } fn make_items(self: Box) -> Option; 1]>> { @@ -638,7 +612,15 @@ impl MacResult for DummyResult { } fn make_ty(self: Box) -> Option> { - Some(DummyResult::raw_ty(self.span)) + // FIXME(nnethercote): you might expect `ast::TyKind::Dummy` to be used here, but some + // values produced here end up being lowered to HIR, which `ast::TyKind::Dummy` does not + // support, so we use an empty tuple instead. + Some(P(ast::Ty { + id: ast::DUMMY_NODE_ID, + kind: ast::TyKind::Tup(ThinVec::new()), + span: self.span, + tokens: None, + })) } fn make_arms(self: Box) -> Option> { @@ -670,7 +652,13 @@ impl MacResult for DummyResult { } fn make_crate(self: Box) -> Option { - Some(DummyResult::raw_crate()) + Some(ast::Crate { + attrs: Default::default(), + items: Default::default(), + spans: Default::default(), + id: ast::DUMMY_NODE_ID, + is_placeholder: Default::default(), + }) } } diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index 83f120525bc5f..1b6e191c2eb09 100644 --- a/compiler/rustc_expand/src/build.rs +++ b/compiler/rustc_expand/src/build.rs @@ -175,20 +175,6 @@ impl<'a> ExtCtxt<'a> { ast::Stmt { id: ast::DUMMY_NODE_ID, span: expr.span, kind: ast::StmtKind::Expr(expr) } } - pub fn stmt_let_pat(&self, sp: Span, pat: P, ex: P) -> ast::Stmt { - let local = P(ast::Local { - pat, - ty: None, - id: ast::DUMMY_NODE_ID, - kind: LocalKind::Init(ex), - span: sp, - colon_sp: None, - attrs: AttrVec::new(), - tokens: None, - }); - self.stmt_local(local, sp) - } - pub fn stmt_let(&self, sp: Span, mutbl: bool, ident: Ident, ex: P) -> ast::Stmt { self.stmt_let_ty(sp, mutbl, ident, None, ex) } @@ -278,10 +264,6 @@ impl<'a> ExtCtxt<'a> { self.expr_ident(span, Ident::with_dummy_span(kw::SelfLower)) } - pub fn expr_field(&self, span: Span, expr: P, field: Ident) -> P { - self.expr(span, ast::ExprKind::Field(expr, field)) - } - pub fn expr_macro_call(&self, span: Span, call: P) -> P { self.expr(span, ast::ExprKind::MacCall(call)) } @@ -394,11 +376,6 @@ impl<'a> ExtCtxt<'a> { self.expr(span, ast::ExprKind::Lit(lit)) } - pub fn expr_char(&self, span: Span, ch: char) -> P { - let lit = token::Lit::new(token::Char, literal::escape_char_symbol(ch), None); - self.expr(span, ast::ExprKind::Lit(lit)) - } - pub fn expr_byte_str(&self, span: Span, bytes: Vec) -> P { let lit = token::Lit::new(token::ByteStr, literal::escape_byte_str_symbol(&bytes), None); self.expr(span, ast::ExprKind::Lit(lit)) @@ -414,10 +391,6 @@ impl<'a> ExtCtxt<'a> { self.expr_addr_of(sp, self.expr_array(sp, exprs)) } - pub fn expr_cast(&self, sp: Span, expr: P, ty: P) -> P { - self.expr(sp, ast::ExprKind::Cast(expr, ty)) - } - pub fn expr_some(&self, sp: Span, expr: P) -> P { let some = self.std_path(&[sym::option, sym::Option, sym::Some]); self.expr_call_global(sp, some, thin_vec![expr]) diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index b554a5ccd1961..897420a11cdfb 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -99,10 +99,11 @@ pub fn features(sess: &Session, krate_attrs: &[Attribute], crate_name: Symbol) - // If the declared feature is unstable, record it. if let Some(f) = UNSTABLE_FEATURES.iter().find(|f| name == f.feature.name) { (f.set_enabled)(&mut features); - // When the ICE comes from core, alloc or std (approximation of the standard library), there's a chance - // that the person hitting the ICE may be using -Zbuild-std or similar with an untested target. - // The bug is probably in the standard library and not the compiler in that case, but that doesn't - // really matter - we want a bug report. + // When the ICE comes from core, alloc or std (approximation of the standard + // library), there's a chance that the person hitting the ICE may be using + // -Zbuild-std or similar with an untested target. The bug is probably in the + // standard library and not the compiler in that case, but that doesn't really + // matter - we want a bug report. if features.internal(name) && ![sym::core, sym::alloc, sym::std].contains(&crate_name) { diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 503c9170cab53..f61cebc02562a 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -4,7 +4,6 @@ use crate::errors::{ IncompleteParse, RecursionLimitReached, RemoveExprNotSupported, RemoveNodeNotSupported, UnsupportedKeyValue, WrongFragmentKind, }; -use crate::hygiene::SyntaxContext; use crate::mbe::diagnostics::annotate_err_with_kind; use crate::module::{mod_dir_path, parse_external_mod, DirOwnership, ParsedExternalMod}; use crate::placeholders::{placeholder, PlaceholderExpander}; @@ -32,6 +31,7 @@ use rustc_session::lint::builtin::{UNUSED_ATTRIBUTES, UNUSED_DOC_COMMENTS}; use rustc_session::lint::BuiltinLintDiag; use rustc_session::parse::feature_err; use rustc_session::{Limit, Session}; +use rustc_span::hygiene::SyntaxContext; use rustc_span::symbol::{sym, Ident}; use rustc_span::{ErrorGuaranteed, FileName, LocalExpnId, Span}; @@ -87,7 +87,7 @@ macro_rules! ast_fragments { } impl AstFragment { - pub fn add_placeholders(&mut self, placeholders: &[NodeId]) { + fn add_placeholders(&mut self, placeholders: &[NodeId]) { if placeholders.is_empty() { return; } @@ -100,14 +100,14 @@ macro_rules! ast_fragments { } } - pub fn make_opt_expr(self) -> Option> { + pub(crate) fn make_opt_expr(self) -> Option> { match self { AstFragment::OptExpr(expr) => expr, _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), } } - pub fn make_method_receiver_expr(self) -> P { + pub(crate) fn make_method_receiver_expr(self) -> P { match self { AstFragment::MethodReceiverExpr(expr) => expr, _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), @@ -125,7 +125,7 @@ macro_rules! ast_fragments { T::fragment_to_output(self) } - pub fn mut_visit_with(&mut self, vis: &mut F) { + pub(crate) fn mut_visit_with(&mut self, vis: &mut F) { match self { AstFragment::OptExpr(opt_expr) => { visit_clobber(opt_expr, |opt_expr| { @@ -372,6 +372,14 @@ impl Invocation { InvocationKind::Derive { path, .. } => path.span, } } + + fn span_mut(&mut self) -> &mut Span { + match &mut self.kind { + InvocationKind::Bang { span, .. } => span, + InvocationKind::Attr { attr, .. } => &mut attr.span, + InvocationKind::Derive { path, .. } => &mut path.span, + } + } } pub struct MacroExpander<'a, 'b> { @@ -432,7 +440,8 @@ impl<'a, 'b> MacroExpander<'a, 'b> { break; } invocations = mem::take(&mut undetermined_invocations); - force = !mem::replace(&mut progress, false); + force = !progress; + progress = false; if force && self.monotonic { self.cx.dcx().span_delayed_bug( invocations.last().unwrap().0.span(), @@ -471,7 +480,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { self.cx.force_mode = force; let fragment_kind = invoc.fragment_kind; - let (expanded_fragment, new_invocations) = match self.expand_invoc(invoc, &ext.kind) { + match self.expand_invoc(invoc, &ext.kind) { ExpandResult::Ready(fragment) => { let mut derive_invocations = Vec::new(); let derive_placeholders = self @@ -503,12 +512,19 @@ impl<'a, 'b> MacroExpander<'a, 'b> { }) .unwrap_or_default(); - let (fragment, collected_invocations) = + let (expanded_fragment, collected_invocations) = self.collect_invocations(fragment, &derive_placeholders); - // We choose to expand any derive invocations associated with this macro invocation - // *before* any macro invocations collected from the output fragment + // We choose to expand any derive invocations associated with this macro + // invocation *before* any macro invocations collected from the output + // fragment. derive_invocations.extend(collected_invocations); - (fragment, derive_invocations) + + progress = true; + if expanded_fragments.len() < depth { + expanded_fragments.push(Vec::new()); + } + expanded_fragments[depth - 1].push((expn_id, expanded_fragment)); + invocations.extend(derive_invocations.into_iter().rev()); } ExpandResult::Retry(invoc) => { if force { @@ -519,17 +535,9 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } else { // Cannot expand, will retry this invocation later. undetermined_invocations.push((invoc, Some(ext))); - continue; } } - }; - - progress = true; - if expanded_fragments.len() < depth { - expanded_fragments.push(Vec::new()); } - expanded_fragments[depth - 1].push((expn_id, expanded_fragment)); - invocations.extend(new_invocations.into_iter().rev()); } self.cx.current_expansion = orig_expansion_data; @@ -590,11 +598,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { for (invoc, _) in invocations.iter_mut() { let expn_id = invoc.expansion_data.id; let parent_def = self.cx.resolver.invocation_parent(expn_id); - let span = match &mut invoc.kind { - InvocationKind::Bang { span, .. } => span, - InvocationKind::Attr { attr, .. } => &mut attr.span, - InvocationKind::Derive { path, .. } => &mut path.span, - }; + let span = invoc.span_mut(); *span = span.with_parent(Some(parent_def)); } } @@ -957,7 +961,7 @@ pub fn parse_ast_fragment<'a>( }) } -pub fn ensure_complete_parse<'a>( +pub(crate) fn ensure_complete_parse<'a>( parser: &Parser<'a>, macro_path: &ast::Path, kind_name: &str, diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs index 3c9d2e8706835..4222c9fe90616 100644 --- a/compiler/rustc_expand/src/lib.rs +++ b/compiler/rustc_expand/src/lib.rs @@ -1,61 +1,37 @@ +// tidy-alphabetical-start +#![allow(internal_features)] +#![allow(rustc::diagnostic_outside_of_impl)] #![doc(rust_logo)] -#![feature(rustdoc_internals)] #![feature(array_windows)] #![feature(associated_type_defaults)] #![feature(if_let_guard)] #![feature(let_chains)] -#![feature(lint_reasons)] #![feature(macro_metavar_expr)] #![feature(map_try_insert)] #![feature(proc_macro_diagnostic)] #![feature(proc_macro_internals)] -#![feature(proc_macro_span)] +#![feature(rustdoc_internals)] #![feature(try_blocks)] #![feature(yeet_expr)] -#![allow(rustc::diagnostic_outside_of_impl)] -#![allow(internal_features)] +// tidy-alphabetical-end extern crate proc_macro as pm; +mod build; +mod errors; +// FIXME(Nilstrieb) Translate macro_rules diagnostics +#[allow(rustc::untranslatable_diagnostic)] +mod mbe; mod placeholders; mod proc_macro_server; pub use mbe::macro_rules::compile_declarative_macro; -pub(crate) use rustc_span::hygiene; pub mod base; -pub mod build; -#[macro_use] pub mod config; -pub mod errors; pub mod expand; pub mod module; - // FIXME(Nilstrieb) Translate proc_macro diagnostics #[allow(rustc::untranslatable_diagnostic)] pub mod proc_macro; -// FIXME(Nilstrieb) Translate macro_rules diagnostics -#[allow(rustc::untranslatable_diagnostic)] -pub(crate) mod mbe; - -// HACK(Centril, #64197): These shouldn't really be here. -// Rather, they should be with their respective modules which are defined in other crates. -// However, since for now constructing a `ParseSess` sorta requires `config` from this crate, -// these tests will need to live here in the interim. - -#[cfg(test)] -mod tests; -#[cfg(test)] -mod parse { - mod tests; -} -#[cfg(test)] -mod tokenstream { - mod tests; -} -#[cfg(test)] -mod mut_visit { - mod tests; -} - rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_expand/src/mbe.rs b/compiler/rustc_expand/src/mbe.rs index bd6a9b7cb07da..a805c4fcf7b97 100644 --- a/compiler/rustc_expand/src/mbe.rs +++ b/compiler/rustc_expand/src/mbe.rs @@ -4,12 +4,13 @@ //! official terminology: "declarative macros". pub(crate) mod diagnostics; -pub(crate) mod macro_check; -pub(crate) mod macro_parser; pub(crate) mod macro_rules; -pub(crate) mod metavar_expr; -pub(crate) mod quoted; -pub(crate) mod transcribe; + +mod macro_check; +mod macro_parser; +mod metavar_expr; +mod quoted; +mod transcribe; use metavar_expr::MetaVarExpr; use rustc_ast::token::{Delimiter, NonterminalKind, Token, TokenKind}; diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index 5d6c3e8aa3a4a..464361cb4020b 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -28,7 +28,8 @@ pub(super) fn failed_to_match_macro<'cx>( ) -> Box { let psess = &cx.sess.psess; - // An error occurred, try the expansion again, tracking the expansion closely for better diagnostics. + // An error occurred, try the expansion again, tracking the expansion closely for better + // diagnostics. let mut tracker = CollectTrackerAndEmitter::new(cx, sp); let try_success_result = try_match_macro(psess, name, &arg, lhses, &mut tracker); diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index df2643ad1ddea..470bde232d723 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -157,8 +157,8 @@ pub(super) trait Tracker<'matcher> { /// This is called before trying to match next MatcherLoc on the current token. fn before_match_loc(&mut self, _parser: &TtParser, _matcher: &'matcher MatcherLoc) {} - /// This is called after an arm has been parsed, either successfully or unsuccessfully. When this is called, - /// `before_match_loc` was called at least once (with a `MatcherLoc::Eof`). + /// This is called after an arm has been parsed, either successfully or unsuccessfully. When + /// this is called, `before_match_loc` was called at least once (with a `MatcherLoc::Eof`). fn after_arm(&mut self, _result: &NamedParseResult) {} /// For tracing. @@ -169,7 +169,8 @@ pub(super) trait Tracker<'matcher> { } } -/// A noop tracker that is used in the hot path of the expansion, has zero overhead thanks to monomorphization. +/// A noop tracker that is used in the hot path of the expansion, has zero overhead thanks to +/// monomorphization. pub(super) struct NoopTracker; impl<'matcher> Tracker<'matcher> for NoopTracker { @@ -492,7 +493,7 @@ pub fn compile_declarative_macro( .pop() .unwrap(); // We don't handle errors here, the driver will abort - // after parsing/expansion. we can report every error in every macro this way. + // after parsing/expansion. We can report every error in every macro this way. check_emission(check_lhs_nt_follows(sess, def, &tt)); return tt; } @@ -528,7 +529,7 @@ pub fn compile_declarative_macro( check_emission(check_rhs(sess, rhs)); } - // don't abort iteration early, so that errors for multiple lhses can be reported + // Don't abort iteration early, so that errors for multiple lhses can be reported. for lhs in &lhses { check_emission(check_lhs_no_empty_seq(sess, slice::from_ref(lhs))); } diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index dad83984c8b15..011aa95c8a116 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -39,26 +39,32 @@ impl MutVisitor for Marker { } /// An iterator over the token trees in a delimited token tree (`{ ... }`) or a sequence (`$(...)`). -enum Frame<'a> { - Delimited { - tts: &'a [mbe::TokenTree], - idx: usize, - delim: Delimiter, - span: DelimSpan, - spacing: DelimSpacing, - }, - Sequence { - tts: &'a [mbe::TokenTree], - idx: usize, - sep: Option, - kleene_op: KleeneOp, - }, +struct Frame<'a> { + tts: &'a [mbe::TokenTree], + idx: usize, + kind: FrameKind, +} + +enum FrameKind { + Delimited { delim: Delimiter, span: DelimSpan, spacing: DelimSpacing }, + Sequence { sep: Option, kleene_op: KleeneOp }, } impl<'a> Frame<'a> { - /// Construct a new frame around the delimited set of tokens. - fn new(src: &'a mbe::Delimited, span: DelimSpan, spacing: DelimSpacing) -> Frame<'a> { - Frame::Delimited { tts: &src.tts, idx: 0, delim: src.delim, span, spacing } + fn new_delimited(src: &'a mbe::Delimited, span: DelimSpan, spacing: DelimSpacing) -> Frame<'a> { + Frame { + tts: &src.tts, + idx: 0, + kind: FrameKind::Delimited { delim: src.delim, span, spacing }, + } + } + + fn new_sequence( + src: &'a mbe::SequenceRepetition, + sep: Option, + kleene_op: KleeneOp, + ) -> Frame<'a> { + Frame { tts: &src.tts, idx: 0, kind: FrameKind::Sequence { sep, kleene_op } } } } @@ -66,13 +72,9 @@ impl<'a> Iterator for Frame<'a> { type Item = &'a mbe::TokenTree; fn next(&mut self) -> Option<&'a mbe::TokenTree> { - match self { - Frame::Delimited { tts, idx, .. } | Frame::Sequence { tts, idx, .. } => { - let res = tts.get(*idx); - *idx += 1; - res - } - } + let res = self.tts.get(self.idx); + self.idx += 1; + res } } @@ -111,13 +113,16 @@ pub(super) fn transcribe<'a>( // We descend into the RHS (`src`), expanding things as we go. This stack contains the things // we have yet to expand/are still expanding. We start the stack off with the whole RHS. The // choice of spacing values doesn't matter. - let mut stack: SmallVec<[Frame<'_>; 1]> = - smallvec![Frame::new(src, src_span, DelimSpacing::new(Spacing::Alone, Spacing::Alone))]; + let mut stack: SmallVec<[Frame<'_>; 1]> = smallvec![Frame::new_delimited( + src, + src_span, + DelimSpacing::new(Spacing::Alone, Spacing::Alone) + )]; // As we descend in the RHS, we will need to be able to match nested sequences of matchers. // `repeats` keeps track of where we are in matching at each level, with the last element being // the most deeply nested sequence. This is used as a stack. - let mut repeats = Vec::new(); + let mut repeats: Vec<(usize, usize)> = Vec::new(); // `result` contains resulting token stream from the TokenTree we just finished processing. At // the end, this will contain the full result of transcription, but at arbitrary points during @@ -142,11 +147,12 @@ pub(super) fn transcribe<'a>( // Otherwise, if we have just reached the end of a sequence and we can keep repeating, // go back to the beginning of the sequence. - if let Frame::Sequence { idx, sep, .. } = stack.last_mut().unwrap() { + let frame = stack.last_mut().unwrap(); + if let FrameKind::Sequence { sep, .. } = &frame.kind { let (repeat_idx, repeat_len) = repeats.last_mut().unwrap(); *repeat_idx += 1; if repeat_idx < repeat_len { - *idx = 0; + frame.idx = 0; if let Some(sep) = sep { result.push(TokenTree::Token(sep.clone(), Spacing::Alone)); } @@ -157,16 +163,16 @@ pub(super) fn transcribe<'a>( // We are done with the top of the stack. Pop it. Depending on what it was, we do // different things. Note that the outermost item must be the delimited, wrapped RHS // that was passed in originally to `transcribe`. - match stack.pop().unwrap() { + match stack.pop().unwrap().kind { // Done with a sequence. Pop from repeats. - Frame::Sequence { .. } => { + FrameKind::Sequence { .. } => { repeats.pop(); } // We are done processing a Delimited. If this is the top-level delimited, we are // done. Otherwise, we unwind the result_stack to append what we have produced to // any previous results. - Frame::Delimited { delim, span, mut spacing, .. } => { + FrameKind::Delimited { delim, span, mut spacing, .. } => { // Hack to force-insert a space after `]` in certain case. // See discussion of the `hex-literal` crate in #114571. if delim == Delimiter::Bracket { @@ -192,7 +198,7 @@ pub(super) fn transcribe<'a>( // We are descending into a sequence. We first make sure that the matchers in the RHS // and the matches in `interp` have the same shape. Otherwise, either the caller or the // macro writer has made a mistake. - seq @ mbe::TokenTree::Sequence(_, delimited) => { + seq @ mbe::TokenTree::Sequence(_, seq_rep) => { match lockstep_iter_size(seq, interp, &repeats) { LockstepIterSize::Unconstrained => { return Err(cx @@ -233,12 +239,11 @@ pub(super) fn transcribe<'a>( // The first time we encounter the sequence we push it to the stack. It // then gets reused (see the beginning of the loop) until we are done // repeating. - stack.push(Frame::Sequence { - idx: 0, - sep: seq.separator.clone(), - tts: &delimited.tts, - kleene_op: seq.kleene.op, - }); + stack.push(Frame::new_sequence( + seq_rep, + seq.separator.clone(), + seq.kleene.op, + )); } } } @@ -294,13 +299,7 @@ pub(super) fn transcribe<'a>( // the previous results (from outside the Delimited). mbe::TokenTree::Delimited(mut span, spacing, delimited) => { mut_visit::visit_delim_span(&mut span, &mut marker); - stack.push(Frame::Delimited { - tts: &delimited.tts, - delim: delimited.delim, - idx: 0, - span, - spacing: *spacing, - }); + stack.push(Frame::new_delimited(delimited, span, *spacing)); result_stack.push(mem::take(&mut result)); } @@ -358,10 +357,13 @@ fn maybe_use_metavar_location( ) -> TokenTree { let undelimited_seq = matches!( stack.last(), - Some(Frame::Sequence { + Some(Frame { tts: [_], - sep: None, - kleene_op: KleeneOp::ZeroOrMore | KleeneOp::OneOrMore, + kind: FrameKind::Sequence { + sep: None, + kleene_op: KleeneOp::ZeroOrMore | KleeneOp::OneOrMore, + .. + }, .. }) ); diff --git a/compiler/rustc_expand/src/parse/tests.rs b/compiler/rustc_expand/src/parse/tests.rs deleted file mode 100644 index 066afd7a41d28..0000000000000 --- a/compiler/rustc_expand/src/parse/tests.rs +++ /dev/null @@ -1,382 +0,0 @@ -use crate::tests::{ - matches_codepattern, psess, string_to_stream, with_error_checking_parse, - with_expected_parse_error, -}; - -use ast::token::IdentIsRaw; -use rustc_ast::ptr::P; -use rustc_ast::token::{self, Delimiter, Token}; -use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; -use rustc_ast::visit; -use rustc_ast::{self as ast, PatKind}; -use rustc_ast_pretty::pprust::item_to_string; -use rustc_errors::PResult; -use rustc_parse::new_parser_from_source_str; -use rustc_parse::parser::ForceCollect; -use rustc_session::parse::ParseSess; -use rustc_span::create_default_session_globals_then; -use rustc_span::symbol::{kw, sym, Symbol}; -use rustc_span::{BytePos, FileName, Pos, Span}; -use std::path::PathBuf; - -/// Parses an item. -/// -/// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err` -/// when a syntax error occurred. -fn parse_item_from_source_str( - name: FileName, - source: String, - psess: &ParseSess, -) -> PResult<'_, Option>> { - new_parser_from_source_str(psess, name, source).parse_item(ForceCollect::No) -} - -// Produces a `rustc_span::span`. -fn sp(a: u32, b: u32) -> Span { - Span::with_root_ctxt(BytePos(a), BytePos(b)) -} - -/// Parses a string, return an expression. -fn string_to_expr(source_str: String) -> P { - with_error_checking_parse(source_str, &psess(), |p| p.parse_expr()) -} - -/// Parses a string, returns an item. -fn string_to_item(source_str: String) -> Option> { - with_error_checking_parse(source_str, &psess(), |p| p.parse_item(ForceCollect::No)) -} - -#[test] -fn bad_path_expr_1() { - // This should trigger error: expected identifier, found keyword `return` - create_default_session_globals_then(|| { - with_expected_parse_error( - "::abc::def::return", - "expected identifier, found keyword `return`", - |p| p.parse_expr(), - ); - }) -} - -// Checks the token-tree-ization of macros. -#[test] -fn string_to_tts_macro() { - create_default_session_globals_then(|| { - let stream = string_to_stream("macro_rules! zip (($a)=>($a))".to_string()); - let tts = &stream.trees().collect::>()[..]; - - match tts { - [ - TokenTree::Token( - Token { kind: token::Ident(name_macro_rules, IdentIsRaw::No), .. }, - _, - ), - TokenTree::Token(Token { kind: token::Not, .. }, _), - TokenTree::Token(Token { kind: token::Ident(name_zip, IdentIsRaw::No), .. }, _), - TokenTree::Delimited(.., macro_delim, macro_tts), - ] if name_macro_rules == &kw::MacroRules && name_zip.as_str() == "zip" => { - let tts = ¯o_tts.trees().collect::>(); - match &tts[..] { - [ - TokenTree::Delimited(.., first_delim, first_tts), - TokenTree::Token(Token { kind: token::FatArrow, .. }, _), - TokenTree::Delimited(.., second_delim, second_tts), - ] if macro_delim == &Delimiter::Parenthesis => { - let tts = &first_tts.trees().collect::>(); - match &tts[..] { - [ - TokenTree::Token(Token { kind: token::Dollar, .. }, _), - TokenTree::Token( - Token { kind: token::Ident(name, IdentIsRaw::No), .. }, - _, - ), - ] if first_delim == &Delimiter::Parenthesis && name.as_str() == "a" => { - } - _ => panic!("value 3: {:?} {:?}", first_delim, first_tts), - } - let tts = &second_tts.trees().collect::>(); - match &tts[..] { - [ - TokenTree::Token(Token { kind: token::Dollar, .. }, _), - TokenTree::Token( - Token { kind: token::Ident(name, IdentIsRaw::No), .. }, - _, - ), - ] if second_delim == &Delimiter::Parenthesis - && name.as_str() == "a" => {} - _ => panic!("value 4: {:?} {:?}", second_delim, second_tts), - } - } - _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts), - } - } - _ => panic!("value: {:?}", tts), - } - }) -} - -#[test] -fn string_to_tts_1() { - create_default_session_globals_then(|| { - let tts = string_to_stream("fn a(b: i32) { b; }".to_string()); - - let expected = TokenStream::new(vec![ - TokenTree::token_alone(token::Ident(kw::Fn, IdentIsRaw::No), sp(0, 2)), - TokenTree::token_joint_hidden( - token::Ident(Symbol::intern("a"), IdentIsRaw::No), - sp(3, 4), - ), - TokenTree::Delimited( - DelimSpan::from_pair(sp(4, 5), sp(11, 12)), - // `JointHidden` because the `(` is followed immediately by - // `b`, `Alone` because the `)` is followed by whitespace. - DelimSpacing::new(Spacing::JointHidden, Spacing::Alone), - Delimiter::Parenthesis, - TokenStream::new(vec![ - TokenTree::token_joint( - token::Ident(Symbol::intern("b"), IdentIsRaw::No), - sp(5, 6), - ), - TokenTree::token_alone(token::Colon, sp(6, 7)), - // `JointHidden` because the `i32` is immediately followed by the `)`. - TokenTree::token_joint_hidden( - token::Ident(sym::i32, IdentIsRaw::No), - sp(8, 11), - ), - ]) - .into(), - ), - TokenTree::Delimited( - DelimSpan::from_pair(sp(13, 14), sp(18, 19)), - // First `Alone` because the `{` is followed by whitespace, - // second `Alone` because the `}` is followed immediately by - // EOF. - DelimSpacing::new(Spacing::Alone, Spacing::Alone), - Delimiter::Brace, - TokenStream::new(vec![ - TokenTree::token_joint( - token::Ident(Symbol::intern("b"), IdentIsRaw::No), - sp(15, 16), - ), - // `Alone` because the `;` is followed by whitespace. - TokenTree::token_alone(token::Semi, sp(16, 17)), - ]) - .into(), - ), - ]); - - assert_eq!(tts, expected); - }) -} - -#[test] -fn parse_use() { - create_default_session_globals_then(|| { - let use_s = "use foo::bar::baz;"; - let vitem = string_to_item(use_s.to_string()).unwrap(); - let vitem_s = item_to_string(&vitem); - assert_eq!(&vitem_s[..], use_s); - - let use_s = "use foo::bar as baz;"; - let vitem = string_to_item(use_s.to_string()).unwrap(); - let vitem_s = item_to_string(&vitem); - assert_eq!(&vitem_s[..], use_s); - }) -} - -#[test] -fn parse_extern_crate() { - create_default_session_globals_then(|| { - let ex_s = "extern crate foo;"; - let vitem = string_to_item(ex_s.to_string()).unwrap(); - let vitem_s = item_to_string(&vitem); - assert_eq!(&vitem_s[..], ex_s); - - let ex_s = "extern crate foo as bar;"; - let vitem = string_to_item(ex_s.to_string()).unwrap(); - let vitem_s = item_to_string(&vitem); - assert_eq!(&vitem_s[..], ex_s); - }) -} - -fn get_spans_of_pat_idents(src: &str) -> Vec { - let item = string_to_item(src.to_string()).unwrap(); - - struct PatIdentVisitor { - spans: Vec, - } - impl<'a> visit::Visitor<'a> for PatIdentVisitor { - fn visit_pat(&mut self, p: &'a ast::Pat) { - match &p.kind { - PatKind::Ident(_, ident, _) => { - self.spans.push(ident.span); - } - _ => { - visit::walk_pat(self, p); - } - } - } - } - let mut v = PatIdentVisitor { spans: Vec::new() }; - visit::walk_item(&mut v, &item); - return v.spans; -} - -#[test] -fn span_of_self_arg_pat_idents_are_correct() { - create_default_session_globals_then(|| { - let srcs = [ - "impl z { fn a (&self, &myarg: i32) {} }", - "impl z { fn a (&mut self, &myarg: i32) {} }", - "impl z { fn a (&'a self, &myarg: i32) {} }", - "impl z { fn a (self, &myarg: i32) {} }", - "impl z { fn a (self: Foo, &myarg: i32) {} }", - ]; - - for src in srcs { - let spans = get_spans_of_pat_idents(src); - let (lo, hi) = (spans[0].lo(), spans[0].hi()); - assert!( - "self" == &src[lo.to_usize()..hi.to_usize()], - "\"{}\" != \"self\". src=\"{}\"", - &src[lo.to_usize()..hi.to_usize()], - src - ) - } - }) -} - -#[test] -fn parse_exprs() { - create_default_session_globals_then(|| { - // just make sure that they parse.... - string_to_expr("3 + 4".to_string()); - string_to_expr("a::z.froob(b,&(987+3))".to_string()); - }) -} - -#[test] -fn attrs_fix_bug() { - create_default_session_globals_then(|| { - string_to_item( - "pub fn mk_file_writer(path: &Path, flags: &[FileFlag]) - -> Result, String> { -#[cfg(windows)] -fn wb() -> c_int { - (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int -} - -#[cfg(unix)] -fn wb() -> c_int { O_WRONLY as c_int } - -let mut fflags: c_int = wb(); -}" - .to_string(), - ); - }) -} - -#[test] -fn crlf_doc_comments() { - create_default_session_globals_then(|| { - let psess = psess(); - - let name_1 = FileName::Custom("crlf_source_1".to_string()); - let source = "/// doc comment\r\nfn foo() {}".to_string(); - let item = parse_item_from_source_str(name_1, source, &psess).unwrap().unwrap(); - let doc = item.attrs.iter().filter_map(|at| at.doc_str()).next().unwrap(); - assert_eq!(doc.as_str(), " doc comment"); - - let name_2 = FileName::Custom("crlf_source_2".to_string()); - let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string(); - let item = parse_item_from_source_str(name_2, source, &psess).unwrap().unwrap(); - let docs = item.attrs.iter().filter_map(|at| at.doc_str()).collect::>(); - let b: &[_] = &[Symbol::intern(" doc comment"), Symbol::intern(" line 2")]; - assert_eq!(&docs[..], b); - - let name_3 = FileName::Custom("clrf_source_3".to_string()); - let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string(); - let item = parse_item_from_source_str(name_3, source, &psess).unwrap().unwrap(); - let doc = item.attrs.iter().filter_map(|at| at.doc_str()).next().unwrap(); - assert_eq!(doc.as_str(), " doc comment\n * with CRLF "); - }); -} - -#[test] -fn ttdelim_span() { - fn parse_expr_from_source_str( - name: FileName, - source: String, - psess: &ParseSess, - ) -> PResult<'_, P> { - new_parser_from_source_str(psess, name, source).parse_expr() - } - - create_default_session_globals_then(|| { - let psess = psess(); - let expr = parse_expr_from_source_str( - PathBuf::from("foo").into(), - "foo!( fn main() { body } )".to_string(), - &psess, - ) - .unwrap(); - - let ast::ExprKind::MacCall(mac) = &expr.kind else { panic!("not a macro") }; - let span = mac.args.tokens.trees().last().unwrap().span(); - - match psess.source_map().span_to_snippet(span) { - Ok(s) => assert_eq!(&s[..], "{ body }"), - Err(_) => panic!("could not get snippet"), - } - }); -} - -// This tests that when parsing a string (rather than a file) we don't try -// and read in a file for a module declaration and just parse a stub. -// See `recurse_into_file_modules` in the parser. -#[test] -fn out_of_line_mod() { - create_default_session_globals_then(|| { - let item = parse_item_from_source_str( - PathBuf::from("foo").into(), - "mod foo { struct S; mod this_does_not_exist; }".to_owned(), - &psess(), - ) - .unwrap() - .unwrap(); - - let ast::ItemKind::Mod(_, mod_kind) = &item.kind else { panic!() }; - assert!(matches!(mod_kind, ast::ModKind::Loaded(items, ..) if items.len() == 2)); - }); -} - -#[test] -fn eqmodws() { - assert_eq!(matches_codepattern("", ""), true); - assert_eq!(matches_codepattern("", "a"), false); - assert_eq!(matches_codepattern("a", ""), false); - assert_eq!(matches_codepattern("a", "a"), true); - assert_eq!(matches_codepattern("a b", "a \n\t\r b"), true); - assert_eq!(matches_codepattern("a b ", "a \n\t\r b"), true); - assert_eq!(matches_codepattern("a b", "a \n\t\r b "), false); - assert_eq!(matches_codepattern("a b", "a b"), true); - assert_eq!(matches_codepattern("ab", "a b"), false); - assert_eq!(matches_codepattern("a b", "ab"), true); - assert_eq!(matches_codepattern(" a b", "ab"), true); -} - -#[test] -fn pattern_whitespace() { - assert_eq!(matches_codepattern("", "\x0C"), false); - assert_eq!(matches_codepattern("a b ", "a \u{0085}\n\t\r b"), true); - assert_eq!(matches_codepattern("a b", "a \u{0085}\n\t\r b "), false); -} - -#[test] -fn non_pattern_whitespace() { - // These have the property 'White_Space' but not 'Pattern_White_Space' - assert_eq!(matches_codepattern("a b", "a\u{2002}b"), false); - assert_eq!(matches_codepattern("a b", "a\u{2002}b"), false); - assert_eq!(matches_codepattern("\u{205F}a b", "ab"), false); - assert_eq!(matches_codepattern("a \u{3000}b", "ab"), false); -} diff --git a/compiler/rustc_expand/src/placeholders.rs b/compiler/rustc_expand/src/placeholders.rs index 581d71875bd07..7026425e167c8 100644 --- a/compiler/rustc_expand/src/placeholders.rs +++ b/compiler/rustc_expand/src/placeholders.rs @@ -9,7 +9,7 @@ use rustc_span::DUMMY_SP; use smallvec::{smallvec, SmallVec}; use thin_vec::ThinVec; -pub fn placeholder( +pub(crate) fn placeholder( kind: AstFragmentKind, id: ast::NodeId, vis: Option, diff --git a/compiler/rustc_feature/src/accepted.rs b/compiler/rustc_feature/src/accepted.rs index 943cc63285787..bb6a54fae7072 100644 --- a/compiler/rustc_feature/src/accepted.rs +++ b/compiler/rustc_feature/src/accepted.rs @@ -162,6 +162,8 @@ declare_features! ( (accepted, drop_types_in_const, "1.22.0", Some(33156)), /// Allows using `dyn Trait` as a syntax for trait objects. (accepted, dyn_trait, "1.27.0", Some(44662)), + /// Allows `X..Y` patterns. + (accepted, exclusive_range_pattern, "CURRENT_RUSTC_VERSION", Some(37854)), /// Allows integer match exhaustiveness checking (RFC 2591). (accepted, exhaustive_integer_patterns, "1.33.0", Some(50907)), /// Allows explicit generic arguments specification with `impl Trait` present. diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 9d3aac66c4103..dbb88e42a3eb9 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -396,10 +396,6 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ ), // Entry point: - gated!( - unix_sigpipe, Normal, template!(NameValueStr: "inherit|sig_ign|sig_dfl"), ErrorFollowing, - EncodeCrossCrate::Yes, experimental!(unix_sigpipe) - ), ungated!(start, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::No), ungated!(no_start, CrateLevel, template!(Word), WarnFollowing, EncodeCrossCrate::No), ungated!(no_main, CrateLevel, template!(Word), WarnFollowing, EncodeCrossCrate::No), @@ -522,7 +518,7 @@ pub const BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[ // RFC 2397 gated!( do_not_recommend, Normal, template!(Word), WarnFollowing, - EncodeCrossCrate::No, experimental!(do_not_recommend) + EncodeCrossCrate::Yes, experimental!(do_not_recommend) ), // `#[cfi_encoding = ""]` diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index e7d7a9f380b19..60b386acf9106 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -454,8 +454,6 @@ declare_features! ( (incomplete, dyn_star, "1.65.0", Some(102425)), /// Uses generic effect parameters for ~const bounds (unstable, effects, "1.72.0", Some(102090)), - /// Allows `X..Y` patterns. - (unstable, exclusive_range_pattern, "1.11.0", Some(37854)), /// Allows exhaustive pattern matching on types that contain uninhabited types. (unstable, exhaustive_patterns, "1.13.0", Some(51085)), /// Allows explicit tail calls via `become` expression. @@ -581,6 +579,9 @@ declare_features! ( (incomplete, repr128, "1.16.0", Some(56071)), /// Allows `repr(simd)` and importing the various simd intrinsics. (unstable, repr_simd, "1.4.0", Some(27731)), + /// Allows enums like Result to be used across FFI, if T's niche value can + /// be used to describe E or vise-versa. + (unstable, result_ffi_guarantees, "CURRENT_RUSTC_VERSION", Some(110503)), /// Allows bounding the return type of AFIT/RPITIT. (incomplete, return_type_notation, "1.70.0", Some(109417)), /// Allows `extern "rust-cold"`. @@ -619,8 +620,6 @@ declare_features! ( /// Allows creation of instances of a struct by moving fields that have /// not changed from prior instances of the same struct (RFC #2528) (unstable, type_changing_struct_update, "1.58.0", Some(86555)), - /// Enables rustc to generate code that instructs libstd to NOT ignore SIGPIPE. - (unstable, unix_sigpipe, "1.65.0", Some(97889)), /// Allows unnamed fields of struct and union type (incomplete, unnamed_fields, "1.74.0", Some(49804)), /// Allows unsized fn parameters. diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index fc8f7466694c7..244c479120dc2 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -229,9 +229,8 @@ impl<'hir> PathSegment<'hir> { } #[derive(Clone, Copy, Debug, HashStable_Generic)] -pub struct ConstArg { - pub value: AnonConst, - pub span: Span, +pub struct ConstArg<'hir> { + pub value: &'hir AnonConst, /// Indicates whether this comes from a `~const` desugaring. pub is_desugared_from_effects: bool, } @@ -252,7 +251,7 @@ impl InferArg { pub enum GenericArg<'hir> { Lifetime(&'hir Lifetime), Type(&'hir Ty<'hir>), - Const(ConstArg), + Const(ConstArg<'hir>), Infer(InferArg), } @@ -261,7 +260,7 @@ impl GenericArg<'_> { match self { GenericArg::Lifetime(l) => l.ident.span, GenericArg::Type(t) => t.span, - GenericArg::Const(c) => c.span, + GenericArg::Const(c) => c.value.span, GenericArg::Infer(i) => i.span, } } @@ -490,7 +489,7 @@ pub enum GenericParamKind<'hir> { Const { ty: &'hir Ty<'hir>, /// Optional default value for the const generic param - default: Option, + default: Option<&'hir AnonConst>, is_host_effect: bool, }, } @@ -1562,12 +1561,12 @@ impl fmt::Display for ConstContext { pub type Lit = Spanned; #[derive(Copy, Clone, Debug, HashStable_Generic)] -pub enum ArrayLen { +pub enum ArrayLen<'hir> { Infer(InferArg), - Body(AnonConst), + Body(&'hir AnonConst), } -impl ArrayLen { +impl ArrayLen<'_> { pub fn hir_id(&self) -> HirId { match self { ArrayLen::Infer(InferArg { hir_id, .. }) | ArrayLen::Body(AnonConst { hir_id, .. }) => { @@ -1590,6 +1589,7 @@ pub struct AnonConst { pub hir_id: HirId, pub def_id: LocalDefId, pub body: BodyId, + pub span: Span, } /// An inline constant expression `const { something }`. @@ -2002,7 +2002,7 @@ pub enum ExprKind<'hir> { /// /// E.g., `[1; 5]`. The first expression is the element /// to be repeated; the second is the number of times to repeat it. - Repeat(&'hir Expr<'hir>, ArrayLen), + Repeat(&'hir Expr<'hir>, ArrayLen<'hir>), /// A suspension point for coroutines (i.e., `yield `). Yield(&'hir Expr<'hir>, YieldSource), @@ -2382,7 +2382,7 @@ pub struct TypeBinding<'hir> { #[derive(Debug, Clone, Copy, HashStable_Generic)] pub enum Term<'hir> { Ty(&'hir Ty<'hir>), - Const(AnonConst), + Const(&'hir AnonConst), } impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> { @@ -2391,8 +2391,8 @@ impl<'hir> From<&'hir Ty<'hir>> for Term<'hir> { } } -impl<'hir> From for Term<'hir> { - fn from(c: AnonConst) -> Self { +impl<'hir> From<&'hir AnonConst> for Term<'hir> { + fn from(c: &'hir AnonConst) -> Self { Term::Const(c) } } @@ -2683,7 +2683,7 @@ pub enum TyKind<'hir> { /// A variable length slice (i.e., `[T]`). Slice(&'hir Ty<'hir>), /// A fixed length array (i.e., `[T; n]`). - Array(&'hir Ty<'hir>, ArrayLen), + Array(&'hir Ty<'hir>, ArrayLen<'hir>), /// A raw pointer (i.e., `*const T` or `*mut T`). Ptr(MutTy<'hir>), /// A reference (i.e., `&'a T` or `&'a mut T`). @@ -2712,7 +2712,7 @@ pub enum TyKind<'hir> { /// where `Bound` is a trait or a lifetime. TraitObject(&'hir [PolyTraitRef<'hir>], &'hir Lifetime, TraitObjectSyntax), /// Unused for now. - Typeof(AnonConst), + Typeof(&'hir AnonConst), /// `TyKind::Infer` means the type should be inferred instead of it having been /// specified. This can appear anywhere in a type. Infer, @@ -2745,10 +2745,10 @@ pub enum InlineAsmOperand<'hir> { out_expr: Option<&'hir Expr<'hir>>, }, Const { - anon_const: AnonConst, + anon_const: &'hir AnonConst, }, SymFn { - anon_const: AnonConst, + anon_const: &'hir AnonConst, }, SymStatic { path: QPath<'hir>, @@ -2950,7 +2950,7 @@ pub struct Variant<'hir> { /// Fields and constructor id of the variant. pub data: VariantData<'hir>, /// Explicit discriminant (e.g., `Foo = 1`). - pub disr_expr: Option, + pub disr_expr: Option<&'hir AnonConst>, /// Span pub span: Span, } @@ -3479,15 +3479,13 @@ impl<'hir> OwnerNode<'hir> { } } - // Span by reference to pass to `Node::Err`. - #[allow(rustc::pass_by_value)] - pub fn span(&self) -> &'hir Span { + pub fn span(&self) -> Span { match self { OwnerNode::Item(Item { span, .. }) | OwnerNode::ForeignItem(ForeignItem { span, .. }) | OwnerNode::ImplItem(ImplItem { span, .. }) - | OwnerNode::TraitItem(TraitItem { span, .. }) => span, - OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => inner_span, + | OwnerNode::TraitItem(TraitItem { span, .. }) => *span, + OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span, OwnerNode::Synthetic => unreachable!(), } } @@ -3632,9 +3630,7 @@ pub enum Node<'hir> { PreciseCapturingNonLifetimeArg(&'hir PreciseCapturingNonLifetimeArg), // Created by query feeding Synthetic, - // Span by reference to minimize `Node`'s size - #[allow(rustc::pass_by_value)] - Err(&'hir Span), + Err(Span), } impl<'hir> Node<'hir> { @@ -3871,7 +3867,7 @@ mod size_asserts { static_assert_size!(FnDecl<'_>, 40); static_assert_size!(ForeignItem<'_>, 72); static_assert_size!(ForeignItemKind<'_>, 40); - static_assert_size!(GenericArg<'_>, 32); + static_assert_size!(GenericArg<'_>, 24); static_assert_size!(GenericBound<'_>, 48); static_assert_size!(Generics<'_>, 56); static_assert_size!(Impl<'_>, 80); diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index cd9f9ff9109c1..fa89a4a44ef5a 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -338,7 +338,7 @@ pub trait Visitor<'v>: Sized { fn visit_pat_field(&mut self, f: &'v PatField<'v>) -> Self::Result { walk_pat_field(self, f) } - fn visit_array_length(&mut self, len: &'v ArrayLen) -> Self::Result { + fn visit_array_length(&mut self, len: &'v ArrayLen<'v>) -> Self::Result { walk_array_len(self, len) } fn visit_anon_const(&mut self, c: &'v AnonConst) -> Self::Result { @@ -703,7 +703,7 @@ pub fn walk_pat_field<'v, V: Visitor<'v>>(visitor: &mut V, field: &'v PatField<' visitor.visit_pat(field.pat) } -pub fn walk_array_len<'v, V: Visitor<'v>>(visitor: &mut V, len: &'v ArrayLen) -> V::Result { +pub fn walk_array_len<'v, V: Visitor<'v>>(visitor: &mut V, len: &'v ArrayLen<'v>) -> V::Result { match len { // FIXME: Use `visit_infer` here. ArrayLen::Infer(InferArg { hir_id, span: _ }) => visitor.visit_id(*hir_id), diff --git a/compiler/rustc_hir_analysis/src/autoderef.rs b/compiler/rustc_hir_analysis/src/autoderef.rs index f2ceb4702643a..f101c595bdf35 100644 --- a/compiler/rustc_hir_analysis/src/autoderef.rs +++ b/compiler/rustc_hir_analysis/src/autoderef.rs @@ -1,6 +1,6 @@ use crate::errors::AutoDerefReachedRecursionLimit; +use crate::traits; use crate::traits::query::evaluate_obligation::InferCtxtExt; -use crate::traits::{self, TraitEngine, TraitEngineExt}; use rustc_infer::infer::InferCtxt; use rustc_middle::ty::TypeVisitableExt; use rustc_middle::ty::{self, Ty, TyCtxt}; @@ -8,7 +8,7 @@ use rustc_session::Limit; use rustc_span::def_id::LocalDefId; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::Span; -use rustc_trait_selection::traits::StructurallyNormalizeExt; +use rustc_trait_selection::traits::ObligationCtxt; #[derive(Copy, Clone, Debug)] pub enum AutoderefKind { @@ -167,25 +167,19 @@ impl<'a, 'tcx> Autoderef<'a, 'tcx> { &self, ty: Ty<'tcx>, ) -> Option<(Ty<'tcx>, Vec>)> { - let mut fulfill_cx = >::new(self.infcx); - - let cause = traits::ObligationCause::misc(self.span, self.body_id); - let normalized_ty = match self - .infcx - .at(&cause, self.param_env) - .structurally_normalize(ty, &mut *fulfill_cx) - { - Ok(normalized_ty) => normalized_ty, - Err(errors) => { - // This shouldn't happen, except for evaluate/fulfill mismatches, - // but that's not a reason for an ICE (`predicate_may_hold` is conservative - // by design). - debug!(?errors, "encountered errors while fulfilling"); - return None; - } + let ocx = ObligationCtxt::new(self.infcx); + let Ok(normalized_ty) = ocx.structurally_normalize( + &traits::ObligationCause::misc(self.span, self.body_id), + self.param_env, + ty, + ) else { + // We shouldn't have errors here, except for evaluate/fulfill mismatches, + // but that's not a reason for an ICE (`predicate_may_hold` is conservative + // by design). + // FIXME(-Znext-solver): This *actually* shouldn't happen then. + return None; }; - - let errors = fulfill_cx.select_where_possible(self.infcx); + let errors = ocx.select_where_possible(); if !errors.is_empty() { // This shouldn't happen, except for evaluate/fulfill mismatches, // but that's not a reason for an ICE (`predicate_may_hold` is conservative @@ -194,7 +188,7 @@ impl<'a, 'tcx> Autoderef<'a, 'tcx> { return None; } - Some((normalized_ty, fulfill_cx.pending_obligations())) + Some((normalized_ty, ocx.into_pending_obligations())) } /// Returns the final type we ended up with, which may be an inference diff --git a/compiler/rustc_hir_analysis/src/bounds.rs b/compiler/rustc_hir_analysis/src/bounds.rs index aafb5c1c0b4bc..5562b81871fc7 100644 --- a/compiler/rustc_hir_analysis/src/bounds.rs +++ b/compiler/rustc_hir_analysis/src/bounds.rs @@ -23,7 +23,7 @@ use rustc_span::Span; /// include the self type (e.g., `trait_bounds`) but in others we do not #[derive(Default, PartialEq, Eq, Clone, Debug)] pub struct Bounds<'tcx> { - pub clauses: Vec<(ty::Clause<'tcx>, Span)>, + clauses: Vec<(ty::Clause<'tcx>, Span)>, } impl<'tcx> Bounds<'tcx> { diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 0f0736f87568b..9198ceb8f59db 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -143,7 +143,7 @@ impl<'v> Visitor<'v> for HirPlaceholderCollector { _ => {} } } - fn visit_array_length(&mut self, length: &'v hir::ArrayLen) { + fn visit_array_length(&mut self, length: &'v hir::ArrayLen<'v>) { if let hir::ArrayLen::Infer(inf) = length { self.0.push(inf.span); } diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index 9d7deebac48e4..5ccfd06f25822 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -24,7 +24,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { let hir_id = tcx.local_def_id_to_hir_id(def_id); let node = tcx.hir_node(hir_id); - let Node::AnonConst(_) = node else { + let Node::AnonConst(&AnonConst { span, .. }) = node else { span_bug!( tcx.def_span(def_id), "expected anon const in `anon_const_type_of`, got {node:?}" @@ -134,7 +134,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { // I dont think it's possible to reach this but I'm not 100% sure - BoxyUwU return Ty::new_error_with_message( tcx, - tcx.def_span(def_id), + span, "unexpected non-GAT usage of an anon const", ); } @@ -152,7 +152,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { let Some(type_dependent_def) = tables.type_dependent_def_id(parent_node_id) else { return Ty::new_error_with_message( tcx, - tcx.def_span(def_id), + span, format!("unable to find type-dependent def for {parent_node_id:?}"), ); }; @@ -194,7 +194,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { } else { return Ty::new_error_with_message( tcx, - tcx.def_span(def_id), + span, format!("unable to find const parent for {hir_id} in pat {pat:?}"), ); } @@ -202,7 +202,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { _ => { return Ty::new_error_with_message( tcx, - tcx.def_span(def_id), + span, format!("unexpected const parent path {parent_node:?}"), ); } @@ -226,11 +226,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { .map(|idx| (idx, seg)) }) }) else { - return Ty::new_error_with_message( - tcx, - tcx.def_span(def_id), - "no arg matching AnonConst in path", - ); + return Ty::new_error_with_message(tcx, span, "no arg matching AnonConst in path"); }; let generics = match tcx.res_generics_def_id(segment.res) { @@ -238,7 +234,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { None => { return Ty::new_error_with_message( tcx, - tcx.def_span(def_id), + span, format!("unexpected anon const res {:?} in path: {:?}", segment.res, path), ); } @@ -250,7 +246,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { _ => { return Ty::new_error_with_message( tcx, - tcx.def_span(def_id), + span, format!("unexpected const parent in type_of(): {parent_node:?}"), ); } @@ -278,7 +274,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { } else { return Ty::new_error_with_message( tcx, - tcx.def_span(def_id), + span, format!("const generic parameter not found in {generics:?} at position {arg_idx:?}"), ); } diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 285b99c2c69d5..4f5fbd024a998 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -968,7 +968,7 @@ impl<'a> State<'a> { self.print_else(elseopt) } - fn print_array_length(&mut self, len: &hir::ArrayLen) { + fn print_array_length(&mut self, len: &hir::ArrayLen<'_>) { match len { hir::ArrayLen::Infer(..) => self.word("_"), hir::ArrayLen::Body(ct) => self.print_anon_const(ct), @@ -1052,7 +1052,7 @@ impl<'a> State<'a> { self.end() } - fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::ArrayLen) { + fn print_expr_repeat(&mut self, element: &hir::Expr<'_>, count: &hir::ArrayLen<'_>) { self.ibox(INDENT_UNIT); self.word("["); self.print_expr(element); diff --git a/compiler/rustc_hir_typeck/Cargo.toml b/compiler/rustc_hir_typeck/Cargo.toml index 9e7f0776b6087..73a775690d66b 100644 --- a/compiler/rustc_hir_typeck/Cargo.toml +++ b/compiler/rustc_hir_typeck/Cargo.toml @@ -12,7 +12,6 @@ rustc_attr = { path = "../rustc_attr" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_fluent_macro = { path = "../rustc_fluent_macro" } -rustc_graphviz = { path = "../rustc_graphviz" } rustc_hir = { path = "../rustc_hir" } rustc_hir_analysis = { path = "../rustc_hir_analysis" } rustc_hir_pretty = { path = "../rustc_hir_pretty" } diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 825276aef421c..df92af876f612 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -37,16 +37,13 @@ use crate::errors::SuggestBoxingForReturnImplTrait; use crate::FnCtxt; -use rustc_errors::{codes::*, struct_span_code_err, Applicability, Diag, MultiSpan}; +use rustc_errors::{codes::*, struct_span_code_err, Applicability, Diag}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::Expr; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; use rustc_infer::infer::type_variable::TypeVariableOrigin; use rustc_infer::infer::{Coercion, DefineOpaqueTypes, InferOk, InferResult}; -use rustc_infer::traits::TraitEngineExt as _; -use rustc_infer::traits::{IfExpressionCause, MatchExpressionArmCause, TraitEngine}; +use rustc_infer::traits::{IfExpressionCause, MatchExpressionArmCause}; use rustc_infer::traits::{Obligation, PredicateObligation}; use rustc_middle::lint::in_external_macro; use rustc_middle::traits::BuiltinImplSource; @@ -65,7 +62,6 @@ use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::traits::error_reporting::suggestions::TypeErrCtxtExt; use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; -use rustc_trait_selection::traits::TraitEngineExt as _; use rustc_trait_selection::traits::{ self, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt, }; @@ -95,22 +91,6 @@ impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> { type CoerceResult<'tcx> = InferResult<'tcx, (Vec>, Ty<'tcx>)>; -struct CollectRetsVisitor<'tcx> { - ret_exprs: Vec<&'tcx hir::Expr<'tcx>>, -} - -impl<'tcx> Visitor<'tcx> for CollectRetsVisitor<'tcx> { - fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) { - match expr.kind { - hir::ExprKind::Ret(_) => self.ret_exprs.push(expr), - // `return` in closures does not return from the outer function - hir::ExprKind::Closure(_) => return, - _ => {} - } - intravisit::walk_expr(self, expr); - } -} - /// Coercing a mutable reference to an immutable works, while /// coercing `&T` to `&mut T` should be forbidden. fn coerce_mutbls<'tcx>( @@ -164,11 +144,10 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // Filter these cases out to make sure our coercion is more accurate. match res { Ok(InferOk { value, obligations }) if self.next_trait_solver() => { - let mut fulfill_cx = >::new(self); - fulfill_cx.register_predicate_obligations(self, obligations); - let errs = fulfill_cx.select_where_possible(self); - if errs.is_empty() { - Ok(InferOk { value, obligations: fulfill_cx.pending_obligations() }) + let ocx = ObligationCtxt::new(self); + ocx.register_obligations(obligations); + if ocx.select_where_possible().is_empty() { + Ok(InferOk { value, obligations: ocx.into_pending_obligations() }) } else { Err(TypeError::Mismatch) } @@ -631,13 +610,12 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // but we need to constrain vars before processing goals mentioning // them. Some(ty::PredicateKind::AliasRelate(..)) => { - let mut fulfill_cx = >::new(self); - fulfill_cx.register_predicate_obligation(self, obligation); - let errs = fulfill_cx.select_where_possible(self); - if !errs.is_empty() { + let ocx = ObligationCtxt::new(self); + ocx.register_obligation(obligation); + if !ocx.select_where_possible().is_empty() { return Err(TypeError::Mismatch); } - coercion.obligations.extend(fulfill_cx.pending_obligations()); + coercion.obligations.extend(ocx.into_pending_obligations()); continue; } _ => { @@ -1601,7 +1579,6 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { let mut err; let mut unsized_return = false; - let mut visitor = CollectRetsVisitor { ret_exprs: vec![] }; match *cause.code() { ObligationCauseCode::ReturnNoExpression => { err = struct_span_code_err!( @@ -1636,11 +1613,6 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { if !fcx.tcx.features().unsized_locals { unsized_return = self.is_return_ty_definitely_unsized(fcx); } - if let Some(expression) = expression - && let hir::ExprKind::Loop(loop_blk, ..) = expression.kind - { - intravisit::walk_block(&mut visitor, loop_blk); - } } ObligationCauseCode::ReturnValue(id) => { err = self.report_return_mismatched_types( @@ -1741,6 +1713,22 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { augment_error(&mut err); if let Some(expr) = expression { + if let hir::ExprKind::Loop( + _, + _, + loop_src @ (hir::LoopSource::While | hir::LoopSource::ForLoop), + _, + ) = expr.kind + { + let loop_type = if loop_src == hir::LoopSource::While { + "`while` loops" + } else { + "`for` loops" + }; + + err.note(format!("{loop_type} evaluate to unit type `()`")); + } + fcx.emit_coerce_suggestions( &mut err, expr, @@ -1749,15 +1737,6 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { None, Some(coercion_error), ); - if visitor.ret_exprs.len() > 0 { - self.note_unreachable_loop_return( - &mut err, - fcx.tcx, - &expr, - &visitor.ret_exprs, - expected, - ); - } } let reported = err.emit_unless(unsized_return); @@ -1831,110 +1810,6 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { ); } - fn note_unreachable_loop_return( - &self, - err: &mut Diag<'_>, - tcx: TyCtxt<'tcx>, - expr: &hir::Expr<'tcx>, - ret_exprs: &Vec<&'tcx hir::Expr<'tcx>>, - ty: Ty<'tcx>, - ) { - let hir::ExprKind::Loop(_, _, _, loop_span) = expr.kind else { - return; - }; - let mut span: MultiSpan = vec![loop_span].into(); - span.push_span_label(loop_span, "this might have zero elements to iterate on"); - const MAXITER: usize = 3; - let iter = ret_exprs.iter().take(MAXITER); - for ret_expr in iter { - span.push_span_label( - ret_expr.span, - "if the loop doesn't execute, this value would never get returned", - ); - } - err.span_note( - span, - "the function expects a value to always be returned, but loops might run zero times", - ); - if MAXITER < ret_exprs.len() { - err.note(format!( - "if the loop doesn't execute, {} other values would never get returned", - ret_exprs.len() - MAXITER - )); - } - let hir = tcx.hir(); - let item = hir.get_parent_item(expr.hir_id); - let ret_msg = "return a value for the case when the loop has zero elements to iterate on"; - let ret_ty_msg = - "otherwise consider changing the return type to account for that possibility"; - let node = tcx.hir_node(item.into()); - if let Some(body_id) = node.body_id() - && let Some(sig) = node.fn_sig() - && let hir::ExprKind::Block(block, _) = hir.body(body_id).value.kind - && !ty.is_never() - { - let indentation = if let None = block.expr - && let [.., last] = &block.stmts - { - tcx.sess.source_map().indentation_before(last.span).unwrap_or_else(String::new) - } else if let Some(expr) = block.expr { - tcx.sess.source_map().indentation_before(expr.span).unwrap_or_else(String::new) - } else { - String::new() - }; - if let None = block.expr - && let [.., last] = &block.stmts - { - err.span_suggestion_verbose( - last.span.shrink_to_hi(), - ret_msg, - format!("\n{indentation}/* `{ty}` value */"), - Applicability::MaybeIncorrect, - ); - } else if let Some(expr) = block.expr { - err.span_suggestion_verbose( - expr.span.shrink_to_hi(), - ret_msg, - format!("\n{indentation}/* `{ty}` value */"), - Applicability::MaybeIncorrect, - ); - } - let mut sugg = match sig.decl.output { - hir::FnRetTy::DefaultReturn(span) => { - vec![(span, " -> Option<()>".to_string())] - } - hir::FnRetTy::Return(ty) => { - vec![ - (ty.span.shrink_to_lo(), "Option<".to_string()), - (ty.span.shrink_to_hi(), ">".to_string()), - ] - } - }; - for ret_expr in ret_exprs { - match ret_expr.kind { - hir::ExprKind::Ret(Some(expr)) => { - sugg.push((expr.span.shrink_to_lo(), "Some(".to_string())); - sugg.push((expr.span.shrink_to_hi(), ")".to_string())); - } - hir::ExprKind::Ret(None) => { - sugg.push((ret_expr.span.shrink_to_hi(), " Some(())".to_string())); - } - _ => {} - } - } - if let None = block.expr - && let [.., last] = &block.stmts - { - sugg.push((last.span.shrink_to_hi(), format!("\n{indentation}None"))); - } else if let Some(expr) = block.expr { - sugg.push((expr.span.shrink_to_hi(), format!("\n{indentation}None"))); - } - err.multipart_suggestion(ret_ty_msg, sugg, Applicability::MaybeIncorrect); - } else { - err.help(format!("{ret_msg}, {ret_ty_msg}")); - } - } - fn report_return_mismatched_types<'a>( &self, cause: &ObligationCause<'tcx>, diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 618d90a07ec29..60c0b1872fa03 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -57,7 +57,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { || self.suggest_into(err, expr, expr_ty, expected) || self.suggest_floating_point_literal(err, expr, expected) || self.suggest_null_ptr_for_literal_zero_given_to_ptr_arg(err, expr, expected) - || self.suggest_coercing_result_via_try_operator(err, expr, expected, expr_ty); + || self.suggest_coercing_result_via_try_operator(err, expr, expected, expr_ty) + || self.suggest_returning_value_after_loop(err, expr, expected); if !suggested { self.note_source_of_type_mismatch_constraint( diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 8b1ea7c952cb1..7b552bb707743 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -1444,7 +1444,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; }; if let hir::TyKind::Array(_, length) = ty.peel_refs().kind - && let hir::ArrayLen::Body(hir::AnonConst { hir_id, .. }) = length + && let hir::ArrayLen::Body(&hir::AnonConst { hir_id, .. }) = length { let span = self.tcx.hir().span(hir_id); self.dcx().try_steal_modify_and_emit_err( @@ -1483,7 +1483,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn check_expr_repeat( &self, element: &'tcx hir::Expr<'tcx>, - count: &'tcx hir::ArrayLen, + count: &'tcx hir::ArrayLen<'tcx>, expected: Expectation<'tcx>, expr: &'tcx hir::Expr<'tcx>, ) -> Ty<'tcx> { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 2060e08aacf97..552747bdc5272 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -438,7 +438,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - pub fn lower_array_length(&self, length: &hir::ArrayLen) -> ty::Const<'tcx> { + pub fn lower_array_length(&self, length: &hir::ArrayLen<'tcx>) -> ty::Const<'tcx> { match length { hir::ArrayLen::Infer(inf) => self.ct_infer(self.tcx.types.usize, None, inf.span), hir::ArrayLen::Body(anon_const) => { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 133778a416cc2..d00fea4fae498 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -18,8 +18,8 @@ use rustc_hir::def::Res; use rustc_hir::def::{CtorKind, CtorOf, DefKind}; use rustc_hir::lang_items::LangItem; use rustc_hir::{ - CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, ExprKind, GenericBound, HirId, Node, - Path, QPath, Stmt, StmtKind, TyKind, WherePredicate, + Arm, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, ExprKind, GenericBound, HirId, + Node, Path, QPath, Stmt, StmtKind, TyKind, WherePredicate, }; use rustc_hir_analysis::collect::suggest_impl_trait; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; @@ -1942,6 +1942,91 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { false } + // If the expr is a while or for loop and is the tail expr of its + // enclosing body suggest returning a value right after it + pub fn suggest_returning_value_after_loop( + &self, + err: &mut Diag<'_>, + expr: &hir::Expr<'tcx>, + expected: Ty<'tcx>, + ) -> bool { + let hir = self.tcx.hir(); + let enclosing_scope = + hir.get_enclosing_scope(expr.hir_id).map(|hir_id| self.tcx.hir_node(hir_id)); + + // Get tail expr of the enclosing block or body + let tail_expr = if let Some(Node::Block(hir::Block { expr, .. })) = enclosing_scope + && expr.is_some() + { + *expr + } else { + let body_def_id = hir.enclosing_body_owner(expr.hir_id); + let body_id = hir.body_owned_by(body_def_id); + let body = hir.body(body_id); + + // Get tail expr of the body + match body.value.kind { + // Regular function body etc. + hir::ExprKind::Block(block, _) => block.expr, + // Anon const body (there's no block in this case) + hir::ExprKind::DropTemps(expr) => Some(expr), + _ => None, + } + }; + + let Some(tail_expr) = tail_expr else { + return false; // Body doesn't have a tail expr we can compare with + }; + + // Get the loop expr within the tail expr + let loop_expr_in_tail = match expr.kind { + hir::ExprKind::Loop(_, _, hir::LoopSource::While, _) => tail_expr, + hir::ExprKind::Loop(_, _, hir::LoopSource::ForLoop, _) => { + match tail_expr.peel_drop_temps() { + Expr { kind: ExprKind::Match(_, [Arm { body, .. }], _), .. } => body, + _ => return false, // Not really a for loop + } + } + _ => return false, // Not a while or a for loop + }; + + // If the expr is the loop expr in the tail + // then make the suggestion + if expr.hir_id == loop_expr_in_tail.hir_id { + let span = expr.span; + + let (msg, suggestion) = if expected.is_never() { + ( + "consider adding a diverging expression here", + "`loop {}` or `panic!(\"...\")`".to_string(), + ) + } else { + ("consider returning a value here", format!("`{expected}` value")) + }; + + let src_map = self.tcx.sess.source_map(); + let suggestion = if src_map.is_multiline(expr.span) { + let indentation = src_map.indentation_before(span).unwrap_or_else(String::new); + format!("\n{indentation}/* {suggestion} */") + } else { + // If the entire expr is on a single line + // put the suggestion also on the same line + format!(" /* {suggestion} */") + }; + + err.span_suggestion_verbose( + span.shrink_to_hi(), + msg, + suggestion, + Applicability::MaybeIncorrect, + ); + + true + } else { + false + } + } + /// If the expected type is an enum (Issue #55250) with any variants whose /// sole field is of the found type, suggest such variants. (Issue #42764) pub(crate) fn suggest_compatible_variants( diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 382dba5f95fb9..8c7ae7f8e980d 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -10,7 +10,6 @@ use rustc_hir::pat_util::EnumerateAndAdjustIterator; use rustc_hir::{self as hir, BindingMode, ByRef, HirId, Mutability, Pat, PatKind}; use rustc_infer::infer; use rustc_infer::infer::type_variable::TypeVariableOrigin; -use rustc_lint as lint; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::ty::{self, Ty, TypeVisitableExt}; use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS; @@ -684,7 +683,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { { // `mut x` resets the binding mode in edition <= 2021. self.tcx.emit_node_span_lint( - lint::builtin::DEREFERENCING_MUT_BINDING, + rustc_lint::builtin::DEREFERENCING_MUT_BINDING, pat.hir_id, pat.span, errors::DereferencingMutBinding { span: pat.span }, diff --git a/compiler/rustc_incremental/src/persist/fs.rs b/compiler/rustc_incremental/src/persist/fs.rs index 3d7c0cfc30aa3..193042b8cdf25 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -104,10 +104,14 @@ //! implemented. use crate::errors; +use rustc_data_structures::base_n; +use rustc_data_structures::base_n::BaseNString; +use rustc_data_structures::base_n::ToBaseN; +use rustc_data_structures::base_n::CASE_INSENSITIVE; +use rustc_data_structures::flock; use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; use rustc_data_structures::svh::Svh; use rustc_data_structures::unord::{UnordMap, UnordSet}; -use rustc_data_structures::{base_n, flock}; use rustc_errors::ErrorGuaranteed; use rustc_fs_util::{link_or_copy, try_canonicalize, LinkOrCopy}; use rustc_middle::bug; @@ -333,31 +337,24 @@ pub fn finalize_session_directory(sess: &Session, svh: Option) { debug!("finalize_session_directory() - session directory: {}", incr_comp_session_dir.display()); - let old_sub_dir_name = incr_comp_session_dir + let mut sub_dir_name = incr_comp_session_dir .file_name() .unwrap() .to_str() - .expect("malformed session dir name: contains non-Unicode characters"); + .expect("malformed session dir name: contains non-Unicode characters") + .to_string(); - // Keep the 's-{timestamp}-{random-number}' prefix, but replace the - // '-working' part with the SVH of the crate - let dash_indices: Vec<_> = old_sub_dir_name.match_indices('-').map(|(idx, _)| idx).collect(); - if dash_indices.len() != 3 { - bug!( - "Encountered incremental compilation session directory with \ - malformed name: {}", - incr_comp_session_dir.display() - ) - } - - // State: "s-{timestamp}-{random-number}-" - let mut new_sub_dir_name = String::from(&old_sub_dir_name[..=dash_indices[2]]); + // Keep the 's-{timestamp}-{random-number}' prefix, but replace "working" with the SVH of the crate + sub_dir_name.truncate(sub_dir_name.len() - "working".len()); + // Double-check that we kept this: "s-{timestamp}-{random-number}-" + assert!(sub_dir_name.ends_with('-'), "{:?}", sub_dir_name); + assert!(sub_dir_name.as_bytes().iter().filter(|b| **b == b'-').count() == 3); - // Append the svh - base_n::push_str(svh.as_u128(), INT_ENCODE_BASE, &mut new_sub_dir_name); + // Append the SVH + sub_dir_name.push_str(&svh.as_u128().to_base_fixed_len(CASE_INSENSITIVE)); // Create the full path - let new_path = incr_comp_session_dir.parent().unwrap().join(new_sub_dir_name); + let new_path = incr_comp_session_dir.parent().unwrap().join(&*sub_dir_name); debug!("finalize_session_directory() - new path: {}", new_path.display()); match rename_path_with_retry(&*incr_comp_session_dir, &new_path, 3) { @@ -453,11 +450,11 @@ fn generate_session_dir_path(crate_dir: &Path) -> PathBuf { let random_number = thread_rng().next_u32(); debug!("generate_session_dir_path: random_number = {}", random_number); - let directory_name = format!( - "s-{}-{}-working", - timestamp, - base_n::encode(random_number as u128, INT_ENCODE_BASE) - ); + // Chop the first 3 characters off the timestamp. Those 3 bytes will be zero for a while. + let (zeroes, timestamp) = timestamp.split_at(3); + assert_eq!(zeroes, "000"); + let directory_name = + format!("s-{}-{}-working", timestamp, random_number.to_base_fixed_len(CASE_INSENSITIVE)); debug!("generate_session_dir_path: directory_name = {}", directory_name); let directory_path = crate_dir.join(directory_name); debug!("generate_session_dir_path: directory_path = {}", directory_path.display()); @@ -588,10 +585,10 @@ fn extract_timestamp_from_session_dir(directory_name: &str) -> Result String { +fn timestamp_to_string(timestamp: SystemTime) -> BaseNString { let duration = timestamp.duration_since(UNIX_EPOCH).unwrap(); let micros = duration.as_secs() * 1_000_000 + (duration.subsec_nanos() as u64) / 1000; - base_n::encode(micros as u128, INT_ENCODE_BASE) + micros.to_base_fixed_len(CASE_INSENSITIVE) } fn string_to_timestamp(s: &str) -> Result { @@ -622,9 +619,8 @@ fn crate_path(sess: &Session) -> PathBuf { sess.cfg_version, ); - let stable_crate_id = base_n::encode(stable_crate_id.as_u64() as u128, INT_ENCODE_BASE); - - let crate_name = format!("{crate_name}-{stable_crate_id}"); + let crate_name = + format!("{crate_name}-{}", stable_crate_id.as_u64().to_base_fixed_len(CASE_INSENSITIVE)); incr_dir.join(crate_name) } diff --git a/compiler/rustc_infer/src/traits/mod.rs b/compiler/rustc_infer/src/traits/mod.rs index e3611ab28e532..f77a611586180 100644 --- a/compiler/rustc_infer/src/traits/mod.rs +++ b/compiler/rustc_infer/src/traits/mod.rs @@ -206,6 +206,18 @@ impl<'tcx> FulfillmentError<'tcx> { ) -> FulfillmentError<'tcx> { FulfillmentError { obligation, code, root_obligation } } + + pub fn is_true_error(&self) -> bool { + match self.code { + FulfillmentErrorCode::SelectionError(_) + | FulfillmentErrorCode::ProjectionError(_) + | FulfillmentErrorCode::SubtypeError(_, _) + | FulfillmentErrorCode::ConstEquateError(_, _) => true, + FulfillmentErrorCode::Cycle(_) | FulfillmentErrorCode::Ambiguity { overflow: _ } => { + false + } + } + } } impl<'tcx> PolyTraitObligation<'tcx> { diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index b593c41a8eafa..76d5d7a3ac2fd 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -4,7 +4,6 @@ use crate::proc_macro_decls; use crate::util; use rustc_ast::{self as ast, visit}; -use rustc_borrowck as mir_borrowck; use rustc_codegen_ssa::traits::CodegenBackend; use rustc_data_structures::parallel; use rustc_data_structures::steal::Steal; @@ -20,7 +19,6 @@ use rustc_middle::arena::Arena; use rustc_middle::dep_graph::DepGraph; use rustc_middle::ty::{self, GlobalCtxt, RegisteredTools, TyCtxt}; use rustc_middle::util::Providers; -use rustc_mir_build as mir_build; use rustc_parse::{parse_crate_from_file, parse_crate_from_source_str, validate_attr}; use rustc_passes::{abi_test, hir_stats, layout_test}; use rustc_resolve::Resolver; @@ -616,8 +614,8 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock = LazyLock::new(|| { proc_macro_decls::provide(providers); rustc_const_eval::provide(providers); rustc_middle::hir::provide(providers); - mir_borrowck::provide(providers); - mir_build::provide(providers); + rustc_borrowck::provide(providers); + rustc_mir_build::provide(providers); rustc_mir_transform::provide(providers); rustc_monomorphize::provide(providers); rustc_privacy::provide(providers); diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index db150cc1f875d..36f9dda7250ca 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -20,7 +20,7 @@ use rustc_span::source_map::{RealFileLoader, SourceMapInputs}; use rustc_span::symbol::sym; use rustc_span::{FileName, SourceFileHashAlgorithm}; use rustc_target::spec::{ - CodeModel, LinkerFlavorCli, MergeFunctions, PanicStrategy, RelocModel, WasmCAbi, + CodeModel, LinkerFlavorCli, MergeFunctions, OnBrokenPipe, PanicStrategy, RelocModel, WasmCAbi, }; use rustc_target::spec::{RelroLevel, SanitizerSet, SplitDebuginfo, StackProtector, TlsModel}; use std::collections::{BTreeMap, BTreeSet}; @@ -809,6 +809,7 @@ fn test_unstable_options_tracking_hash() { tracked!(no_profiler_runtime, true); tracked!(no_trait_vptr, true); tracked!(no_unique_section_names, true); + tracked!(on_broken_pipe, OnBrokenPipe::Kill); tracked!(oom, OomStrategy::Panic); tracked!(osx_rpath_install_name, true); tracked!(packed_bundled_libs, true); diff --git a/compiler/rustc_interface/src/util.rs b/compiler/rustc_interface/src/util.rs index 02dcfe9c8dffb..ce4d382501522 100644 --- a/compiler/rustc_interface/src/util.rs +++ b/compiler/rustc_interface/src/util.rs @@ -7,18 +7,16 @@ use rustc_data_structures::sync; use rustc_metadata::{load_symbol_from_dylib, DylibError}; use rustc_middle::ty::CurrentGcx; use rustc_parse::validate_attr; -use rustc_session as session; -use rustc_session::config::{Cfg, OutFileName, OutputFilenames, OutputTypes}; +use rustc_session::config::{host_triple, Cfg, OutFileName, OutputFilenames, OutputTypes}; use rustc_session::filesearch::sysroot_candidates; use rustc_session::lint::{self, BuiltinLintDiag, LintBuffer}; -use rustc_session::{filesearch, Session}; +use rustc_session::output::{categorize_crate_type, CRATE_TYPES}; +use rustc_session::{filesearch, EarlyDiagCtxt, Session}; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::edition::Edition; use rustc_span::source_map::SourceMapInputs; use rustc_span::symbol::sym; use rustc_target::spec::Target; -use session::output::{categorize_crate_type, CRATE_TYPES}; -use session::EarlyDiagCtxt; use std::env::consts::{DLL_PREFIX, DLL_SUFFIX}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -286,7 +284,7 @@ fn get_codegen_sysroot( "cannot load the default codegen backend twice" ); - let target = session::config::host_triple(); + let target = host_triple(); let sysroot_candidates = sysroot_candidates(); let sysroot = iter::once(sysroot) diff --git a/compiler/rustc_lint/src/context/diagnostics/check_cfg.rs b/compiler/rustc_lint/src/context/diagnostics/check_cfg.rs index e9a6276192e52..3c423b4e2aa6d 100644 --- a/compiler/rustc_lint/src/context/diagnostics/check_cfg.rs +++ b/compiler/rustc_lint/src/context/diagnostics/check_cfg.rs @@ -164,9 +164,9 @@ pub(super) fn unexpected_cfg_name( if is_from_cargo { if !is_feature_cfg { - diag.help(format!("consider using a Cargo feature instead or adding `println!(\"cargo:rustc-check-cfg={inst}\");` to the top of a `build.rs`")); + diag.help(format!("consider using a Cargo feature instead or adding `println!(\"cargo::rustc-check-cfg={inst}\");` to the top of the `build.rs`")); } - diag.note("see for more information about checking conditional configuration"); + diag.note("see for more information about checking conditional configuration"); } else { diag.help(format!("to expect this configuration use `--check-cfg={inst}`")); diag.note("see for more information about checking conditional configuration"); @@ -266,9 +266,9 @@ pub(super) fn unexpected_cfg_value( diag.help("consider defining some features in `Cargo.toml`"); } } else if !is_cfg_a_well_know_name { - diag.help(format!("consider using a Cargo feature instead or adding `println!(\"cargo:rustc-check-cfg={inst}\");` to the top of a `build.rs`")); + diag.help(format!("consider using a Cargo feature instead or adding `println!(\"cargo::rustc-check-cfg={inst}\");` to the top of the `build.rs`")); } - diag.note("see for more information about checking conditional configuration"); + diag.note("see for more information about checking conditional configuration"); } else { if !is_cfg_a_well_know_name { diag.help(format!("to expect this configuration use `--check-cfg={inst}`")); diff --git a/compiler/rustc_lint/src/pass_by_value.rs b/compiler/rustc_lint/src/pass_by_value.rs index 1f0a8a0b56783..c1f5cd45dc824 100644 --- a/compiler/rustc_lint/src/pass_by_value.rs +++ b/compiler/rustc_lint/src/pass_by_value.rs @@ -74,9 +74,12 @@ fn gen_args(cx: &LateContext<'_>, segment: &PathSegment<'_>) -> String { GenericArg::Type(ty) => { cx.tcx.sess.source_map().span_to_snippet(ty.span).unwrap_or_else(|_| "_".into()) } - GenericArg::Const(c) => { - cx.tcx.sess.source_map().span_to_snippet(c.span).unwrap_or_else(|_| "_".into()) - } + GenericArg::Const(c) => cx + .tcx + .sess + .source_map() + .span_to_snippet(c.value.span) + .unwrap_or_else(|_| "_".into()), GenericArg::Infer(_) => String::from("_"), }) .collect::>(); diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 13b6054586cd5..f9f766f832af7 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1101,6 +1101,32 @@ fn get_nullable_type<'tcx>( }) } +/// A type is niche-optimization candidate iff: +/// - Is a zero-sized type with alignment 1 (a “1-ZSTâ€). +/// - Has no fields. +/// - Does not have the `#[non_exhaustive]` attribute. +fn is_niche_optimization_candidate<'tcx>( + tcx: TyCtxt<'tcx>, + param_env: ty::ParamEnv<'tcx>, + ty: Ty<'tcx>, +) -> bool { + if tcx.layout_of(param_env.and(ty)).is_ok_and(|layout| !layout.is_1zst()) { + return false; + } + + match ty.kind() { + ty::Adt(ty_def, _) => { + let non_exhaustive = ty_def.is_variant_list_non_exhaustive(); + let empty = (ty_def.is_struct() && ty_def.all_fields().next().is_none()) + || (ty_def.is_enum() && ty_def.variants().is_empty()); + + !non_exhaustive && empty + } + ty::Tuple(tys) => tys.is_empty(), + _ => false, + } +} + /// Check if this enum can be safely exported based on the "nullable pointer optimization". If it /// can, return the type that `ty` can be safely converted to, otherwise return `None`. /// Currently restricted to function pointers, boxes, references, `core::num::NonZero`, @@ -1117,6 +1143,22 @@ pub(crate) fn repr_nullable_ptr<'tcx>( let field_ty = match &ty_def.variants().raw[..] { [var_one, var_two] => match (&var_one.fields.raw[..], &var_two.fields.raw[..]) { ([], [field]) | ([field], []) => field.ty(tcx, args), + ([field1], [field2]) => { + if !tcx.features().result_ffi_guarantees { + return None; + } + + let ty1 = field1.ty(tcx, args); + let ty2 = field2.ty(tcx, args); + + if is_niche_optimization_candidate(tcx, param_env, ty1) { + ty2 + } else if is_niche_optimization_candidate(tcx, param_env, ty2) { + ty1 + } else { + return None; + } + } _ => return None, }, _ => return None, @@ -1202,7 +1244,6 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { args: GenericArgsRef<'tcx>, ) -> FfiResult<'tcx> { use FfiResult::*; - let transparent_with_all_zst_fields = if def.repr().transparent() { if let Some(field) = transparent_newtype_field(self.cx.tcx, variant) { // Transparent newtypes have at most one non-ZST field which needs to be checked.. @@ -1329,27 +1370,29 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { return FfiSafe; } + if def.is_variant_list_non_exhaustive() && !def.did().is_local() { + return FfiUnsafe { + ty, + reason: fluent::lint_improper_ctypes_non_exhaustive, + help: None, + }; + } + // Check for a repr() attribute to specify the size of the // discriminant. if !def.repr().c() && !def.repr().transparent() && def.repr().int.is_none() { - // Special-case types like `Option`. - if repr_nullable_ptr(self.cx.tcx, self.cx.param_env, ty, self.mode) - .is_none() + // Special-case types like `Option` and `Result` + if let Some(ty) = + repr_nullable_ptr(self.cx.tcx, self.cx.param_env, ty, self.mode) { - return FfiUnsafe { - ty, - reason: fluent::lint_improper_ctypes_enum_repr_reason, - help: Some(fluent::lint_improper_ctypes_enum_repr_help), - }; + return self.check_type_for_ffi(cache, ty); } - } - if def.is_variant_list_non_exhaustive() && !def.did().is_local() { return FfiUnsafe { ty, - reason: fluent::lint_improper_ctypes_non_exhaustive, - help: None, + reason: fluent::lint_improper_ctypes_enum_repr_reason, + help: Some(fluent::lint_improper_ctypes_enum_repr_help), }; } diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index c7996c27c2f09..eea3ca44c48b2 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -844,7 +844,6 @@ declare_lint! { /// ### Example /// /// ```rust - /// # #![feature(exclusive_range_pattern)] /// let x = 123u32; /// match x { /// 0..100 => { println!("small"); } diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index c0c773c6285c2..c7aea137b6841 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -885,7 +885,7 @@ impl<'hir> Map<'hir> { Node::ImplItem(impl_item) => impl_item.span, Node::Variant(variant) => variant.span, Node::Field(field) => field.span, - Node::AnonConst(constant) => self.body(constant.body).value.span, + Node::AnonConst(constant) => constant.span, Node::ConstBlock(constant) => self.body(constant.body).value.span, Node::Expr(expr) => expr.span, Node::ExprField(field) => field.span, @@ -912,7 +912,7 @@ impl<'hir> Map<'hir> { Node::ArrayLenInfer(inf) => inf.span, Node::PreciseCapturingNonLifetimeArg(param) => param.ident.span, Node::Synthetic => unreachable!(), - Node::Err(span) => *span, + Node::Err(span) => span, } } diff --git a/compiler/rustc_middle/src/mir/coverage.rs b/compiler/rustc_middle/src/mir/coverage.rs index 9d9ca22247ad6..477303e2434f4 100644 --- a/compiler/rustc_middle/src/mir/coverage.rs +++ b/compiler/rustc_middle/src/mir/coverage.rs @@ -277,7 +277,7 @@ pub struct FunctionCoverageInfo { pub mappings: Vec, /// The depth of the deepest decision is used to know how many /// temp condbitmaps should be allocated for the function. - pub mcdc_max_decision_depth: u16, + pub mcdc_num_condition_bitmaps: usize, } /// Branch information recorded during THIR-to-MIR lowering, and stored in MIR. diff --git a/compiler/rustc_middle/src/mir/interpret/allocation.rs b/compiler/rustc_middle/src/mir/interpret/allocation.rs index 9cc5c6a2ee940..791e87735f40b 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation.rs @@ -29,9 +29,7 @@ use provenance_map::*; pub use init_mask::{InitChunk, InitChunkIter}; /// Functionality required for the bytes of an `Allocation`. -pub trait AllocBytes: - Clone + fmt::Debug + Eq + PartialEq + Hash + Deref + DerefMut -{ +pub trait AllocBytes: Clone + fmt::Debug + Deref + DerefMut { /// Create an `AllocBytes` from a slice of `u8`. fn from_bytes<'a>(slice: impl Into>, _align: Align) -> Self; @@ -346,10 +344,10 @@ impl Allocation { } } -impl Allocation { +impl Allocation { /// Adjust allocation from the ones in `tcx` to a custom Machine instance - /// with a different `Provenance` and `Extra` type. - pub fn adjust_from_tcx( + /// with a different `Provenance`, `Extra` and `Byte` type. + pub fn adjust_from_tcx( self, cx: &impl HasDataLayout, extra: Extra, @@ -371,7 +369,7 @@ impl Allocation { } // Create allocation. Ok(Allocation { - bytes, + bytes: AllocBytes::from_bytes(Cow::Owned(Vec::from(bytes)), self.align), provenance: ProvenanceMap::from_presorted_ptrs(new_provenance), init_mask: self.init_mask, align: self.align, diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index 6d4585cfbc66a..daab6c855819b 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -1,7 +1,9 @@ use crate::dep_graph::{DepNode, WorkProduct, WorkProductId}; use crate::ty::{GenericArgs, Instance, InstanceDef, SymbolName, TyCtxt}; use rustc_attr::InlineAttr; -use rustc_data_structures::base_n; +use rustc_data_structures::base_n::BaseNString; +use rustc_data_structures::base_n::ToBaseN; +use rustc_data_structures::base_n::CASE_INSENSITIVE; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxIndexMap; @@ -337,14 +339,11 @@ impl<'tcx> CodegenUnit<'tcx> { self.is_code_coverage_dead_code_cgu = true; } - pub fn mangle_name(human_readable_name: &str) -> String { - // We generate a 80 bit hash from the name. This should be enough to - // avoid collisions and is still reasonably short for filenames. + pub fn mangle_name(human_readable_name: &str) -> BaseNString { let mut hasher = StableHasher::new(); human_readable_name.hash(&mut hasher); let hash: Hash128 = hasher.finish(); - let hash = hash.as_u128() & ((1u128 << 80) - 1); - base_n::encode(hash, base_n::CASE_INSENSITIVE) + hash.as_u128().to_base_fixed_len(CASE_INSENSITIVE) } pub fn compute_size_estimate(&mut self) { diff --git a/compiler/rustc_middle/src/traits/solve.rs b/compiler/rustc_middle/src/traits/solve.rs index 4c34bf88c7f96..3ad6b68d1299b 100644 --- a/compiler/rustc_middle/src/traits/solve.rs +++ b/compiler/rustc_middle/src/traits/solve.rs @@ -273,6 +273,8 @@ pub enum GoalSource { /// they are from an impl where-clause. This is necessary due to /// backwards compatability, cc trait-system-refactor-initiatitive#70. ImplWhereBound, + /// Instantiating a higher-ranked goal and re-proving it. + InstantiateHigherRanked, } /// Possible ways the given goal can be proven. diff --git a/compiler/rustc_middle/src/traits/solve/inspect/format.rs b/compiler/rustc_middle/src/traits/solve/inspect/format.rs index 2d73be387fdcd..11aa0e10931cb 100644 --- a/compiler/rustc_middle/src/traits/solve/inspect/format.rs +++ b/compiler/rustc_middle/src/traits/solve/inspect/format.rs @@ -127,6 +127,7 @@ impl<'a, 'b> ProofTreeFormatter<'a, 'b> { let source = match source { GoalSource::Misc => "misc", GoalSource::ImplWhereBound => "impl where-bound", + GoalSource::InstantiateHigherRanked => "higher-ranked goal", }; writeln!(this.f, "ADDED GOAL ({source}): {goal:?}")? } diff --git a/compiler/rustc_middle/src/ty/fast_reject.rs b/compiler/rustc_middle/src/ty/fast_reject.rs index 15f048ab598c9..8d7489f5f7e60 100644 --- a/compiler/rustc_middle/src/ty/fast_reject.rs +++ b/compiler/rustc_middle/src/ty/fast_reject.rs @@ -330,20 +330,19 @@ impl DeepRejectCtxt { } pub fn consts_may_unify(self, obligation_ct: ty::Const<'_>, impl_ct: ty::Const<'_>) -> bool { - match impl_ct.kind() { + let impl_val = match impl_ct.kind() { ty::ConstKind::Expr(_) | ty::ConstKind::Param(_) | ty::ConstKind::Unevaluated(_) | ty::ConstKind::Error(_) => { return true; } - ty::ConstKind::Value(_) => {} + ty::ConstKind::Value(impl_val) => impl_val, ty::ConstKind::Infer(_) | ty::ConstKind::Bound(..) | ty::ConstKind::Placeholder(_) => { bug!("unexpected impl arg: {:?}", impl_ct) } - } + }; - let k = impl_ct.kind(); match obligation_ct.kind() { ty::ConstKind::Param(_) => match self.treat_obligation_params { TreatParams::ForLookup => false, @@ -358,10 +357,7 @@ impl DeepRejectCtxt { ty::ConstKind::Expr(_) | ty::ConstKind::Unevaluated(_) | ty::ConstKind::Error(_) => { true } - ty::ConstKind::Value(obl) => match k { - ty::ConstKind::Value(imp) => obl == imp, - _ => true, - }, + ty::ConstKind::Value(obl_val) => obl_val == impl_val, ty::ConstKind::Infer(_) => true, diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index d6e6cc957b4be..794e7ebb7b431 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -566,7 +566,8 @@ fn construct_const<'a, 'tcx>( span, .. }) => (*span, ty.span), - Node::AnonConst(_) | Node::ConstBlock(_) => { + Node::AnonConst(ct) => (ct.span, ct.span), + Node::ConstBlock(_) => { let span = tcx.def_span(def); (span, span) } diff --git a/compiler/rustc_mir_transform/src/copy_prop.rs b/compiler/rustc_mir_transform/src/copy_prop.rs index 0119b95cced97..c1f9313a377de 100644 --- a/compiler/rustc_mir_transform/src/copy_prop.rs +++ b/compiler/rustc_mir_transform/src/copy_prop.rs @@ -3,7 +3,6 @@ use rustc_index::IndexSlice; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; -use rustc_mir_dataflow::impls::borrowed_locals; use crate::ssa::SsaLocals; @@ -32,8 +31,8 @@ impl<'tcx> MirPass<'tcx> for CopyProp { } fn propagate_ssa<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { - let borrowed_locals = borrowed_locals(body); - let ssa = SsaLocals::new(body); + let param_env = tcx.param_env_reveal_all_normalized(body.source.def_id()); + let ssa = SsaLocals::new(tcx, body, param_env); let fully_moved = fully_moved_locals(&ssa, body); debug!(?fully_moved); @@ -51,7 +50,7 @@ fn propagate_ssa<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { tcx, copy_classes: ssa.copy_classes(), fully_moved, - borrowed_locals, + borrowed_locals: ssa.borrowed_locals(), storage_to_remove, } .visit_body_preserves_cfg(body); @@ -101,7 +100,7 @@ struct Replacer<'a, 'tcx> { tcx: TyCtxt<'tcx>, fully_moved: BitSet, storage_to_remove: BitSet, - borrowed_locals: BitSet, + borrowed_locals: &'a BitSet, copy_classes: &'a IndexSlice, } @@ -112,6 +111,12 @@ impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> { fn visit_local(&mut self, local: &mut Local, ctxt: PlaceContext, _: Location) { let new_local = self.copy_classes[*local]; + // We must not unify two locals that are borrowed. But this is fine if one is borrowed and + // the other is not. We chose to check the original local, and not the target. That way, if + // the original local is borrowed and the target is not, we do not pessimize the whole class. + if self.borrowed_locals.contains(*local) { + return; + } match ctxt { // Do not modify the local in storage statements. PlaceContext::NonUse(NonUseContext::StorageLive | NonUseContext::StorageDead) => {} @@ -122,32 +127,14 @@ impl<'tcx> MutVisitor<'tcx> for Replacer<'_, 'tcx> { } } - fn visit_place(&mut self, place: &mut Place<'tcx>, ctxt: PlaceContext, loc: Location) { + fn visit_place(&mut self, place: &mut Place<'tcx>, _: PlaceContext, loc: Location) { if let Some(new_projection) = self.process_projection(place.projection, loc) { place.projection = self.tcx().mk_place_elems(&new_projection); } - let observes_address = match ctxt { - PlaceContext::NonMutatingUse( - NonMutatingUseContext::SharedBorrow - | NonMutatingUseContext::FakeBorrow - | NonMutatingUseContext::AddressOf, - ) => true, - // For debuginfo, merging locals is ok. - PlaceContext::NonUse(NonUseContext::VarDebugInfo) => { - self.borrowed_locals.contains(place.local) - } - _ => false, - }; - if observes_address && !place.is_indirect() { - // We observe the address of `place.local`. Do not replace it. - } else { - self.visit_local( - &mut place.local, - PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy), - loc, - ) - } + // Any non-mutating use context is ok. + let ctxt = PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy); + self.visit_local(&mut place.local, ctxt, loc) } fn visit_operand(&mut self, operand: &mut Operand<'tcx>, loc: Location) { diff --git a/compiler/rustc_mir_transform/src/coverage/mappings.rs b/compiler/rustc_mir_transform/src/coverage/mappings.rs index d364658efb6d6..ddbe1333c4b08 100644 --- a/compiler/rustc_mir_transform/src/coverage/mappings.rs +++ b/compiler/rustc_mir_transform/src/coverage/mappings.rs @@ -2,9 +2,8 @@ use std::collections::BTreeSet; use rustc_data_structures::graph::DirectedGraph; use rustc_index::bit_set::BitSet; -use rustc_middle::mir::coverage::{ - BlockMarkerId, BranchSpan, ConditionInfo, CoverageKind, MCDCBranchSpan, MCDCDecisionSpan, -}; +use rustc_index::IndexVec; +use rustc_middle::mir::coverage::{BlockMarkerId, BranchSpan, ConditionInfo, CoverageKind}; use rustc_middle::mir::{self, BasicBlock, StatementKind}; use rustc_span::Span; @@ -13,55 +12,53 @@ use crate::coverage::spans::{ extract_refined_covspans, unexpand_into_body_span_with_visible_macro, }; use crate::coverage::ExtractedHirInfo; -use rustc_index::IndexVec; - -#[derive(Clone, Debug)] -pub(super) enum BcbMappingKind { - /// Associates an ordinary executable code span with its corresponding BCB. - Code(BasicCoverageBlock), - - // Ordinary branch mappings are stored separately, so they don't have a - // variant in this enum. - // - /// Associates a mcdc branch span with condition info besides fields for normal branch. - MCDCBranch { - true_bcb: BasicCoverageBlock, - false_bcb: BasicCoverageBlock, - /// If `None`, this actually represents a normal branch mapping inserted - /// for code that was too complex for MC/DC. - condition_info: Option, - decision_depth: u16, - }, - /// Associates a mcdc decision with its join BCB. - MCDCDecision { - end_bcbs: BTreeSet, - bitmap_idx: u32, - conditions_num: u16, - decision_depth: u16, - }, -} +/// Associates an ordinary executable code span with its corresponding BCB. #[derive(Debug)] -pub(super) struct BcbMapping { - pub(super) kind: BcbMappingKind, +pub(super) struct CodeMapping { pub(super) span: Span, + pub(super) bcb: BasicCoverageBlock, } -/// This is separate from [`BcbMappingKind`] to help prepare for larger changes +/// This is separate from [`MCDCBranch`] to help prepare for larger changes /// that will be needed for improved branch coverage in the future. /// (See .) #[derive(Debug)] -pub(super) struct BcbBranchPair { +pub(super) struct BranchPair { pub(super) span: Span, pub(super) true_bcb: BasicCoverageBlock, pub(super) false_bcb: BasicCoverageBlock, } +/// Associates an MC/DC branch span with condition info besides fields for normal branch. +#[derive(Debug)] +pub(super) struct MCDCBranch { + pub(super) span: Span, + pub(super) true_bcb: BasicCoverageBlock, + pub(super) false_bcb: BasicCoverageBlock, + /// If `None`, this actually represents a normal branch mapping inserted + /// for code that was too complex for MC/DC. + pub(super) condition_info: Option, + pub(super) decision_depth: u16, +} + +/// Associates an MC/DC decision with its join BCBs. +#[derive(Debug)] +pub(super) struct MCDCDecision { + pub(super) span: Span, + pub(super) end_bcbs: BTreeSet, + pub(super) bitmap_idx: u32, + pub(super) conditions_num: u16, + pub(super) decision_depth: u16, +} + pub(super) struct CoverageSpans { bcb_has_mappings: BitSet, - pub(super) mappings: Vec, - pub(super) branch_pairs: Vec, + pub(super) code_mappings: Vec, + pub(super) branch_pairs: Vec, test_vector_bitmap_bytes: u32, + pub(super) mcdc_branches: Vec, + pub(super) mcdc_decisions: Vec, } impl CoverageSpans { @@ -83,8 +80,10 @@ pub(super) fn generate_coverage_spans( hir_info: &ExtractedHirInfo, basic_coverage_blocks: &CoverageGraph, ) -> Option { - let mut mappings = vec![]; + let mut code_mappings = vec![]; let mut branch_pairs = vec![]; + let mut mcdc_branches = vec![]; + let mut mcdc_decisions = vec![]; if hir_info.is_async_fn { // An async function desugars into a function that returns a future, @@ -92,17 +91,27 @@ pub(super) fn generate_coverage_spans( // outer function will be unhelpful, so just keep the signature span // and ignore all of the spans in the MIR body. if let Some(span) = hir_info.fn_sig_span_extended { - mappings.push(BcbMapping { kind: BcbMappingKind::Code(START_BCB), span }); + code_mappings.push(CodeMapping { span, bcb: START_BCB }); } } else { - extract_refined_covspans(mir_body, hir_info, basic_coverage_blocks, &mut mappings); + extract_refined_covspans(mir_body, hir_info, basic_coverage_blocks, &mut code_mappings); branch_pairs.extend(extract_branch_pairs(mir_body, hir_info, basic_coverage_blocks)); - mappings.extend(extract_mcdc_mappings(mir_body, hir_info.body_span, basic_coverage_blocks)); + extract_mcdc_mappings( + mir_body, + hir_info.body_span, + basic_coverage_blocks, + &mut mcdc_branches, + &mut mcdc_decisions, + ); } - if mappings.is_empty() && branch_pairs.is_empty() { + if code_mappings.is_empty() + && branch_pairs.is_empty() + && mcdc_branches.is_empty() + && mcdc_decisions.is_empty() + { return None; } @@ -111,29 +120,36 @@ pub(super) fn generate_coverage_spans( let mut insert = |bcb| { bcb_has_mappings.insert(bcb); }; - let mut test_vector_bitmap_bytes = 0; - for BcbMapping { kind, span: _ } in &mappings { - match *kind { - BcbMappingKind::Code(bcb) => insert(bcb), - BcbMappingKind::MCDCBranch { true_bcb, false_bcb, .. } => { - insert(true_bcb); - insert(false_bcb); - } - BcbMappingKind::MCDCDecision { bitmap_idx, conditions_num, .. } => { - // `bcb_has_mappings` is used for inject coverage counters - // but they are not needed for decision BCBs. - // While the length of test vector bitmap should be calculated here. - test_vector_bitmap_bytes = test_vector_bitmap_bytes - .max(bitmap_idx + (1_u32 << conditions_num as u32).div_ceil(8)); - } - } + + for &CodeMapping { span: _, bcb } in &code_mappings { + insert(bcb); + } + for &BranchPair { true_bcb, false_bcb, .. } in &branch_pairs { + insert(true_bcb); + insert(false_bcb); } - for &BcbBranchPair { true_bcb, false_bcb, .. } in &branch_pairs { + for &MCDCBranch { true_bcb, false_bcb, .. } in &mcdc_branches { insert(true_bcb); insert(false_bcb); } - Some(CoverageSpans { bcb_has_mappings, mappings, branch_pairs, test_vector_bitmap_bytes }) + // Determine the length of the test vector bitmap. + let test_vector_bitmap_bytes = mcdc_decisions + .iter() + .map(|&MCDCDecision { bitmap_idx, conditions_num, .. }| { + bitmap_idx + (1_u32 << u32::from(conditions_num)).div_ceil(8) + }) + .max() + .unwrap_or(0); + + Some(CoverageSpans { + bcb_has_mappings, + code_mappings, + branch_pairs, + test_vector_bitmap_bytes, + mcdc_branches, + mcdc_decisions, + }) } fn resolve_block_markers( @@ -167,7 +183,7 @@ pub(super) fn extract_branch_pairs( mir_body: &mir::Body<'_>, hir_info: &ExtractedHirInfo, basic_coverage_blocks: &CoverageGraph, -) -> Vec { +) -> Vec { let Some(branch_info) = mir_body.coverage_branch_info.as_deref() else { return vec![] }; let block_markers = resolve_block_markers(branch_info, mir_body); @@ -190,7 +206,7 @@ pub(super) fn extract_branch_pairs( let true_bcb = bcb_from_marker(true_marker)?; let false_bcb = bcb_from_marker(false_marker)?; - Some(BcbBranchPair { span, true_bcb, false_bcb }) + Some(BranchPair { span, true_bcb, false_bcb }) }) .collect::>() } @@ -199,10 +215,10 @@ pub(super) fn extract_mcdc_mappings( mir_body: &mir::Body<'_>, body_span: Span, basic_coverage_blocks: &CoverageGraph, -) -> Vec { - let Some(branch_info) = mir_body.coverage_branch_info.as_deref() else { - return vec![]; - }; + mcdc_branches: &mut impl Extend, + mcdc_decisions: &mut impl Extend, +) { + let Some(branch_info) = mir_body.coverage_branch_info.as_deref() else { return }; let block_markers = resolve_block_markers(branch_info, mir_body); @@ -223,53 +239,42 @@ pub(super) fn extract_mcdc_mappings( Some((span, true_bcb, false_bcb)) }; - let mcdc_branch_filter_map = |&MCDCBranchSpan { - span: raw_span, - true_marker, - false_marker, - condition_info, - decision_depth, - }| { - check_branch_bcb(raw_span, true_marker, false_marker).map(|(span, true_bcb, false_bcb)| { - BcbMapping { - kind: BcbMappingKind::MCDCBranch { - true_bcb, - false_bcb, - condition_info, - decision_depth, - }, - span, - } - }) - }; + mcdc_branches.extend(branch_info.mcdc_branch_spans.iter().filter_map( + |&mir::coverage::MCDCBranchSpan { + span: raw_span, + condition_info, + true_marker, + false_marker, + decision_depth, + }| { + let (span, true_bcb, false_bcb) = + check_branch_bcb(raw_span, true_marker, false_marker)?; + Some(MCDCBranch { span, true_bcb, false_bcb, condition_info, decision_depth }) + }, + )); let mut next_bitmap_idx = 0; - let decision_filter_map = |decision: &MCDCDecisionSpan| { - let (span, _) = unexpand_into_body_span_with_visible_macro(decision.span, body_span)?; + mcdc_decisions.extend(branch_info.mcdc_decision_spans.iter().filter_map( + |decision: &mir::coverage::MCDCDecisionSpan| { + let (span, _) = unexpand_into_body_span_with_visible_macro(decision.span, body_span)?; - let end_bcbs = decision - .end_markers - .iter() - .map(|&marker| bcb_from_marker(marker)) - .collect::>()?; + let end_bcbs = decision + .end_markers + .iter() + .map(|&marker| bcb_from_marker(marker)) + .collect::>()?; - let bitmap_idx = next_bitmap_idx; - next_bitmap_idx += (1_u32 << decision.conditions_num).div_ceil(8); + let bitmap_idx = next_bitmap_idx; + next_bitmap_idx += (1_u32 << decision.conditions_num).div_ceil(8); - Some(BcbMapping { - kind: BcbMappingKind::MCDCDecision { + Some(MCDCDecision { + span, end_bcbs, bitmap_idx, conditions_num: decision.conditions_num as u16, decision_depth: decision.decision_depth, - }, - span, - }) - }; - - std::iter::empty() - .chain(branch_info.mcdc_branch_spans.iter().filter_map(mcdc_branch_filter_map)) - .chain(branch_info.mcdc_decision_spans.iter().filter_map(decision_filter_map)) - .collect::>() + }) + }, + )); } diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index 9edde6662469e..1e2599e78e9e1 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -9,7 +9,7 @@ mod tests; use self::counters::{CounterIncrementSite, CoverageCounters}; use self::graph::{BasicCoverageBlock, CoverageGraph}; -use self::mappings::{BcbBranchPair, BcbMapping, BcbMappingKind, CoverageSpans}; +use self::mappings::CoverageSpans; use crate::MirPass; @@ -102,15 +102,12 @@ fn instrument_function_for_coverage<'tcx>(tcx: TyCtxt<'tcx>, mir_body: &mut mir: inject_mcdc_statements(mir_body, &basic_coverage_blocks, &coverage_spans); - let mcdc_max_decision_depth = coverage_spans - .mappings + let mcdc_num_condition_bitmaps = coverage_spans + .mcdc_decisions .iter() - .filter_map(|bcb_mapping| match bcb_mapping.kind { - BcbMappingKind::MCDCDecision { decision_depth, .. } => Some(decision_depth), - _ => None, - }) + .map(|&mappings::MCDCDecision { decision_depth, .. }| decision_depth) .max() - .unwrap_or(0); + .map_or(0, |max| usize::from(max) + 1); mir_body.function_coverage_info = Some(Box::new(FunctionCoverageInfo { function_source_hash: hir_info.function_source_hash, @@ -118,7 +115,7 @@ fn instrument_function_for_coverage<'tcx>(tcx: TyCtxt<'tcx>, mir_body: &mut mir: mcdc_bitmap_bytes: coverage_spans.test_vector_bitmap_bytes(), expressions: coverage_counters.into_expressions(), mappings, - mcdc_max_decision_depth, + mcdc_num_condition_bitmaps, })); } @@ -149,44 +146,45 @@ fn create_mappings<'tcx>( .expect("all BCBs with spans were given counters") .as_term() }; + let region_for_span = |span: Span| make_code_region(source_map, file_name, span, body_span); let mut mappings = Vec::new(); - mappings.extend(coverage_spans.mappings.iter().filter_map( - |BcbMapping { kind: bcb_mapping_kind, span }| { - let kind = match *bcb_mapping_kind { - BcbMappingKind::Code(bcb) => MappingKind::Code(term_for_bcb(bcb)), - BcbMappingKind::MCDCBranch { - true_bcb, false_bcb, condition_info: None, .. - } => MappingKind::Branch { - true_term: term_for_bcb(true_bcb), - false_term: term_for_bcb(false_bcb), - }, - BcbMappingKind::MCDCBranch { - true_bcb, - false_bcb, - condition_info: Some(mcdc_params), - .. - } => MappingKind::MCDCBranch { - true_term: term_for_bcb(true_bcb), - false_term: term_for_bcb(false_bcb), - mcdc_params, - }, - BcbMappingKind::MCDCDecision { bitmap_idx, conditions_num, .. } => { - MappingKind::MCDCDecision(DecisionInfo { bitmap_idx, conditions_num }) - } - }; - let code_region = make_code_region(source_map, file_name, *span, body_span)?; + mappings.extend(coverage_spans.code_mappings.iter().filter_map( + |&mappings::CodeMapping { span, bcb }| { + let code_region = region_for_span(span)?; + let kind = MappingKind::Code(term_for_bcb(bcb)); Some(Mapping { kind, code_region }) }, )); mappings.extend(coverage_spans.branch_pairs.iter().filter_map( - |&BcbBranchPair { span, true_bcb, false_bcb }| { + |&mappings::BranchPair { span, true_bcb, false_bcb }| { let true_term = term_for_bcb(true_bcb); let false_term = term_for_bcb(false_bcb); let kind = MappingKind::Branch { true_term, false_term }; - let code_region = make_code_region(source_map, file_name, span, body_span)?; + let code_region = region_for_span(span)?; + Some(Mapping { kind, code_region }) + }, + )); + + mappings.extend(coverage_spans.mcdc_branches.iter().filter_map( + |&mappings::MCDCBranch { span, true_bcb, false_bcb, condition_info, decision_depth: _ }| { + let code_region = region_for_span(span)?; + let true_term = term_for_bcb(true_bcb); + let false_term = term_for_bcb(false_bcb); + let kind = match condition_info { + Some(mcdc_params) => MappingKind::MCDCBranch { true_term, false_term, mcdc_params }, + None => MappingKind::Branch { true_term, false_term }, + }; + Some(Mapping { kind, code_region }) + }, + )); + + mappings.extend(coverage_spans.mcdc_decisions.iter().filter_map( + |&mappings::MCDCDecision { span, bitmap_idx, conditions_num, .. }| { + let code_region = region_for_span(span)?; + let kind = MappingKind::MCDCDecision(DecisionInfo { bitmap_idx, conditions_num }); Some(Mapping { kind, code_region }) }, )); @@ -258,13 +256,13 @@ fn inject_mcdc_statements<'tcx>( } // Inject test vector update first because `inject_statement` always insert new statement at head. - for (end_bcbs, bitmap_idx, decision_depth) in - coverage_spans.mappings.iter().filter_map(|mapping| match &mapping.kind { - BcbMappingKind::MCDCDecision { end_bcbs, bitmap_idx, decision_depth, .. } => { - Some((end_bcbs, *bitmap_idx, *decision_depth)) - } - _ => None, - }) + for &mappings::MCDCDecision { + span: _, + ref end_bcbs, + bitmap_idx, + conditions_num: _, + decision_depth, + } in &coverage_spans.mcdc_decisions { for end in end_bcbs { let end_bb = basic_coverage_blocks[*end].leader_bb(); @@ -276,24 +274,22 @@ fn inject_mcdc_statements<'tcx>( } } - for (true_bcb, false_bcb, condition_id, decision_depth) in - coverage_spans.mappings.iter().filter_map(|mapping| match mapping.kind { - BcbMappingKind::MCDCBranch { true_bcb, false_bcb, condition_info, decision_depth } => { - Some((true_bcb, false_bcb, condition_info?.condition_id, decision_depth)) - } - _ => None, - }) + for &mappings::MCDCBranch { span: _, true_bcb, false_bcb, condition_info, decision_depth } in + &coverage_spans.mcdc_branches { + let Some(condition_info) = condition_info else { continue }; + let id = condition_info.condition_id; + let true_bb = basic_coverage_blocks[true_bcb].leader_bb(); inject_statement( mir_body, - CoverageKind::CondBitmapUpdate { id: condition_id, value: true, decision_depth }, + CoverageKind::CondBitmapUpdate { id, value: true, decision_depth }, true_bb, ); let false_bb = basic_coverage_blocks[false_bcb].leader_bb(); inject_statement( mir_body, - CoverageKind::CondBitmapUpdate { id: condition_id, value: false, decision_depth }, + CoverageKind::CondBitmapUpdate { id, value: false, decision_depth }, false_bb, ); } diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs index d6432e2e9d41c..a0570c45f9630 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -2,7 +2,7 @@ use rustc_middle::mir; use rustc_span::{BytePos, Span}; use crate::coverage::graph::{BasicCoverageBlock, CoverageGraph}; -use crate::coverage::mappings::{BcbMapping, BcbMappingKind}; +use crate::coverage::mappings; use crate::coverage::spans::from_mir::SpanFromMir; use crate::coverage::ExtractedHirInfo; @@ -17,14 +17,14 @@ pub(super) fn extract_refined_covspans( mir_body: &mir::Body<'_>, hir_info: &ExtractedHirInfo, basic_coverage_blocks: &CoverageGraph, - mappings: &mut impl Extend, + code_mappings: &mut impl Extend, ) { let sorted_spans = from_mir::mir_to_initial_sorted_coverage_spans(mir_body, hir_info, basic_coverage_blocks); let coverage_spans = SpansRefiner::refine_sorted_spans(sorted_spans); - mappings.extend(coverage_spans.into_iter().map(|RefinedCovspan { bcb, span, .. }| { + code_mappings.extend(coverage_spans.into_iter().map(|RefinedCovspan { bcb, span, .. }| { // Each span produced by the generator represents an ordinary code region. - BcbMapping { kind: BcbMappingKind::Code(bcb), span } + mappings::CodeMapping { span, bcb } })); } diff --git a/compiler/rustc_mir_transform/src/gvn.rs b/compiler/rustc_mir_transform/src/gvn.rs index 24832086b167b..4dd595ce1e1ce 100644 --- a/compiler/rustc_mir_transform/src/gvn.rs +++ b/compiler/rustc_mir_transform/src/gvn.rs @@ -121,7 +121,7 @@ impl<'tcx> MirPass<'tcx> for GVN { fn propagate_ssa<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let param_env = tcx.param_env_reveal_all_normalized(body.source.def_id()); - let ssa = SsaLocals::new(body); + let ssa = SsaLocals::new(tcx, body, param_env); // Clone dominators as we need them while mutating the body. let dominators = body.basic_blocks.dominators().clone(); @@ -724,6 +724,14 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { // Invariant: `value` holds the value up-to the `index`th projection excluded. let mut value = self.locals[place.local]?; for (index, proj) in place.projection.iter().enumerate() { + if let Value::Projection(pointer, ProjectionElem::Deref) = *self.get(value) + && let Value::Address { place: mut pointee, kind, .. } = *self.get(pointer) + && let AddressKind::Ref(BorrowKind::Shared) = kind + && let Some(v) = self.simplify_place_value(&mut pointee, location) + { + value = v; + place_ref = pointee.project_deeper(&place.projection[index..], self.tcx).as_ref(); + } if let Some(local) = self.try_as_local(value, location) { // Both `local` and `Place { local: place.local, projection: projection[..index] }` // hold the same value. Therefore, following place holds the value in the original @@ -735,6 +743,14 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { value = self.project(base, value, proj)?; } + if let Value::Projection(pointer, ProjectionElem::Deref) = *self.get(value) + && let Value::Address { place: mut pointee, kind, .. } = *self.get(pointer) + && let AddressKind::Ref(BorrowKind::Shared) = kind + && let Some(v) = self.simplify_place_value(&mut pointee, location) + { + value = v; + place_ref = pointee.project_deeper(&[], self.tcx).as_ref(); + } if let Some(new_local) = self.try_as_local(value, location) { place_ref = PlaceRef { local: new_local, projection: &[] }; } diff --git a/compiler/rustc_mir_transform/src/normalize_array_len.rs b/compiler/rustc_mir_transform/src/normalize_array_len.rs index 128634bd7f254..c26a54616331c 100644 --- a/compiler/rustc_mir_transform/src/normalize_array_len.rs +++ b/compiler/rustc_mir_transform/src/normalize_array_len.rs @@ -22,7 +22,8 @@ impl<'tcx> MirPass<'tcx> for NormalizeArrayLen { } fn normalize_array_len_calls<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { - let ssa = SsaLocals::new(body); + let param_env = tcx.param_env_reveal_all_normalized(body.source.def_id()); + let ssa = SsaLocals::new(tcx, body, param_env); let slice_lengths = compute_slice_length(tcx, &ssa, body); debug!(?slice_lengths); diff --git a/compiler/rustc_mir_transform/src/ref_prop.rs b/compiler/rustc_mir_transform/src/ref_prop.rs index d5642be551375..044ae32c1d40f 100644 --- a/compiler/rustc_mir_transform/src/ref_prop.rs +++ b/compiler/rustc_mir_transform/src/ref_prop.rs @@ -82,7 +82,8 @@ impl<'tcx> MirPass<'tcx> for ReferencePropagation { } fn propagate_ssa<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool { - let ssa = SsaLocals::new(body); + let param_env = tcx.param_env_reveal_all_normalized(body.source.def_id()); + let ssa = SsaLocals::new(tcx, body, param_env); let mut replacer = compute_replacement(tcx, body, &ssa); debug!(?replacer.targets); diff --git a/compiler/rustc_mir_transform/src/ssa.rs b/compiler/rustc_mir_transform/src/ssa.rs index fddc62e6652fa..55fed7d9da28d 100644 --- a/compiler/rustc_mir_transform/src/ssa.rs +++ b/compiler/rustc_mir_transform/src/ssa.rs @@ -2,8 +2,9 @@ //! 1/ They are only assigned-to once, either as a function parameter, or in an assign statement; //! 2/ This single assignment dominates all uses; //! -//! As a consequence of rule 2, we consider that borrowed locals are not SSA, even if they are -//! `Freeze`, as we do not track that the assignment dominates all uses of the borrow. +//! As we do not track indirect assignments, a local that has its address taken (either by +//! AddressOf or by borrowing) is considered non-SSA. However, it is UB to modify through an +//! immutable borrow of a `Freeze` local. Those can still be considered to be SSA. use rustc_data_structures::graph::dominators::Dominators; use rustc_index::bit_set::BitSet; @@ -11,6 +12,7 @@ use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::middle::resolve_bound_vars::Set1; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; +use rustc_middle::ty::{ParamEnv, TyCtxt}; pub struct SsaLocals { /// Assignments to each local. This defines whether the local is SSA. @@ -24,6 +26,8 @@ pub struct SsaLocals { /// Number of "direct" uses of each local, ie. uses that are not dereferences. /// We ignore non-uses (Storage statements, debuginfo). direct_uses: IndexVec, + /// Set of SSA locals that are immutably borrowed. + borrowed_locals: BitSet, } pub enum AssignedValue<'a, 'tcx> { @@ -33,15 +37,22 @@ pub enum AssignedValue<'a, 'tcx> { } impl SsaLocals { - pub fn new<'tcx>(body: &Body<'tcx>) -> SsaLocals { + pub fn new<'tcx>(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, param_env: ParamEnv<'tcx>) -> SsaLocals { let assignment_order = Vec::with_capacity(body.local_decls.len()); let assignments = IndexVec::from_elem(Set1::Empty, &body.local_decls); let dominators = body.basic_blocks.dominators(); let direct_uses = IndexVec::from_elem(0, &body.local_decls); - let mut visitor = - SsaVisitor { body, assignments, assignment_order, dominators, direct_uses }; + let borrowed_locals = BitSet::new_empty(body.local_decls.len()); + let mut visitor = SsaVisitor { + body, + assignments, + assignment_order, + dominators, + direct_uses, + borrowed_locals, + }; for local in body.args_iter() { visitor.assignments[local] = Set1::One(DefLocation::Argument); @@ -58,6 +69,16 @@ impl SsaLocals { visitor.visit_var_debug_info(var_debug_info); } + // The immutability of shared borrows only works on `Freeze` locals. If the visitor found + // borrows, we need to check the types. For raw pointers and mutable borrows, the locals + // have already been marked as non-SSA. + debug!(?visitor.borrowed_locals); + for local in visitor.borrowed_locals.iter() { + if !body.local_decls[local].ty.is_freeze(tcx, param_env) { + visitor.assignments[local] = Set1::Many; + } + } + debug!(?visitor.assignments); debug!(?visitor.direct_uses); @@ -70,6 +91,7 @@ impl SsaLocals { assignments: visitor.assignments, assignment_order: visitor.assignment_order, direct_uses: visitor.direct_uses, + borrowed_locals: visitor.borrowed_locals, // This is filled by `compute_copy_classes`. copy_classes: IndexVec::default(), }; @@ -174,6 +196,11 @@ impl SsaLocals { &self.copy_classes } + /// Set of SSA locals that are immutably borrowed. + pub fn borrowed_locals(&self) -> &BitSet { + &self.borrowed_locals + } + /// Make a property uniform on a copy equivalence class by removing elements. pub fn meet_copy_equivalence(&self, property: &mut BitSet) { // Consolidate to have a local iff all its copies are. @@ -208,6 +235,8 @@ struct SsaVisitor<'tcx, 'a> { assignments: IndexVec>, assignment_order: Vec, direct_uses: IndexVec, + // Track locals that are immutably borrowed, so we can check their type is `Freeze` later. + borrowed_locals: BitSet, } impl SsaVisitor<'_, '_> { @@ -232,16 +261,18 @@ impl<'tcx> Visitor<'tcx> for SsaVisitor<'tcx, '_> { PlaceContext::MutatingUse(MutatingUseContext::Projection) | PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection) => bug!(), // Anything can happen with raw pointers, so remove them. - // We do not verify that all uses of the borrow dominate the assignment to `local`, - // so we have to remove them too. - PlaceContext::NonMutatingUse( - NonMutatingUseContext::SharedBorrow - | NonMutatingUseContext::FakeBorrow - | NonMutatingUseContext::AddressOf, - ) + PlaceContext::NonMutatingUse(NonMutatingUseContext::AddressOf) | PlaceContext::MutatingUse(_) => { self.assignments[local] = Set1::Many; } + // Immutable borrows are ok, but we need to delay a check that the type is `Freeze`. + PlaceContext::NonMutatingUse( + NonMutatingUseContext::SharedBorrow | NonMutatingUseContext::FakeBorrow, + ) => { + self.borrowed_locals.insert(local); + self.check_dominates(local, loc); + self.direct_uses[local] += 1; + } PlaceContext::NonMutatingUse(_) => { self.check_dominates(local, loc); self.direct_uses[local] += 1; diff --git a/compiler/rustc_parse/Cargo.toml b/compiler/rustc_parse/Cargo.toml index f562332316874..b33896154f239 100644 --- a/compiler/rustc_parse/Cargo.toml +++ b/compiler/rustc_parse/Cargo.toml @@ -21,3 +21,7 @@ tracing = "0.1" unicode-normalization = "0.1.11" unicode-width = "0.1.4" # tidy-alphabetical-end + +[dev-dependencies] +termcolor = "1.2" + diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 7486da33b2173..f1476fe02c5f6 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -45,6 +45,20 @@ use crate::errors::{ self, IncorrectVisibilityRestriction, MismatchedClosingDelimiter, NonStringAbiLiteral, }; +#[cfg(test)] +mod tests; + +// Ideally, these tests would be in `rustc_ast`. But they depend on having a +// parser, so they are here. +#[cfg(test)] +mod tokenstream { + mod tests; +} +#[cfg(test)] +mod mut_visit { + mod tests; +} + bitflags::bitflags! { #[derive(Clone, Copy)] struct Restrictions: u8 { diff --git a/compiler/rustc_expand/src/mut_visit/tests.rs b/compiler/rustc_parse/src/parser/mut_visit/tests.rs similarity index 97% rename from compiler/rustc_expand/src/mut_visit/tests.rs rename to compiler/rustc_parse/src/parser/mut_visit/tests.rs index 8974d45b4d8cf..b3cb28af657ee 100644 --- a/compiler/rustc_expand/src/mut_visit/tests.rs +++ b/compiler/rustc_parse/src/parser/mut_visit/tests.rs @@ -1,5 +1,4 @@ -use crate::tests::{matches_codepattern, string_to_crate}; - +use crate::parser::tests::{matches_codepattern, string_to_crate}; use rustc_ast as ast; use rustc_ast::mut_visit::MutVisitor; use rustc_ast_pretty::pprust; diff --git a/compiler/rustc_expand/src/tests.rs b/compiler/rustc_parse/src/parser/tests.rs similarity index 61% rename from compiler/rustc_expand/src/tests.rs rename to compiler/rustc_parse/src/parser/tests.rs index 2b0b58eb1d924..a31e350541ab3 100644 --- a/compiler/rustc_expand/src/tests.rs +++ b/compiler/rustc_parse/src/parser/tests.rs @@ -1,25 +1,30 @@ -use rustc_ast as ast; -use rustc_ast::tokenstream::TokenStream; -use rustc_parse::{new_parser_from_source_str, parser::Parser, source_file_to_stream}; -use rustc_session::parse::ParseSess; -use rustc_span::create_default_session_globals_then; -use rustc_span::source_map::{FilePathMapping, SourceMap}; -use rustc_span::{BytePos, Span}; - +use crate::parser::ForceCollect; +use crate::{new_parser_from_source_str, parser::Parser, source_file_to_stream}; +use ast::token::IdentIsRaw; +use rustc_ast::ptr::P; +use rustc_ast::token::{self, Delimiter, Token}; +use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; +use rustc_ast::visit; +use rustc_ast::{self as ast, PatKind}; +use rustc_ast_pretty::pprust::item_to_string; use rustc_data_structures::sync::Lrc; use rustc_errors::emitter::HumanEmitter; use rustc_errors::{DiagCtxt, MultiSpan, PResult}; -use termcolor::WriteColor; - +use rustc_session::parse::ParseSess; +use rustc_span::create_default_session_globals_then; +use rustc_span::source_map::{FilePathMapping, SourceMap}; +use rustc_span::symbol::{kw, sym, Symbol}; +use rustc_span::{BytePos, FileName, Pos, Span}; use std::io; use std::io::prelude::*; use std::iter::Peekable; use std::path::{Path, PathBuf}; use std::str; use std::sync::{Arc, Mutex}; +use termcolor::WriteColor; -pub(crate) fn psess() -> ParseSess { - ParseSess::new(vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE]) +fn psess() -> ParseSess { + ParseSess::new(vec![crate::DEFAULT_LOCALE_RESOURCE, crate::DEFAULT_LOCALE_RESOURCE]) } /// Map string to parser (via tts). @@ -31,7 +36,7 @@ fn create_test_handler() -> (DiagCtxt, Lrc, Arc>>) { let output = Arc::new(Mutex::new(Vec::new())); let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty())); let fallback_bundle = rustc_errors::fallback_fluent_bundle( - vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE], + vec![crate::DEFAULT_LOCALE_RESOURCE, crate::DEFAULT_LOCALE_RESOURCE], false, ); let emitter = HumanEmitter::new(Box::new(Shared { data: output.clone() }), fallback_bundle) @@ -44,7 +49,7 @@ fn create_test_handler() -> (DiagCtxt, Lrc, Arc>>) { /// Returns the result of parsing the given string via the given callback. /// /// If there are any errors, this will panic. -pub(crate) fn with_error_checking_parse<'a, T, F>(s: String, psess: &'a ParseSess, f: F) -> T +fn with_error_checking_parse<'a, T, F>(s: String, psess: &'a ParseSess, f: F) -> T where F: FnOnce(&mut Parser<'a>) -> PResult<'a, T>, { @@ -56,7 +61,7 @@ where /// Verifies that parsing the given string using the given callback will /// generate an error that contains the given text. -pub(crate) fn with_expected_parse_error(source_str: &str, expected_output: &str, f: F) +fn with_expected_parse_error(source_str: &str, expected_output: &str, f: F) where F: for<'a> FnOnce(&mut Parser<'a>) -> PResult<'a, T>, { @@ -150,8 +155,8 @@ struct SpanLabel { label: &'static str, } -pub(crate) struct Shared { - pub data: Arc>, +struct Shared { + data: Arc>, } impl WriteColor for Shared { @@ -1053,3 +1058,365 @@ error: foo "#, ); } + +/// Parses an item. +/// +/// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err` +/// when a syntax error occurred. +fn parse_item_from_source_str( + name: FileName, + source: String, + psess: &ParseSess, +) -> PResult<'_, Option>> { + new_parser_from_source_str(psess, name, source).parse_item(ForceCollect::No) +} + +// Produces a `rustc_span::span`. +fn sp(a: u32, b: u32) -> Span { + Span::with_root_ctxt(BytePos(a), BytePos(b)) +} + +/// Parses a string, return an expression. +fn string_to_expr(source_str: String) -> P { + with_error_checking_parse(source_str, &psess(), |p| p.parse_expr()) +} + +/// Parses a string, returns an item. +fn string_to_item(source_str: String) -> Option> { + with_error_checking_parse(source_str, &psess(), |p| p.parse_item(ForceCollect::No)) +} + +#[test] +fn bad_path_expr_1() { + // This should trigger error: expected identifier, found keyword `return` + create_default_session_globals_then(|| { + with_expected_parse_error( + "::abc::def::return", + "expected identifier, found keyword `return`", + |p| p.parse_expr(), + ); + }) +} + +// Checks the token-tree-ization of macros. +#[test] +fn string_to_tts_macro() { + create_default_session_globals_then(|| { + let stream = string_to_stream("macro_rules! zip (($a)=>($a))".to_string()); + let tts = &stream.trees().collect::>()[..]; + + match tts { + [ + TokenTree::Token( + Token { kind: token::Ident(name_macro_rules, IdentIsRaw::No), .. }, + _, + ), + TokenTree::Token(Token { kind: token::Not, .. }, _), + TokenTree::Token(Token { kind: token::Ident(name_zip, IdentIsRaw::No), .. }, _), + TokenTree::Delimited(.., macro_delim, macro_tts), + ] if name_macro_rules == &kw::MacroRules && name_zip.as_str() == "zip" => { + let tts = ¯o_tts.trees().collect::>(); + match &tts[..] { + [ + TokenTree::Delimited(.., first_delim, first_tts), + TokenTree::Token(Token { kind: token::FatArrow, .. }, _), + TokenTree::Delimited(.., second_delim, second_tts), + ] if macro_delim == &Delimiter::Parenthesis => { + let tts = &first_tts.trees().collect::>(); + match &tts[..] { + [ + TokenTree::Token(Token { kind: token::Dollar, .. }, _), + TokenTree::Token( + Token { kind: token::Ident(name, IdentIsRaw::No), .. }, + _, + ), + ] if first_delim == &Delimiter::Parenthesis && name.as_str() == "a" => { + } + _ => panic!("value 3: {:?} {:?}", first_delim, first_tts), + } + let tts = &second_tts.trees().collect::>(); + match &tts[..] { + [ + TokenTree::Token(Token { kind: token::Dollar, .. }, _), + TokenTree::Token( + Token { kind: token::Ident(name, IdentIsRaw::No), .. }, + _, + ), + ] if second_delim == &Delimiter::Parenthesis + && name.as_str() == "a" => {} + _ => panic!("value 4: {:?} {:?}", second_delim, second_tts), + } + } + _ => panic!("value 2: {:?} {:?}", macro_delim, macro_tts), + } + } + _ => panic!("value: {:?}", tts), + } + }) +} + +#[test] +fn string_to_tts_1() { + create_default_session_globals_then(|| { + let tts = string_to_stream("fn a(b: i32) { b; }".to_string()); + + let expected = TokenStream::new(vec![ + TokenTree::token_alone(token::Ident(kw::Fn, IdentIsRaw::No), sp(0, 2)), + TokenTree::token_joint_hidden( + token::Ident(Symbol::intern("a"), IdentIsRaw::No), + sp(3, 4), + ), + TokenTree::Delimited( + DelimSpan::from_pair(sp(4, 5), sp(11, 12)), + // `JointHidden` because the `(` is followed immediately by + // `b`, `Alone` because the `)` is followed by whitespace. + DelimSpacing::new(Spacing::JointHidden, Spacing::Alone), + Delimiter::Parenthesis, + TokenStream::new(vec![ + TokenTree::token_joint( + token::Ident(Symbol::intern("b"), IdentIsRaw::No), + sp(5, 6), + ), + TokenTree::token_alone(token::Colon, sp(6, 7)), + // `JointHidden` because the `i32` is immediately followed by the `)`. + TokenTree::token_joint_hidden( + token::Ident(sym::i32, IdentIsRaw::No), + sp(8, 11), + ), + ]) + .into(), + ), + TokenTree::Delimited( + DelimSpan::from_pair(sp(13, 14), sp(18, 19)), + // First `Alone` because the `{` is followed by whitespace, + // second `Alone` because the `}` is followed immediately by + // EOF. + DelimSpacing::new(Spacing::Alone, Spacing::Alone), + Delimiter::Brace, + TokenStream::new(vec![ + TokenTree::token_joint( + token::Ident(Symbol::intern("b"), IdentIsRaw::No), + sp(15, 16), + ), + // `Alone` because the `;` is followed by whitespace. + TokenTree::token_alone(token::Semi, sp(16, 17)), + ]) + .into(), + ), + ]); + + assert_eq!(tts, expected); + }) +} + +#[test] +fn parse_use() { + create_default_session_globals_then(|| { + let use_s = "use foo::bar::baz;"; + let vitem = string_to_item(use_s.to_string()).unwrap(); + let vitem_s = item_to_string(&vitem); + assert_eq!(&vitem_s[..], use_s); + + let use_s = "use foo::bar as baz;"; + let vitem = string_to_item(use_s.to_string()).unwrap(); + let vitem_s = item_to_string(&vitem); + assert_eq!(&vitem_s[..], use_s); + }) +} + +#[test] +fn parse_extern_crate() { + create_default_session_globals_then(|| { + let ex_s = "extern crate foo;"; + let vitem = string_to_item(ex_s.to_string()).unwrap(); + let vitem_s = item_to_string(&vitem); + assert_eq!(&vitem_s[..], ex_s); + + let ex_s = "extern crate foo as bar;"; + let vitem = string_to_item(ex_s.to_string()).unwrap(); + let vitem_s = item_to_string(&vitem); + assert_eq!(&vitem_s[..], ex_s); + }) +} + +fn get_spans_of_pat_idents(src: &str) -> Vec { + let item = string_to_item(src.to_string()).unwrap(); + + struct PatIdentVisitor { + spans: Vec, + } + impl<'a> visit::Visitor<'a> for PatIdentVisitor { + fn visit_pat(&mut self, p: &'a ast::Pat) { + match &p.kind { + PatKind::Ident(_, ident, _) => { + self.spans.push(ident.span); + } + _ => { + visit::walk_pat(self, p); + } + } + } + } + let mut v = PatIdentVisitor { spans: Vec::new() }; + visit::walk_item(&mut v, &item); + return v.spans; +} + +#[test] +fn span_of_self_arg_pat_idents_are_correct() { + create_default_session_globals_then(|| { + let srcs = [ + "impl z { fn a (&self, &myarg: i32) {} }", + "impl z { fn a (&mut self, &myarg: i32) {} }", + "impl z { fn a (&'a self, &myarg: i32) {} }", + "impl z { fn a (self, &myarg: i32) {} }", + "impl z { fn a (self: Foo, &myarg: i32) {} }", + ]; + + for src in srcs { + let spans = get_spans_of_pat_idents(src); + let (lo, hi) = (spans[0].lo(), spans[0].hi()); + assert!( + "self" == &src[lo.to_usize()..hi.to_usize()], + "\"{}\" != \"self\". src=\"{}\"", + &src[lo.to_usize()..hi.to_usize()], + src + ) + } + }) +} + +#[test] +fn parse_exprs() { + create_default_session_globals_then(|| { + // just make sure that they parse.... + string_to_expr("3 + 4".to_string()); + string_to_expr("a::z.froob(b,&(987+3))".to_string()); + }) +} + +#[test] +fn attrs_fix_bug() { + create_default_session_globals_then(|| { + string_to_item( + "pub fn mk_file_writer(path: &Path, flags: &[FileFlag]) + -> Result, String> { +#[cfg(windows)] +fn wb() -> c_int { + (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int +} + +#[cfg(unix)] +fn wb() -> c_int { O_WRONLY as c_int } + +let mut fflags: c_int = wb(); +}" + .to_string(), + ); + }) +} + +#[test] +fn crlf_doc_comments() { + create_default_session_globals_then(|| { + let psess = psess(); + + let name_1 = FileName::Custom("crlf_source_1".to_string()); + let source = "/// doc comment\r\nfn foo() {}".to_string(); + let item = parse_item_from_source_str(name_1, source, &psess).unwrap().unwrap(); + let doc = item.attrs.iter().filter_map(|at| at.doc_str()).next().unwrap(); + assert_eq!(doc.as_str(), " doc comment"); + + let name_2 = FileName::Custom("crlf_source_2".to_string()); + let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string(); + let item = parse_item_from_source_str(name_2, source, &psess).unwrap().unwrap(); + let docs = item.attrs.iter().filter_map(|at| at.doc_str()).collect::>(); + let b: &[_] = &[Symbol::intern(" doc comment"), Symbol::intern(" line 2")]; + assert_eq!(&docs[..], b); + + let name_3 = FileName::Custom("clrf_source_3".to_string()); + let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string(); + let item = parse_item_from_source_str(name_3, source, &psess).unwrap().unwrap(); + let doc = item.attrs.iter().filter_map(|at| at.doc_str()).next().unwrap(); + assert_eq!(doc.as_str(), " doc comment\n * with CRLF "); + }); +} + +#[test] +fn ttdelim_span() { + fn parse_expr_from_source_str( + name: FileName, + source: String, + psess: &ParseSess, + ) -> PResult<'_, P> { + new_parser_from_source_str(psess, name, source).parse_expr() + } + + create_default_session_globals_then(|| { + let psess = psess(); + let expr = parse_expr_from_source_str( + PathBuf::from("foo").into(), + "foo!( fn main() { body } )".to_string(), + &psess, + ) + .unwrap(); + + let ast::ExprKind::MacCall(mac) = &expr.kind else { panic!("not a macro") }; + let span = mac.args.tokens.trees().last().unwrap().span(); + + match psess.source_map().span_to_snippet(span) { + Ok(s) => assert_eq!(&s[..], "{ body }"), + Err(_) => panic!("could not get snippet"), + } + }); +} + +// This tests that when parsing a string (rather than a file) we don't try +// and read in a file for a module declaration and just parse a stub. +// See `recurse_into_file_modules` in the parser. +#[test] +fn out_of_line_mod() { + create_default_session_globals_then(|| { + let item = parse_item_from_source_str( + PathBuf::from("foo").into(), + "mod foo { struct S; mod this_does_not_exist; }".to_owned(), + &psess(), + ) + .unwrap() + .unwrap(); + + let ast::ItemKind::Mod(_, mod_kind) = &item.kind else { panic!() }; + assert!(matches!(mod_kind, ast::ModKind::Loaded(items, ..) if items.len() == 2)); + }); +} + +#[test] +fn eqmodws() { + assert_eq!(matches_codepattern("", ""), true); + assert_eq!(matches_codepattern("", "a"), false); + assert_eq!(matches_codepattern("a", ""), false); + assert_eq!(matches_codepattern("a", "a"), true); + assert_eq!(matches_codepattern("a b", "a \n\t\r b"), true); + assert_eq!(matches_codepattern("a b ", "a \n\t\r b"), true); + assert_eq!(matches_codepattern("a b", "a \n\t\r b "), false); + assert_eq!(matches_codepattern("a b", "a b"), true); + assert_eq!(matches_codepattern("ab", "a b"), false); + assert_eq!(matches_codepattern("a b", "ab"), true); + assert_eq!(matches_codepattern(" a b", "ab"), true); +} + +#[test] +fn pattern_whitespace() { + assert_eq!(matches_codepattern("", "\x0C"), false); + assert_eq!(matches_codepattern("a b ", "a \u{0085}\n\t\r b"), true); + assert_eq!(matches_codepattern("a b", "a \u{0085}\n\t\r b "), false); +} + +#[test] +fn non_pattern_whitespace() { + // These have the property 'White_Space' but not 'Pattern_White_Space' + assert_eq!(matches_codepattern("a b", "a\u{2002}b"), false); + assert_eq!(matches_codepattern("a b", "a\u{2002}b"), false); + assert_eq!(matches_codepattern("\u{205F}a b", "ab"), false); + assert_eq!(matches_codepattern("a \u{3000}b", "ab"), false); +} diff --git a/compiler/rustc_expand/src/tokenstream/tests.rs b/compiler/rustc_parse/src/parser/tokenstream/tests.rs similarity index 98% rename from compiler/rustc_expand/src/tokenstream/tests.rs rename to compiler/rustc_parse/src/parser/tokenstream/tests.rs index 78795e86fd5da..9be00a1479153 100644 --- a/compiler/rustc_expand/src/tokenstream/tests.rs +++ b/compiler/rustc_parse/src/parser/tokenstream/tests.rs @@ -1,5 +1,4 @@ -use crate::tests::string_to_stream; - +use crate::parser::tests::string_to_stream; use rustc_ast::token::{self, IdentIsRaw}; use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_span::create_default_session_globals_then; diff --git a/compiler/rustc_passes/messages.ftl b/compiler/rustc_passes/messages.ftl index a545c170297de..9d58d301e2bc2 100644 --- a/compiler/rustc_passes/messages.ftl +++ b/compiler/rustc_passes/messages.ftl @@ -49,12 +49,6 @@ passes_attr_crate_level = passes_attr_only_in_functions = `{$attr}` attribute can only be used on functions -passes_attr_only_on_main = - `{$attr}` attribute can only be used on `fn main()` - -passes_attr_only_on_root_main = - `{$attr}` attribute can only be used on root `fn main()` - passes_both_ffi_const_and_pure = `#[ffi_const]` function cannot be `#[ffi_pure]` @@ -695,9 +689,6 @@ passes_transparent_incompatible = passes_undefined_naked_function_abi = Rust ABI is unsupported in naked functions -passes_unix_sigpipe_values = - valid values for `#[unix_sigpipe = "..."]` are `inherit`, `sig_ign`, or `sig_dfl` - passes_unknown_external_lang_item = unknown external lang item: `{$lang_item}` diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index c403e9196fab2..e60aa27dba2b9 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -2523,7 +2523,6 @@ fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) { sym::automatically_derived, sym::start, sym::rustc_main, - sym::unix_sigpipe, sym::derive, sym::test, sym::test_case, diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index 438c583db49e5..b43c8282db1db 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -12,17 +12,16 @@ use rustc_span::symbol::sym; use rustc_span::{Span, Symbol}; use crate::errors::{ - AttrOnlyInFunctions, AttrOnlyOnMain, AttrOnlyOnRootMain, ExternMain, MultipleRustcMain, - MultipleStartFunctions, NoMainErr, UnixSigpipeValues, + AttrOnlyInFunctions, ExternMain, MultipleRustcMain, MultipleStartFunctions, NoMainErr, }; struct EntryContext<'tcx> { tcx: TyCtxt<'tcx>, - /// The function that has attribute named `main`. - attr_main_fn: Option<(LocalDefId, Span)>, + /// The function has the `#[rustc_main]` attribute. + rustc_main_fn: Option<(LocalDefId, Span)>, - /// The function that has the attribute 'start' on it. + /// The function that has the attribute `#[start]` on it. start_fn: Option<(LocalDefId, Span)>, /// The functions that one might think are `main` but aren't, e.g. @@ -43,10 +42,10 @@ fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> { } let mut ctxt = - EntryContext { tcx, attr_main_fn: None, start_fn: None, non_main_fns: Vec::new() }; + EntryContext { tcx, rustc_main_fn: None, start_fn: None, non_main_fns: Vec::new() }; for id in tcx.hir().items() { - find_item(id, &mut ctxt); + check_and_search_item(id, &mut ctxt); } configure_main(tcx, &ctxt) @@ -57,7 +56,16 @@ fn attr_span_by_symbol(ctxt: &EntryContext<'_>, id: ItemId, sym: Symbol) -> Opti attr::find_by_name(attrs, sym).map(|attr| attr.span) } -fn find_item(id: ItemId, ctxt: &mut EntryContext<'_>) { +fn check_and_search_item(id: ItemId, ctxt: &mut EntryContext<'_>) { + if !matches!(ctxt.tcx.def_kind(id.owner_id), DefKind::Fn) { + for attr in [sym::start, sym::rustc_main] { + if let Some(span) = attr_span_by_symbol(ctxt, id, attr) { + ctxt.tcx.dcx().emit_err(AttrOnlyInFunctions { span, attr }); + } + } + return; + } + let at_root = ctxt.tcx.opt_local_parent(id.owner_id.def_id) == Some(CRATE_DEF_ID); let attrs = ctxt.tcx.hir().attrs(id.hir_id()); @@ -66,41 +74,25 @@ fn find_item(id: ItemId, ctxt: &mut EntryContext<'_>) { at_root, ctxt.tcx.opt_item_name(id.owner_id.to_def_id()), ); + match entry_point_type { - EntryPointType::None => { - if let Some(span) = attr_span_by_symbol(ctxt, id, sym::unix_sigpipe) { - ctxt.tcx.dcx().emit_err(AttrOnlyOnMain { span, attr: sym::unix_sigpipe }); - } - } - _ if !matches!(ctxt.tcx.def_kind(id.owner_id), DefKind::Fn) => { - for attr in [sym::start, sym::rustc_main] { - if let Some(span) = attr_span_by_symbol(ctxt, id, attr) { - ctxt.tcx.dcx().emit_err(AttrOnlyInFunctions { span, attr }); - } - } - } - EntryPointType::MainNamed => (), + EntryPointType::None => {} + EntryPointType::MainNamed => {} EntryPointType::OtherMain => { - if let Some(span) = attr_span_by_symbol(ctxt, id, sym::unix_sigpipe) { - ctxt.tcx.dcx().emit_err(AttrOnlyOnRootMain { span, attr: sym::unix_sigpipe }); - } ctxt.non_main_fns.push(ctxt.tcx.def_span(id.owner_id)); } EntryPointType::RustcMainAttr => { - if ctxt.attr_main_fn.is_none() { - ctxt.attr_main_fn = Some((id.owner_id.def_id, ctxt.tcx.def_span(id.owner_id))); + if ctxt.rustc_main_fn.is_none() { + ctxt.rustc_main_fn = Some((id.owner_id.def_id, ctxt.tcx.def_span(id.owner_id))); } else { ctxt.tcx.dcx().emit_err(MultipleRustcMain { span: ctxt.tcx.def_span(id.owner_id.to_def_id()), - first: ctxt.attr_main_fn.unwrap().1, + first: ctxt.rustc_main_fn.unwrap().1, additional: ctxt.tcx.def_span(id.owner_id.to_def_id()), }); } } EntryPointType::Start => { - if let Some(span) = attr_span_by_symbol(ctxt, id, sym::unix_sigpipe) { - ctxt.tcx.dcx().emit_err(AttrOnlyOnMain { span, attr: sym::unix_sigpipe }); - } if ctxt.start_fn.is_none() { ctxt.start_fn = Some((id.owner_id.def_id, ctxt.tcx.def_span(id.owner_id))); } else { @@ -118,10 +110,11 @@ fn find_item(id: ItemId, ctxt: &mut EntryContext<'_>) { fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) -> Option<(DefId, EntryFnType)> { if let Some((def_id, _)) = visitor.start_fn { Some((def_id.to_def_id(), EntryFnType::Start)) - } else if let Some((local_def_id, _)) = visitor.attr_main_fn { + } else if let Some((local_def_id, _)) = visitor.rustc_main_fn { let def_id = local_def_id.to_def_id(); - Some((def_id, EntryFnType::Main { sigpipe: sigpipe(tcx, def_id) })) + Some((def_id, EntryFnType::Main { sigpipe: sigpipe(tcx) })) } else { + // The actual resolution of main happens in the resolver, this here if let Some(main_def) = tcx.resolutions(()).main_def && let Some(def_id) = main_def.opt_fn_def_id() { @@ -133,31 +126,19 @@ fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) -> Option<(DefId, return None; } - return Some((def_id, EntryFnType::Main { sigpipe: sigpipe(tcx, def_id) })); + return Some((def_id, EntryFnType::Main { sigpipe: sigpipe(tcx) })); } no_main_err(tcx, visitor); None } } -fn sigpipe(tcx: TyCtxt<'_>, def_id: DefId) -> u8 { - if let Some(attr) = tcx.get_attr(def_id, sym::unix_sigpipe) { - match (attr.value_str(), attr.meta_item_list()) { - (Some(sym::inherit), None) => sigpipe::INHERIT, - (Some(sym::sig_ign), None) => sigpipe::SIG_IGN, - (Some(sym::sig_dfl), None) => sigpipe::SIG_DFL, - (Some(_), None) => { - tcx.dcx().emit_err(UnixSigpipeValues { span: attr.span }); - sigpipe::DEFAULT - } - _ => { - // Keep going so that `fn emit_malformed_attribute()` can print - // an excellent error message - sigpipe::DEFAULT - } - } - } else { - sigpipe::DEFAULT +fn sigpipe(tcx: TyCtxt<'_>) -> u8 { + match tcx.sess.opts.unstable_opts.on_broken_pipe { + rustc_target::spec::OnBrokenPipe::Default => sigpipe::DEFAULT, + rustc_target::spec::OnBrokenPipe::Kill => sigpipe::SIG_DFL, + rustc_target::spec::OnBrokenPipe::Error => sigpipe::SIG_IGN, + rustc_target::spec::OnBrokenPipe::Inherit => sigpipe::INHERIT, } } diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 03a607348e88c..65cad82cc8c2b 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -1206,22 +1206,6 @@ pub struct NakedFunctionsMustUseNoreturn { pub last_span: Span, } -#[derive(Diagnostic)] -#[diag(passes_attr_only_on_main)] -pub struct AttrOnlyOnMain { - #[primary_span] - pub span: Span, - pub attr: Symbol, -} - -#[derive(Diagnostic)] -#[diag(passes_attr_only_on_root_main)] -pub struct AttrOnlyOnRootMain { - #[primary_span] - pub span: Span, - pub attr: Symbol, -} - #[derive(Diagnostic)] #[diag(passes_attr_only_in_functions)] pub struct AttrOnlyInFunctions { @@ -1259,13 +1243,6 @@ pub struct ExternMain { pub span: Span, } -#[derive(Diagnostic)] -#[diag(passes_unix_sigpipe_values)] -pub struct UnixSigpipeValues { - #[primary_span] - pub span: Span, -} - pub struct NoMainErr { pub sp: Span, pub crate_name: Symbol, diff --git a/compiler/rustc_pattern_analysis/src/usefulness.rs b/compiler/rustc_pattern_analysis/src/usefulness.rs index 74af9154f8581..6e96a93473f7d 100644 --- a/compiler/rustc_pattern_analysis/src/usefulness.rs +++ b/compiler/rustc_pattern_analysis/src/usefulness.rs @@ -42,7 +42,6 @@ //! This is enough to compute usefulness: a pattern in a `match` expression is redundant iff it is //! not useful w.r.t. the patterns above it: //! ```compile_fail,E0004 -//! # #![feature(exclusive_range_pattern)] //! # fn foo() { //! match Some(0u32) { //! Some(0..100) => {}, diff --git a/compiler/rustc_privacy/Cargo.toml b/compiler/rustc_privacy/Cargo.toml index e7a32771f350d..f998e0ff1547f 100644 --- a/compiler/rustc_privacy/Cargo.toml +++ b/compiler/rustc_privacy/Cargo.toml @@ -11,7 +11,6 @@ rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_fluent_macro = { path = "../rustc_fluent_macro" } rustc_hir = { path = "../rustc_hir" } -rustc_hir_analysis = { path = "../rustc_hir_analysis" } rustc_macros = { path = "../rustc_macros" } rustc_middle = { path = "../rustc_middle" } rustc_session = { path = "../rustc_session" } diff --git a/compiler/rustc_query_system/Cargo.toml b/compiler/rustc_query_system/Cargo.toml index 6ea87a4a633e5..4d845ab0d07b8 100644 --- a/compiler/rustc_query_system/Cargo.toml +++ b/compiler/rustc_query_system/Cargo.toml @@ -19,7 +19,6 @@ rustc_serialize = { path = "../rustc_serialize" } rustc_session = { path = "../rustc_session" } rustc_span = { path = "../rustc_span" } rustc_target = { path = "../rustc_target" } -rustc_type_ir = { path = "../rustc_type_ir" } smallvec = { version = "1.8.1", features = ["union", "may_dangle"] } thin-vec = "0.2.12" tracing = "0.1" diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 12484462f82f4..01e279b6d04fa 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -1617,7 +1617,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { let post = format!(", consider renaming `{}` into `{snippet}`", suggestion.candidate); (span, snippet, post) } else { - (span, suggestion.candidate.to_string(), String::new()) + (span, suggestion.candidate.to_ident_string(), String::new()) }; let msg = match suggestion.target { SuggestionTarget::SimilarlyNamed => format!( diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 82e41b6c31436..35bf3f761df39 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -141,7 +141,7 @@ pub(crate) fn registered_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools { } // We implicitly add `rustfmt`, `clippy`, `diagnostic` to known tools, // but it's not an error to register them explicitly. - let predefined_tools = [sym::clippy, sym::rustfmt, sym::diagnostic]; + let predefined_tools = [sym::clippy, sym::rustfmt, sym::diagnostic, sym::miri]; registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span)); registered_tools } diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs index 40cd0c14b05f4..d67132d2dd4f6 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs @@ -4,7 +4,9 @@ //! //! For more information about LLVM CFI and cross-language LLVM CFI support for the Rust compiler, //! see design document in the tracking issue #89653. -use rustc_data_structures::base_n; +use rustc_data_structures::base_n::ToBaseN; +use rustc_data_structures::base_n::ALPHANUMERIC_ONLY; +use rustc_data_structures::base_n::CASE_INSENSITIVE; use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; use rustc_middle::bug; @@ -736,7 +738,7 @@ fn encode_ty_name(tcx: TyCtxt<'_>, def_id: DefId) -> String { /// ). fn to_disambiguator(num: u64) -> String { if let Some(num) = num.checked_sub(1) { - format!("s{}_", base_n::encode(num as u128, base_n::ALPHANUMERIC_ONLY)) + format!("s{}_", num.to_base(ALPHANUMERIC_ONLY)) } else { "s_".to_string() } @@ -746,7 +748,7 @@ fn to_disambiguator(num: u64) -> String { /// ). fn to_seq_id(num: usize) -> String { if let Some(num) = num.checked_sub(1) { - base_n::encode(num as u128, base_n::CASE_INSENSITIVE).to_uppercase() + (num as u64).to_base(CASE_INSENSITIVE).to_uppercase() } else { "".to_string() } diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index ad66e5e1c2b4d..f2bdabbf39428 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -2909,7 +2909,9 @@ pub(crate) mod dep_tracking { use rustc_feature::UnstableFeatures; use rustc_span::edition::Edition; use rustc_span::RealFileName; - use rustc_target::spec::{CodeModel, MergeFunctions, PanicStrategy, RelocModel, WasmCAbi}; + use rustc_target::spec::{ + CodeModel, MergeFunctions, OnBrokenPipe, PanicStrategy, RelocModel, WasmCAbi, + }; use rustc_target::spec::{ RelroLevel, SanitizerSet, SplitDebuginfo, StackProtector, TargetTriple, TlsModel, }; @@ -2973,6 +2975,7 @@ pub(crate) mod dep_tracking { InstrumentXRay, CrateType, MergeFunctions, + OnBrokenPipe, PanicStrategy, RelroLevel, OptLevel, diff --git a/compiler/rustc_session/src/config/cfg.rs b/compiler/rustc_session/src/config/cfg.rs index 31badbd86927d..2fa04bbe345e8 100644 --- a/compiler/rustc_session/src/config/cfg.rs +++ b/compiler/rustc_session/src/config/cfg.rs @@ -262,13 +262,15 @@ impl CheckCfg { ins!(sym::debug_assertions, no_values); - // These four are never set by rustc, but we set them anyway: they - // should not trigger a lint because `cargo clippy`, `cargo doc`, - // `cargo test` and `cargo miri run` (respectively) can set them. + // These four are never set by rustc, but we set them anyway; they + // should not trigger the lint because `cargo clippy`, `cargo doc`, + // `cargo test`, `cargo miri run` and `cargo fmt` (respectively) + // can set them. ins!(sym::clippy, no_values); ins!(sym::doc, no_values); ins!(sym::doctest, no_values); ins!(sym::miri, no_values); + ins!(sym::rustfmt, no_values); ins!(sym::overflow_checks, no_values); diff --git a/compiler/rustc_session/src/config/sigpipe.rs b/compiler/rustc_session/src/config/sigpipe.rs index 1fadc75cfd0d2..1830ee034855b 100644 --- a/compiler/rustc_session/src/config/sigpipe.rs +++ b/compiler/rustc_session/src/config/sigpipe.rs @@ -1,6 +1,6 @@ //! NOTE: Keep these constants in sync with `library/std/src/sys/pal/unix/mod.rs`! -/// The default value if `#[unix_sigpipe]` is not specified. This resolves +/// The default value if `-Zon-broken-pipe=...` is not specified. This resolves /// to `SIG_IGN` in `library/std/src/sys/pal/unix/mod.rs`. /// /// Note that `SIG_IGN` has been the Rust default since 2014. See diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 7355e5b695347..65660286dd73a 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -12,7 +12,7 @@ use rustc_span::edition::Edition; use rustc_span::RealFileName; use rustc_span::SourceFileHashAlgorithm; use rustc_target::spec::{ - CodeModel, LinkerFlavorCli, MergeFunctions, PanicStrategy, SanitizerSet, WasmCAbi, + CodeModel, LinkerFlavorCli, MergeFunctions, OnBrokenPipe, PanicStrategy, SanitizerSet, WasmCAbi, }; use rustc_target::spec::{ RelocModel, RelroLevel, SplitDebuginfo, StackProtector, TargetTriple, TlsModel, @@ -378,6 +378,7 @@ mod desc { pub const parse_time_passes_format: &str = "`text` (default) or `json`"; pub const parse_passes: &str = "a space-separated list of passes, or `all`"; pub const parse_panic_strategy: &str = "either `unwind` or `abort`"; + pub const parse_on_broken_pipe: &str = "either `kill`, `error`, or `inherit`"; pub const parse_opt_panic_strategy: &str = parse_panic_strategy; pub const parse_oom_strategy: &str = "either `panic` or `abort`"; pub const parse_relro_level: &str = "one of: `full`, `partial`, or `off`"; @@ -708,6 +709,17 @@ mod parse { true } + pub(crate) fn parse_on_broken_pipe(slot: &mut OnBrokenPipe, v: Option<&str>) -> bool { + match v { + // OnBrokenPipe::Default can't be explicitly specified + Some("kill") => *slot = OnBrokenPipe::Kill, + Some("error") => *slot = OnBrokenPipe::Error, + Some("inherit") => *slot = OnBrokenPipe::Inherit, + _ => return false, + } + true + } + pub(crate) fn parse_oom_strategy(slot: &mut OomStrategy, v: Option<&str>) -> bool { match v { Some("panic") => *slot = OomStrategy::Panic, @@ -1833,6 +1845,8 @@ options! { "do not use unique names for text and data sections when -Z function-sections is used"), normalize_docs: bool = (false, parse_bool, [TRACKED], "normalize associated items in rustdoc when generating documentation"), + on_broken_pipe: OnBrokenPipe = (OnBrokenPipe::Default, parse_on_broken_pipe, [TRACKED], + "behavior of std::io::ErrorKind::BrokenPipe (SIGPIPE)"), oom: OomStrategy = (OomStrategy::Abort, parse_oom_strategy, [TRACKED], "panic strategy for out-of-memory handling"), osx_rpath_install_name: bool = (false, parse_bool, [TRACKED], diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 7fe94c2e82ba6..d41059e8c24a4 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1511,6 +1511,7 @@ symbols! { require, residual, result, + result_ffi_guarantees, resume, return_position_impl_trait_in_trait, return_type_notation, @@ -1936,7 +1937,6 @@ symbols! { unit, universal_impl_trait, unix, - unix_sigpipe, unlikely, unmarked_api, unnamed_fields, diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index fc2c3dcb2d952..5cdfb773b5cb6 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -1,4 +1,4 @@ -use rustc_data_structures::base_n; +use rustc_data_structures::base_n::ToBaseN; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::intern::Interned; use rustc_hir as hir; @@ -832,7 +832,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { /// e.g. `1` becomes `"0_"`, `62` becomes `"Z_"`, etc. pub(crate) fn push_integer_62(x: u64, output: &mut String) { if let Some(x) = x.checked_sub(1) { - base_n::push_str(x as u128, base_n::ALPHANUMERIC_ONLY, output); + output.push_str(&x.to_base(62)); } output.push('_'); } diff --git a/compiler/rustc_target/src/spec/base/fuchsia.rs b/compiler/rustc_target/src/spec/base/fuchsia.rs index 4c2775850d132..d1ac22f3a098c 100644 --- a/compiler/rustc_target/src/spec/base/fuchsia.rs +++ b/compiler/rustc_target/src/spec/base/fuchsia.rs @@ -1,4 +1,6 @@ -use crate::spec::{crt_objects, cvs, Cc, LinkOutputKind, LinkerFlavor, Lld, TargetOptions}; +use crate::spec::{ + crt_objects, cvs, Cc, FramePointer, LinkOutputKind, LinkerFlavor, Lld, TargetOptions, +}; pub fn opts() -> TargetOptions { // This mirrors the linker options provided by clang. We presume lld for @@ -38,6 +40,7 @@ pub fn opts() -> TargetOptions { ]), position_independent_executables: true, has_thread_local: true, + frame_pointer: FramePointer::NonLeaf, ..Default::default() } } diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index bd347c1b4b3fd..cbb248a0fc21c 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -778,6 +778,14 @@ pub enum PanicStrategy { Abort, } +#[derive(Clone, Copy, Debug, PartialEq, Hash, Encodable, Decodable, HashStable_Generic)] +pub enum OnBrokenPipe { + Default, + Kill, + Error, + Inherit, +} + impl PanicStrategy { pub fn desc(&self) -> &str { match *self { diff --git a/compiler/rustc_trait_selection/src/infer.rs b/compiler/rustc_trait_selection/src/infer.rs index b2400cec42f16..3dc55509dad9d 100644 --- a/compiler/rustc_trait_selection/src/infer.rs +++ b/compiler/rustc_trait_selection/src/infer.rs @@ -1,8 +1,9 @@ use crate::traits::query::evaluate_obligation::InferCtxtExt as _; -use crate::traits::{self, ObligationCtxt, SelectionContext, TraitEngineExt as _}; +use crate::traits::{self, ObligationCtxt, SelectionContext}; + use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; -use rustc_infer::traits::{Obligation, TraitEngine, TraitEngineExt as _}; +use rustc_infer::traits::Obligation; use rustc_macros::extension; use rustc_middle::arena::ArenaAllocatable; use rustc_middle::infer::canonical::{Canonical, CanonicalQueryResponse, QueryResponse}; @@ -93,9 +94,9 @@ impl<'tcx> InferCtxt<'tcx> { ty::TraitRef::new(self.tcx, trait_def_id, [ty]), )) { Ok(Some(selection)) => { - let mut fulfill_cx = >::new(self); - fulfill_cx.register_predicate_obligations(self, selection.nested_obligations()); - Some(fulfill_cx.select_all_or_error(self)) + let ocx = ObligationCtxt::new(self); + ocx.register_obligations(selection.nested_obligations()); + Some(ocx.select_all_or_error()) } Ok(None) | Err(_) => None, } diff --git a/compiler/rustc_trait_selection/src/solve/assembly/mod.rs b/compiler/rustc_trait_selection/src/solve/assembly/mod.rs index 280975f63bd3d..f2ca42a0be91e 100644 --- a/compiler/rustc_trait_selection/src/solve/assembly/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/assembly/mod.rs @@ -58,15 +58,15 @@ pub(super) trait GoalKind<'tcx>: /// goal by equating it with the assumption. fn probe_and_consider_implied_clause( ecx: &mut EvalCtxt<'_, 'tcx>, - source: CandidateSource, + parent_source: CandidateSource, goal: Goal<'tcx, Self>, assumption: ty::Clause<'tcx>, - requirements: impl IntoIterator>>, + requirements: impl IntoIterator>)>, ) -> Result, NoSolution> { - Self::probe_and_match_goal_against_assumption(ecx, source, goal, assumption, |ecx| { - // FIXME(-Znext-solver=coinductive): check whether this should be - // `GoalSource::ImplWhereBound` for any caller. - ecx.add_goals(GoalSource::Misc, requirements); + Self::probe_and_match_goal_against_assumption(ecx, parent_source, goal, assumption, |ecx| { + for (nested_source, goal) in requirements { + ecx.add_goal(nested_source, goal); + } ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) }) } @@ -85,9 +85,8 @@ pub(super) trait GoalKind<'tcx>: let ty::Dynamic(bounds, _, _) = *goal.predicate.self_ty().kind() else { bug!("expected object type in `probe_and_consider_object_bound_candidate`"); }; - // FIXME(-Znext-solver=coinductive): Should this be `GoalSource::ImplWhereBound`? ecx.add_goals( - GoalSource::Misc, + GoalSource::ImplWhereBound, structural_traits::predicates_for_object_candidate( ecx, goal.param_env, diff --git a/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs b/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs index 6722abd709c31..d6bf2b596ef1e 100644 --- a/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs +++ b/compiler/rustc_trait_selection/src/solve/eval_ctxt/canonical.rs @@ -90,6 +90,8 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { &mut self, certainty: Certainty, ) -> QueryResult<'tcx> { + self.inspect.make_canonical_response(certainty); + let goals_certainty = self.try_evaluate_added_goals()?; assert_eq!( self.tainted, @@ -98,8 +100,6 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { previous call to `try_evaluate_added_goals!`" ); - self.inspect.make_canonical_response(certainty); - // When normalizing, we've replaced the expected term with an unconstrained // inference variable. This means that we dropped information which could // have been important. We handle this by instead returning the nested goals diff --git a/compiler/rustc_trait_selection/src/solve/eval_ctxt/mod.rs b/compiler/rustc_trait_selection/src/solve/eval_ctxt/mod.rs index 1710746ae504e..773babde0d7b3 100644 --- a/compiler/rustc_trait_selection/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/eval_ctxt/mod.rs @@ -454,7 +454,7 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> { } else { self.infcx.enter_forall(kind, |kind| { let goal = goal.with(self.tcx(), ty::Binder::dummy(kind)); - self.add_goal(GoalSource::Misc, goal); + self.add_goal(GoalSource::InstantiateHigherRanked, goal); self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) }) } @@ -888,8 +888,12 @@ impl<'tcx> EvalCtxt<'_, 'tcx> { self.infcx.resolve_vars_if_possible(value) } - pub(super) fn fresh_args_for_item(&self, def_id: DefId) -> ty::GenericArgsRef<'tcx> { - self.infcx.fresh_args_for_item(DUMMY_SP, def_id) + pub(super) fn fresh_args_for_item(&mut self, def_id: DefId) -> ty::GenericArgsRef<'tcx> { + let args = self.infcx.fresh_args_for_item(DUMMY_SP, def_id); + for arg in args { + self.inspect.add_var_value(arg); + } + args } pub(super) fn translate_args( diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index 3fa409eefffcd..fd4b5805f027d 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -1,15 +1,20 @@ use std::mem; +use std::ops::ControlFlow; use rustc_infer::infer::InferCtxt; -use rustc_infer::traits::solve::MaybeCause; +use rustc_infer::traits::query::NoSolution; +use rustc_infer::traits::solve::inspect::ProbeKind; +use rustc_infer::traits::solve::{CandidateSource, GoalSource, MaybeCause}; use rustc_infer::traits::{ - query::NoSolution, FulfillmentError, FulfillmentErrorCode, MismatchedProjectionTypes, - PredicateObligation, SelectionError, TraitEngine, + self, FulfillmentError, FulfillmentErrorCode, MismatchedProjectionTypes, Obligation, + ObligationCause, PredicateObligation, SelectionError, TraitEngine, }; -use rustc_middle::ty; use rustc_middle::ty::error::{ExpectedFound, TypeError}; +use rustc_middle::ty::{self, TyCtxt}; +use rustc_span::symbol::sym; use super::eval_ctxt::GenerateProofTree; +use super::inspect::{ProofTreeInferCtxtExt, ProofTreeVisitor}; use super::{Certainty, InferCtxtEvalExt}; /// A trait engine using the new trait solver. @@ -133,9 +138,9 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> { .collect(); errors.extend(self.obligations.overflowed.drain(..).map(|obligation| FulfillmentError { - root_obligation: obligation.clone(), + obligation: find_best_leaf_obligation(infcx, &obligation, true), code: FulfillmentErrorCode::Ambiguity { overflow: Some(true) }, - obligation, + root_obligation: obligation, })); errors @@ -192,8 +197,10 @@ impl<'tcx> TraitEngine<'tcx> for FulfillmentCtxt<'tcx> { fn fulfillment_error_for_no_solution<'tcx>( infcx: &InferCtxt<'tcx>, - obligation: PredicateObligation<'tcx>, + root_obligation: PredicateObligation<'tcx>, ) -> FulfillmentError<'tcx> { + let obligation = find_best_leaf_obligation(infcx, &root_obligation, false); + let code = match obligation.predicate.kind().skip_binder() { ty::PredicateKind::Clause(ty::ClauseKind::Projection(_)) => { FulfillmentErrorCode::ProjectionError( @@ -234,7 +241,8 @@ fn fulfillment_error_for_no_solution<'tcx>( bug!("unexpected goal: {obligation:?}") } }; - FulfillmentError { root_obligation: obligation.clone(), code, obligation } + + FulfillmentError { obligation, code, root_obligation } } fn fulfillment_error_for_stalled<'tcx>( @@ -258,5 +266,146 @@ fn fulfillment_error_for_stalled<'tcx>( } }); - FulfillmentError { obligation: obligation.clone(), code, root_obligation: obligation } + FulfillmentError { + obligation: find_best_leaf_obligation(infcx, &obligation, true), + code, + root_obligation: obligation, + } +} + +fn find_best_leaf_obligation<'tcx>( + infcx: &InferCtxt<'tcx>, + obligation: &PredicateObligation<'tcx>, + consider_ambiguities: bool, +) -> PredicateObligation<'tcx> { + let obligation = infcx.resolve_vars_if_possible(obligation.clone()); + infcx + .visit_proof_tree( + obligation.clone().into(), + &mut BestObligation { obligation: obligation.clone(), consider_ambiguities }, + ) + .break_value() + .unwrap_or(obligation) +} + +struct BestObligation<'tcx> { + obligation: PredicateObligation<'tcx>, + consider_ambiguities: bool, +} + +impl<'tcx> BestObligation<'tcx> { + fn with_derived_obligation( + &mut self, + derived_obligation: PredicateObligation<'tcx>, + and_then: impl FnOnce(&mut Self) -> >::Result, + ) -> >::Result { + let old_obligation = std::mem::replace(&mut self.obligation, derived_obligation); + let res = and_then(self); + self.obligation = old_obligation; + res + } +} + +impl<'tcx> ProofTreeVisitor<'tcx> for BestObligation<'tcx> { + type Result = ControlFlow>; + + fn span(&self) -> rustc_span::Span { + self.obligation.cause.span + } + + fn visit_goal(&mut self, goal: &super::inspect::InspectGoal<'_, 'tcx>) -> Self::Result { + // FIXME: Throw out candidates that have no failing WC and >0 failing misc goal. + // This most likely means that the goal just didn't unify at all, e.g. a param + // candidate with an alias in it. + let candidates = goal.candidates(); + + let [candidate] = candidates.as_slice() else { + return ControlFlow::Break(self.obligation.clone()); + }; + + // Don't walk into impls that have `do_not_recommend`. + if let ProbeKind::TraitCandidate { source: CandidateSource::Impl(impl_def_id), result: _ } = + candidate.kind() + && goal.infcx().tcx.has_attr(impl_def_id, sym::do_not_recommend) + { + return ControlFlow::Break(self.obligation.clone()); + } + + // FIXME: Could we extract a trait ref from a projection here too? + // FIXME: Also, what about considering >1 layer up the stack? May be necessary + // for normalizes-to. + let Some(parent_trait_pred) = goal.goal().predicate.to_opt_poly_trait_pred() else { + return ControlFlow::Break(self.obligation.clone()); + }; + + let tcx = goal.infcx().tcx; + let mut impl_where_bound_count = 0; + for nested_goal in candidate.instantiate_nested_goals(self.span()) { + let obligation; + match nested_goal.source() { + GoalSource::Misc => { + continue; + } + GoalSource::ImplWhereBound => { + obligation = Obligation { + cause: derive_cause( + tcx, + candidate.kind(), + self.obligation.cause.clone(), + impl_where_bound_count, + parent_trait_pred, + ), + param_env: nested_goal.goal().param_env, + predicate: nested_goal.goal().predicate, + recursion_depth: self.obligation.recursion_depth + 1, + }; + impl_where_bound_count += 1; + } + GoalSource::InstantiateHigherRanked => { + obligation = self.obligation.clone(); + } + } + + // Skip nested goals that aren't the *reason* for our goal's failure. + match self.consider_ambiguities { + true if matches!(nested_goal.result(), Ok(Certainty::Maybe(_))) => {} + false if matches!(nested_goal.result(), Err(_)) => {} + _ => continue, + } + + self.with_derived_obligation(obligation, |this| nested_goal.visit_with(this))?; + } + + ControlFlow::Break(self.obligation.clone()) + } +} + +fn derive_cause<'tcx>( + tcx: TyCtxt<'tcx>, + candidate_kind: ProbeKind<'tcx>, + mut cause: ObligationCause<'tcx>, + idx: usize, + parent_trait_pred: ty::PolyTraitPredicate<'tcx>, +) -> ObligationCause<'tcx> { + match candidate_kind { + ProbeKind::TraitCandidate { source: CandidateSource::Impl(impl_def_id), result: _ } => { + if let Some((_, span)) = + tcx.predicates_of(impl_def_id).instantiate_identity(tcx).iter().nth(idx) + { + cause = cause.derived_cause(parent_trait_pred, |derived| { + traits::ImplDerivedObligation(Box::new(traits::ImplDerivedObligationCause { + derived, + impl_or_alias_def_id: impl_def_id, + impl_def_predicate_index: Some(idx), + span, + })) + }) + } + } + ProbeKind::TraitCandidate { source: CandidateSource::BuiltinImpl(..), result: _ } => { + cause = cause.derived_cause(parent_trait_pred, traits::BuiltinDerivedObligation); + } + _ => {} + }; + cause } diff --git a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs index 7c6dd4d3febc9..4f79f1b2aafe0 100644 --- a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs +++ b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs @@ -14,7 +14,6 @@ use rustc_ast_ir::visit::VisitorResult; use rustc_infer::infer::resolve::EagerResolver; use rustc_infer::infer::type_variable::TypeVariableOrigin; use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, InferOk}; -use rustc_infer::traits::{TraitEngine, TraitEngineExt}; use rustc_macros::extension; use rustc_middle::infer::unify_key::ConstVariableOrigin; use rustc_middle::traits::query::NoSolution; @@ -26,9 +25,9 @@ use rustc_middle::ty::TypeFoldable; use rustc_span::{Span, DUMMY_SP}; use crate::solve::eval_ctxt::canonical; -use crate::solve::FulfillmentCtxt; use crate::solve::{EvalCtxt, GoalEvaluationKind, GoalSource}; use crate::solve::{GenerateProofTree, InferCtxtEvalExt}; +use crate::traits::ObligationCtxt; pub struct InspectConfig { pub max_depth: usize, @@ -42,6 +41,7 @@ pub struct InspectGoal<'a, 'tcx> { result: Result, evaluation_kind: inspect::CanonicalGoalEvaluationKind<'tcx>, normalizes_to_term_hack: Option>, + source: GoalSource, } /// The expected term of a `NormalizesTo` goal gets replaced @@ -74,14 +74,13 @@ impl<'tcx> NormalizesToTermHack<'tcx> { .eq(DefineOpaqueTypes::Yes, self.term, self.unconstrained_term) .map_err(|_| NoSolution) .and_then(|InferOk { value: (), obligations }| { - let mut fulfill_cx = FulfillmentCtxt::new(infcx); - fulfill_cx.register_predicate_obligations(infcx, obligations); - if fulfill_cx.select_where_possible(infcx).is_empty() { - if fulfill_cx.pending_obligations().is_empty() { - Ok(Certainty::Yes) - } else { - Ok(Certainty::AMBIGUOUS) - } + let ocx = ObligationCtxt::new(infcx); + ocx.register_obligations(obligations); + let errors = ocx.select_all_or_error(); + if errors.is_empty() { + Ok(Certainty::Yes) + } else if errors.iter().all(|e| !e.is_true_error()) { + Ok(Certainty::AMBIGUOUS) } else { Err(NoSolution) } @@ -92,7 +91,7 @@ impl<'tcx> NormalizesToTermHack<'tcx> { pub struct InspectCandidate<'a, 'tcx> { goal: &'a InspectGoal<'a, 'tcx>, kind: inspect::ProbeKind<'tcx>, - nested_goals: Vec>>>, + nested_goals: Vec<(GoalSource, inspect::CanonicalState<'tcx, Goal<'tcx, ty::Predicate<'tcx>>>)>, final_state: inspect::CanonicalState<'tcx, ()>, result: QueryResult<'tcx>, shallow_certainty: Certainty, @@ -127,10 +126,8 @@ impl<'a, 'tcx> InspectCandidate<'a, 'tcx> { /// back their inference constraints. This function modifies /// the state of the `infcx`. pub fn visit_nested_no_probe>(&self, visitor: &mut V) -> V::Result { - if self.goal.depth < visitor.config().max_depth { - for goal in self.instantiate_nested_goals(visitor.span()) { - try_visit!(visitor.visit_goal(&goal)); - } + for goal in self.instantiate_nested_goals(visitor.span()) { + try_visit!(goal.visit_with(visitor)); } V::Result::output() @@ -145,13 +142,16 @@ impl<'a, 'tcx> InspectCandidate<'a, 'tcx> { let instantiated_goals: Vec<_> = self .nested_goals .iter() - .map(|goal| { - canonical::instantiate_canonical_state( - infcx, - span, - param_env, - &mut orig_values, - *goal, + .map(|(source, goal)| { + ( + *source, + canonical::instantiate_canonical_state( + infcx, + span, + param_env, + &mut orig_values, + *goal, + ), ) }) .collect(); @@ -173,7 +173,7 @@ impl<'a, 'tcx> InspectCandidate<'a, 'tcx> { instantiated_goals .into_iter() - .map(|goal| match goal.predicate.kind().no_bound_vars() { + .map(|(source, goal)| match goal.predicate.kind().no_bound_vars() { Some(ty::PredicateKind::NormalizesTo(ty::NormalizesTo { alias, term })) => { let unconstrained_term = match term.unpack() { ty::TermKind::Ty(_) => infcx @@ -197,6 +197,7 @@ impl<'a, 'tcx> InspectCandidate<'a, 'tcx> { self.goal.depth + 1, proof_tree.unwrap(), Some(NormalizesToTermHack { term, unconstrained_term }), + source, ) } _ => InspectGoal::new( @@ -204,6 +205,7 @@ impl<'a, 'tcx> InspectCandidate<'a, 'tcx> { self.goal.depth + 1, infcx.evaluate_root_goal(goal, GenerateProofTree::Yes).1.unwrap(), None, + source, ), }) .collect() @@ -229,16 +231,23 @@ impl<'a, 'tcx> InspectGoal<'a, 'tcx> { self.result } + pub fn source(&self) -> GoalSource { + self.source + } + fn candidates_recur( &'a self, candidates: &mut Vec>, - nested_goals: &mut Vec>>>, + nested_goals: &mut Vec<( + GoalSource, + inspect::CanonicalState<'tcx, Goal<'tcx, ty::Predicate<'tcx>>>, + )>, probe: &inspect::Probe<'tcx>, ) { let mut shallow_certainty = None; for step in &probe.steps { match step { - &inspect::ProbeStep::AddGoal(_source, goal) => nested_goals.push(goal), + &inspect::ProbeStep::AddGoal(source, goal) => nested_goals.push((source, goal)), inspect::ProbeStep::NestedProbe(ref probe) => { // Nested probes have to prove goals added in their parent // but do not leak them, so we truncate the added goals @@ -321,6 +330,7 @@ impl<'a, 'tcx> InspectGoal<'a, 'tcx> { depth: usize, root: inspect::GoalEvaluation<'tcx>, normalizes_to_term_hack: Option>, + source: GoalSource, ) -> Self { let inspect::GoalEvaluation { uncanonicalized_goal, kind, evaluation } = root; let inspect::GoalEvaluationKind::Root { orig_values } = kind else { unreachable!() }; @@ -343,8 +353,17 @@ impl<'a, 'tcx> InspectGoal<'a, 'tcx> { result, evaluation_kind: evaluation.kind, normalizes_to_term_hack, + source, } } + + pub(crate) fn visit_with>(&self, visitor: &mut V) -> V::Result { + if self.depth < visitor.config().max_depth { + try_visit!(visitor.visit_goal(self)); + } + + V::Result::output() + } } /// The public API to interact with proof trees. @@ -369,6 +388,6 @@ impl<'tcx> InferCtxt<'tcx> { ) -> V::Result { let (_, proof_tree) = self.evaluate_root_goal(goal, GenerateProofTree::Yes); let proof_tree = proof_tree.unwrap(); - visitor.visit_goal(&InspectGoal::new(self, 0, proof_tree, None)) + visitor.visit_goal(&InspectGoal::new(self, 0, proof_tree, None, GoalSource::Misc)) } } diff --git a/compiler/rustc_trait_selection/src/solve/normalizes_to/mod.rs b/compiler/rustc_trait_selection/src/solve/normalizes_to/mod.rs index dab87fffe461e..f886c5886504c 100644 --- a/compiler/rustc_trait_selection/src/solve/normalizes_to/mod.rs +++ b/compiler/rustc_trait_selection/src/solve/normalizes_to/mod.rs @@ -389,7 +389,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for NormalizesTo<'tcx> { CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, pred, - [goal.with(tcx, output_is_sized_pred)], + [(GoalSource::ImplWhereBound, goal.with(tcx, output_is_sized_pred))], ) } @@ -473,7 +473,8 @@ impl<'tcx> assembly::GoalKind<'tcx> for NormalizesTo<'tcx> { pred, [goal.with(tcx, output_is_sized_pred)] .into_iter() - .chain(nested_preds.into_iter().map(|pred| goal.with(tcx, pred))), + .chain(nested_preds.into_iter().map(|pred| goal.with(tcx, pred))) + .map(|goal| (GoalSource::ImplWhereBound, goal)), ) } diff --git a/compiler/rustc_trait_selection/src/solve/trait_goals.rs b/compiler/rustc_trait_selection/src/solve/trait_goals.rs index c8cb14abb554d..d2b893d6383bd 100644 --- a/compiler/rustc_trait_selection/src/solve/trait_goals.rs +++ b/compiler/rustc_trait_selection/src/solve/trait_goals.rs @@ -321,7 +321,7 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, pred, - [goal.with(tcx, output_is_sized_pred)], + [(GoalSource::ImplWhereBound, goal.with(tcx, output_is_sized_pred))], ) } @@ -367,7 +367,8 @@ impl<'tcx> assembly::GoalKind<'tcx> for TraitPredicate<'tcx> { pred, [goal.with(tcx, output_is_sized_pred)] .into_iter() - .chain(nested_preds.into_iter().map(|pred| goal.with(tcx, pred))), + .chain(nested_preds.into_iter().map(|pred| goal.with(tcx, pred))) + .map(|goal| (GoalSource::ImplWhereBound, goal)), ) } diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 86e7c42376aa0..59725ce9de096 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -6,12 +6,9 @@ use crate::infer::outlives::env::OutlivesEnvironment; use crate::infer::InferOk; -use crate::regions::InferCtxtRegionExt; use crate::solve::inspect::{InspectGoal, ProofTreeInferCtxtExt, ProofTreeVisitor}; -use crate::solve::{deeply_normalize_for_diagnostics, inspect, FulfillmentCtxt}; -use crate::traits::engine::TraitEngineExt as _; +use crate::solve::{deeply_normalize_for_diagnostics, inspect}; use crate::traits::select::IntercrateAmbiguityCause; -use crate::traits::structural_normalize::StructurallyNormalizeExt; use crate::traits::NormalizeExt; use crate::traits::SkipLeakCheck; use crate::traits::{ @@ -22,7 +19,7 @@ use rustc_errors::{Diag, EmissionGuarantee}; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt}; -use rustc_infer::traits::{util, FulfillmentErrorCode, TraitEngine, TraitEngineExt}; +use rustc_infer::traits::{util, FulfillmentErrorCode}; use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::solve::{CandidateSource, Certainty, Goal}; use rustc_middle::traits::specialization_graph::OverlapMode; @@ -35,6 +32,7 @@ use std::fmt::Debug; use std::ops::ControlFlow; use super::error_reporting::suggest_new_overflow_limit; +use super::ObligationCtxt; /// Whether we do the orphan check relative to this crate or to some remote crate. #[derive(Copy, Clone, Debug)] @@ -361,23 +359,27 @@ fn impl_intersection_has_impossible_obligation<'a, 'cx, 'tcx>( let infcx = selcx.infcx; if infcx.next_trait_solver() { - let mut fulfill_cx = FulfillmentCtxt::new(infcx); - fulfill_cx.register_predicate_obligations(infcx, obligations.iter().cloned()); - + let ocx = ObligationCtxt::new(infcx); + ocx.register_obligations(obligations.iter().cloned()); + let errors_and_ambiguities = ocx.select_all_or_error(); // We only care about the obligations that are *definitely* true errors. // Ambiguities do not prove the disjointness of two impls. - let errors = fulfill_cx.select_where_possible(infcx); + let (errors, ambiguities): (Vec<_>, Vec<_>) = + errors_and_ambiguities.into_iter().partition(|error| error.is_true_error()); + if errors.is_empty() { - let overflow_errors = fulfill_cx.collect_remaining_errors(infcx); - let overflowing_predicates = overflow_errors - .into_iter() - .filter(|e| match e.code { - FulfillmentErrorCode::Ambiguity { overflow: Some(true) } => true, - _ => false, - }) - .map(|e| infcx.resolve_vars_if_possible(e.obligation.predicate)) - .collect(); - IntersectionHasImpossibleObligations::No { overflowing_predicates } + IntersectionHasImpossibleObligations::No { + overflowing_predicates: ambiguities + .into_iter() + .filter(|error| { + matches!( + error.code, + FulfillmentErrorCode::Ambiguity { overflow: Some(true) } + ) + }) + .map(|e| infcx.resolve_vars_if_possible(e.obligation.predicate)) + .collect(), + } } else { IntersectionHasImpossibleObligations::Yes } @@ -589,13 +591,14 @@ fn try_prove_negated_where_clause<'tcx>( // Without this, we over-eagerly register coherence ambiguity candidates when // impl candidates do exist. let ref infcx = root_infcx.fork_with_intercrate(false); - let mut fulfill_cx = FulfillmentCtxt::new(infcx); - - fulfill_cx.register_predicate_obligation( - infcx, - Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, negative_predicate), - ); - if !fulfill_cx.select_all_or_error(infcx).is_empty() { + let ocx = ObligationCtxt::new(infcx); + ocx.register_obligation(Obligation::new( + infcx.tcx, + ObligationCause::dummy(), + param_env, + negative_predicate, + )); + if !ocx.select_all_or_error().is_empty() { return false; } @@ -603,8 +606,7 @@ fn try_prove_negated_where_clause<'tcx>( // if that wasn't implemented just for LocalDefId, and we'd need to do // the normalization ourselves since this is totally fallible... let outlives_env = OutlivesEnvironment::new(param_env); - - let errors = infcx.resolve_regions(&outlives_env); + let errors = ocx.resolve_regions(&outlives_env); if !errors.is_empty() { return false; } @@ -1129,22 +1131,17 @@ impl<'a, 'tcx> ProofTreeVisitor<'tcx> for AmbiguityCausesVisitor<'a, 'tcx> { result: Ok(_), } = cand.kind() { - let lazily_normalize_ty = |ty: Ty<'tcx>| { - let mut fulfill_cx = >::new(infcx); + let lazily_normalize_ty = |mut ty: Ty<'tcx>| { if matches!(ty.kind(), ty::Alias(..)) { - // FIXME(-Znext-solver=coherence): we currently don't - // normalize opaque types here, resulting in diverging behavior - // for TAITs. - match infcx - .at(&ObligationCause::dummy(), param_env) - .structurally_normalize(ty, &mut *fulfill_cx) - { - Ok(ty) => Ok(ty), - Err(_errs) => Err(()), + let ocx = ObligationCtxt::new(infcx); + ty = ocx + .structurally_normalize(&ObligationCause::dummy(), param_env, ty) + .map_err(|_| ())?; + if !ocx.select_where_possible().is_empty() { + return Err(()); } - } else { - Ok(ty) } + Ok(ty) }; infcx.probe(|_| { diff --git a/compiler/rustc_trait_selection/src/traits/engine.rs b/compiler/rustc_trait_selection/src/traits/engine.rs index 432d51ff8f90b..551c8e7702ef7 100644 --- a/compiler/rustc_trait_selection/src/traits/engine.rs +++ b/compiler/rustc_trait_selection/src/traits/engine.rs @@ -7,6 +7,7 @@ use crate::regions::InferCtxtRegionExt; use crate::solve::FulfillmentCtxt as NextFulfillmentCtxt; use crate::traits::error_reporting::TypeErrCtxtExt; use crate::traits::NormalizeExt; +use crate::traits::StructurallyNormalizeExt; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::ErrorGuaranteed; use rustc_hir::def_id::{DefId, LocalDefId}; @@ -15,6 +16,7 @@ use rustc_infer::infer::canonical::{ Canonical, CanonicalQueryResponse, CanonicalVarValues, QueryResponse, }; use rustc_infer::infer::outlives::env::OutlivesEnvironment; +use rustc_infer::infer::RegionResolutionError; use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, InferOk}; use rustc_infer::traits::{ FulfillmentError, Obligation, ObligationCause, PredicateObligation, TraitEngineExt as _, @@ -117,6 +119,17 @@ impl<'a, 'tcx> ObligationCtxt<'a, 'tcx> { self.infcx.at(cause, param_env).deeply_normalize(value, &mut **self.engine.borrow_mut()) } + pub fn structurally_normalize( + &self, + cause: &ObligationCause<'tcx>, + param_env: ty::ParamEnv<'tcx>, + value: Ty<'tcx>, + ) -> Result, Vec>> { + self.infcx + .at(cause, param_env) + .structurally_normalize(value, &mut **self.engine.borrow_mut()) + } + pub fn eq>( &self, cause: &ObligationCause<'tcx>, @@ -182,6 +195,18 @@ impl<'a, 'tcx> ObligationCtxt<'a, 'tcx> { self.engine.borrow_mut().select_all_or_error(self.infcx) } + /// Returns the not-yet-processed and stalled obligations from the + /// `ObligationCtxt`. + /// + /// Takes ownership of the context as doing operations such as + /// [`ObligationCtxt::eq`] afterwards will result in other obligations + /// getting ignored. You can make a new `ObligationCtxt` if this + /// needs to be done in a loop, for example. + #[must_use] + pub fn into_pending_obligations(self) -> Vec> { + self.engine.borrow().pending_obligations() + } + /// Resolves regions and reports errors. /// /// Takes ownership of the context as doing trait solving afterwards @@ -199,6 +224,18 @@ impl<'a, 'tcx> ObligationCtxt<'a, 'tcx> { } } + /// Resolves regions and reports errors. + /// + /// Takes ownership of the context as doing trait solving afterwards + /// will result in region constraints getting ignored. + #[must_use] + pub fn resolve_regions( + self, + outlives_env: &OutlivesEnvironment<'tcx>, + ) -> Vec> { + self.infcx.resolve_regions(outlives_env) + } + pub fn assumed_wf_types_and_report_errors( &self, param_env: ty::ParamEnv<'tcx>, diff --git a/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs b/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs index 5f2a894413529..87d240cf8ac75 100644 --- a/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs +++ b/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs @@ -1,9 +1,10 @@ -use rustc_infer::traits::{TraitEngine, TraitEngineExt}; use rustc_macros::extension; use crate::infer::canonical::OriginalQueryValues; use crate::infer::InferCtxt; -use crate::traits::{EvaluationResult, OverflowError, PredicateObligation, SelectionContext}; +use crate::traits::{ + EvaluationResult, ObligationCtxt, OverflowError, PredicateObligation, SelectionContext, +}; #[extension(pub trait InferCtxtExt<'tcx>)] impl<'tcx> InferCtxt<'tcx> { @@ -67,21 +68,22 @@ impl<'tcx> InferCtxt<'tcx> { if self.next_trait_solver() { self.probe(|snapshot| { - let mut fulfill_cx = crate::solve::FulfillmentCtxt::new(self); - fulfill_cx.register_predicate_obligation(self, obligation.clone()); - // True errors - // FIXME(-Znext-solver): Overflows are reported as ambig here, is that OK? - if !fulfill_cx.select_where_possible(self).is_empty() { - Ok(EvaluationResult::EvaluatedToErr) - } else if !fulfill_cx.select_all_or_error(self).is_empty() { - Ok(EvaluationResult::EvaluatedToAmbig) - } else if self.opaque_types_added_in_snapshot(snapshot) { - Ok(EvaluationResult::EvaluatedToOkModuloOpaqueTypes) + let ocx = ObligationCtxt::new(self); + ocx.register_obligation(obligation.clone()); + let mut result = EvaluationResult::EvaluatedToOk; + for error in ocx.select_all_or_error() { + if error.is_true_error() { + return Ok(EvaluationResult::EvaluatedToErr); + } else { + result = result.max(EvaluationResult::EvaluatedToAmbig); + } + } + if self.opaque_types_added_in_snapshot(snapshot) { + result = result.max(EvaluationResult::EvaluatedToOkModuloOpaqueTypes); } else if self.region_constraints_added_in_snapshot(snapshot) { - Ok(EvaluationResult::EvaluatedToOkModuloRegions) - } else { - Ok(EvaluationResult::EvaluatedToOk) + result = result.max(EvaluationResult::EvaluatedToOkModuloRegions); } + Ok(result) }) } else { assert!(!self.intercrate); diff --git a/compiler/rustc_traits/src/codegen.rs b/compiler/rustc_traits/src/codegen.rs index 51f38964415b0..b96b1b67a7407 100644 --- a/compiler/rustc_traits/src/codegen.rs +++ b/compiler/rustc_traits/src/codegen.rs @@ -4,14 +4,13 @@ // general routines. use rustc_infer::infer::TyCtxtInferExt; -use rustc_infer::traits::{FulfillmentErrorCode, TraitEngineExt as _}; +use rustc_infer::traits::FulfillmentErrorCode; use rustc_middle::bug; use rustc_middle::traits::CodegenObligationError; use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt; use rustc_trait_selection::traits::{ - ImplSource, Obligation, ObligationCause, SelectionContext, TraitEngine, TraitEngineExt, - Unimplemented, + ImplSource, Obligation, ObligationCause, ObligationCtxt, SelectionContext, Unimplemented, }; use tracing::debug; @@ -51,15 +50,15 @@ pub fn codegen_select_candidate<'tcx>( // Currently, we use a fulfillment context to completely resolve // all nested obligations. This is because they can inform the // inference of the impl's type parameters. - let mut fulfill_cx = >::new(&infcx); - let impl_source = selection.map(|predicate| { - fulfill_cx.register_predicate_obligation(&infcx, predicate); + let ocx = ObligationCtxt::new(&infcx); + let impl_source = selection.map(|obligation| { + ocx.register_obligation(obligation); }); // In principle, we only need to do this so long as `impl_source` // contains unbound type parameters. It could be a slight // optimization to stop iterating early. - let errors = fulfill_cx.select_all_or_error(&infcx); + let errors = ocx.select_all_or_error(); if !errors.is_empty() { // `rustc_monomorphize::collector` assumes there are no type errors. // Cycle errors are the only post-monomorphization errors possible; emit them now so diff --git a/config.example.toml b/config.example.toml index 5c1fac7672a9a..3b76952504f28 100644 --- a/config.example.toml +++ b/config.example.toml @@ -254,6 +254,10 @@ # executing the debuginfo test suite. #gdb = "gdb" +# The path to (or name of) the LLDB executable to use. This is only used for +# executing the debuginfo test suite. +#lldb = "lldb" + # The node.js executable to use. Note that this is only used for the emscripten # target when running tests, otherwise this can be omitted. #nodejs = "node" diff --git a/library/alloc/src/borrow.rs b/library/alloc/src/borrow.rs index b6b6246baa670..42f8a08a9e4ee 100644 --- a/library/alloc/src/borrow.rs +++ b/library/alloc/src/borrow.rs @@ -4,9 +4,9 @@ use core::cmp::Ordering; use core::hash::{Hash, Hasher}; -use core::ops::Deref; #[cfg(not(no_global_oom_handling))] use core::ops::{Add, AddAssign}; +use core::ops::{Deref, DerefPure}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::borrow::{Borrow, BorrowMut}; @@ -343,6 +343,9 @@ where } } +#[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl DerefPure for Cow<'_, B> where B::Owned: Borrow {} + #[stable(feature = "rust1", since = "1.0.0")] impl Eq for Cow<'_, B> where B: Eq + ToOwned {} diff --git a/library/alloc/src/ffi/c_str.rs b/library/alloc/src/ffi/c_str.rs index a4baf0e2533d4..19dd90eb81f4d 100644 --- a/library/alloc/src/ffi/c_str.rs +++ b/library/alloc/src/ffi/c_str.rs @@ -41,6 +41,7 @@ use crate::sync::Arc; /// or anything that implements [Into]<[Vec]<[u8]>> (for /// example, you can build a `CString` straight out of a [`String`] or /// a &[str], since both implement that trait). +/// You can create a `CString` from a literal with `CString::from(c"Text")`. /// /// The [`CString::new`] method will actually check that the provided &[[u8]] /// does not have 0 bytes in the middle, and return an error if it @@ -1091,27 +1092,22 @@ impl CStr { /// /// # Examples /// - /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8: + /// Calling `to_string_lossy` on a `CStr` containing valid UTF-8. The leading + /// `c` on the string literal denotes a `CStr`. /// /// ``` /// use std::borrow::Cow; - /// use std::ffi::CStr; /// - /// let cstr = CStr::from_bytes_with_nul(b"Hello World\0") - /// .expect("CStr::from_bytes_with_nul failed"); - /// assert_eq!(cstr.to_string_lossy(), Cow::Borrowed("Hello World")); + /// assert_eq!(c"Hello World".to_string_lossy(), Cow::Borrowed("Hello World")); /// ``` /// /// Calling `to_string_lossy` on a `CStr` containing invalid UTF-8: /// /// ``` /// use std::borrow::Cow; - /// use std::ffi::CStr; /// - /// let cstr = CStr::from_bytes_with_nul(b"Hello \xF0\x90\x80World\0") - /// .expect("CStr::from_bytes_with_nul failed"); /// assert_eq!( - /// cstr.to_string_lossy(), + /// c"Hello \xF0\x90\x80World".to_string_lossy(), /// Cow::Owned(String::from("Hello �World")) as Cow<'_, str> /// ); /// ``` diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index b93936869b3fd..91b83cfe011f2 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -165,6 +165,7 @@ // // Language features: // tidy-alphabetical-start +#![cfg_attr(bootstrap, feature(exclusive_range_pattern))] #![cfg_attr(not(test), feature(coroutine_trait))] #![cfg_attr(test, feature(panic_update_hook))] #![cfg_attr(test, feature(test))] @@ -179,7 +180,6 @@ #![feature(const_try)] #![feature(decl_macro)] #![feature(dropck_eyepatch)] -#![feature(exclusive_range_pattern)] #![feature(fundamental)] #![feature(hashmap_internals)] #![feature(lang_items)] diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 7c9f13e30ffb1..2a859ad55eed2 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -1382,7 +1382,7 @@ impl String { /// Shortens this `String` to the specified length. /// - /// If `new_len` is greater than the string's current length, this has no + /// If `new_len` is greater than or equal to the string's current length, this has no /// effect. /// /// Note that this method has no effect on the allocated capacity diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index ae0436bc5209e..4b491ffdafa70 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -239,7 +239,7 @@ use crate::cmp::Ordering; use crate::fmt::{self, Debug, Display}; use crate::marker::{PhantomData, Unsize}; use crate::mem::{self, size_of}; -use crate::ops::{CoerceUnsized, Deref, DerefMut, DispatchFromDyn}; +use crate::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn}; use crate::ptr::{self, NonNull}; mod lazy; @@ -1452,6 +1452,9 @@ impl Deref for Ref<'_, T> { } } +#[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl DerefPure for Ref<'_, T> {} + impl<'b, T: ?Sized> Ref<'b, T> { /// Copies a `Ref`. /// @@ -1844,6 +1847,9 @@ impl DerefMut for RefMut<'_, T> { } } +#[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl DerefPure for RefMut<'_, T> {} + #[unstable(feature = "coerce_unsized", issue = "18598")] impl<'b, T: ?Sized + Unsize, U: ?Sized> CoerceUnsized> for RefMut<'b, T> {} diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index aefb30463d33b..297f52e756bc6 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -23,28 +23,32 @@ use crate::str; /// /// This type represents a borrowed reference to a nul-terminated /// array of bytes. It can be constructed safely from a &[[u8]] -/// slice, or unsafely from a raw `*const c_char`. It can then be -/// converted to a Rust &[str] by performing UTF-8 validation, or -/// into an owned `CString`. +/// slice, or unsafely from a raw `*const c_char`. It can be expressed as a +/// literal in the form `c"Hello world"`. +/// +/// The `CStr` can then be converted to a Rust &[str] by performing +/// UTF-8 validation, or into an owned `CString`. /// /// `&CStr` is to `CString` as &[str] is to `String`: the former /// in each pair are borrowed references; the latter are owned /// strings. /// /// Note that this structure does **not** have a guaranteed layout (the `repr(transparent)` -/// notwithstanding) and is not recommended to be placed in the signatures of FFI functions. -/// Instead, safe wrappers of FFI functions may leverage the unsafe [`CStr::from_ptr`] constructor -/// to provide a safe interface to other consumers. +/// notwithstanding) and should not be placed in the signatures of FFI functions. +/// Instead, safe wrappers of FFI functions may leverage [`CStr::as_ptr`] and the unsafe +/// [`CStr::from_ptr`] constructor to provide a safe interface to other consumers. /// /// # Examples /// /// Inspecting a foreign C string: /// -/// ```ignore (extern-declaration) +/// ``` /// use std::ffi::CStr; /// use std::os::raw::c_char; /// +/// # /* Extern functions are awkward in doc comments - fake it instead /// extern "C" { fn my_string() -> *const c_char; } +/// # */ unsafe extern "C" fn my_string() -> *const c_char { c"hello".as_ptr() } /// /// unsafe { /// let slice = CStr::from_ptr(my_string()); @@ -54,12 +58,14 @@ use crate::str; /// /// Passing a Rust-originating C string: /// -/// ```ignore (extern-declaration) +/// ``` /// use std::ffi::{CString, CStr}; /// use std::os::raw::c_char; /// /// fn work(data: &CStr) { +/// # /* Extern functions are awkward in doc comments - fake it instead /// extern "C" { fn work_with(data: *const c_char); } +/// # */ unsafe extern "C" fn work_with(s: *const c_char) {} /// /// unsafe { work_with(data.as_ptr()) } /// } @@ -70,11 +76,13 @@ use crate::str; /// /// Converting a foreign C string into a Rust `String`: /// -/// ```ignore (extern-declaration) +/// ``` /// use std::ffi::CStr; /// use std::os::raw::c_char; /// +/// # /* Extern functions are awkward in doc comments - fake it instead /// extern "C" { fn my_string() -> *const c_char; } +/// # */ unsafe extern "C" fn my_string() -> *const c_char { c"hello".as_ptr() } /// /// fn my_string_safe() -> String { /// let cstr = unsafe { CStr::from_ptr(my_string()) }; @@ -241,16 +249,16 @@ impl CStr { /// /// # Examples /// - /// ```ignore (extern-declaration) + /// ``` /// use std::ffi::{c_char, CStr}; /// - /// extern "C" { - /// fn my_string() -> *const c_char; + /// fn my_string() -> *const c_char { + /// c"hello".as_ptr() /// } /// /// unsafe { /// let slice = CStr::from_ptr(my_string()); - /// println!("string returned: {}", slice.to_str().unwrap()); + /// assert_eq!(slice.to_str().unwrap(), "hello"); /// } /// ``` /// @@ -264,6 +272,8 @@ impl CStr { /// BYTES.as_ptr().cast() /// }; /// const HELLO: &CStr = unsafe { CStr::from_ptr(HELLO_PTR) }; + /// + /// assert_eq!(c"Hello, world!", HELLO); /// ``` /// /// [valid]: core::ptr#safety @@ -549,6 +559,7 @@ impl CStr { /// /// let empty_cstr = CStr::from_bytes_with_nul(b"\0")?; /// assert!(empty_cstr.is_empty()); + /// assert!(c"".is_empty()); /// # Ok(()) /// # } /// ``` diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 3318a8ffa5548..d1450bf12ce72 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -987,6 +987,7 @@ pub const unsafe fn assume(b: bool) { #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] #[rustc_nounwind] +#[cfg_attr(not(bootstrap), miri::intrinsic_fallback_checks_ub)] pub const fn likely(b: bool) -> bool { b } @@ -1006,6 +1007,7 @@ pub const fn likely(b: bool) -> bool { #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_intrinsic] #[rustc_nounwind] +#[cfg_attr(not(bootstrap), miri::intrinsic_fallback_checks_ub)] pub const fn unlikely(b: bool) -> bool { b } @@ -2469,6 +2471,7 @@ extern "rust-intrinsic" { #[rustc_nounwind] #[rustc_do_not_const_check] #[inline] +#[cfg_attr(not(bootstrap), miri::intrinsic_fallback_checks_ub)] pub const fn ptr_guaranteed_cmp(ptr: *const T, other: *const T) -> u8 { (ptr == other) as u8 } @@ -2578,8 +2581,7 @@ extern "rust-intrinsic" { /// /// Currently such an assertion would always succeed; until Rust decides /// otherwise, that principle should not be violated. -#[rustc_const_unstable(feature = "const_eval_select", issue = "none")] -#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_const_unstable(feature = "const_eval_select", issue = "124625")] #[rustc_intrinsic] #[rustc_intrinsic_must_be_overridden] pub const fn const_eval_select( @@ -2734,8 +2736,10 @@ pub const fn ub_checks() -> bool { #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_nounwind] #[rustc_intrinsic] +#[cfg_attr(not(bootstrap), miri::intrinsic_fallback_checks_ub)] pub const unsafe fn const_allocate(_size: usize, _align: usize) -> *mut u8 { - // const eval overrides this function, but runtime code should always just return null pointers. + // const eval overrides this function, but runtime code for now just returns null pointers. + // See . crate::ptr::null_mut() } @@ -2753,7 +2757,10 @@ pub const unsafe fn const_allocate(_size: usize, _align: usize) -> *mut u8 { #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_nounwind] #[rustc_intrinsic] -pub const unsafe fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) {} +#[cfg_attr(not(bootstrap), miri::intrinsic_fallback_checks_ub)] +pub const unsafe fn const_deallocate(_ptr: *mut u8, _size: usize, _align: usize) { + // Runtime NOP +} /// `ptr` must point to a vtable. /// The intrinsic will return the size stored in that vtable. diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 5dcef63895441..dcf68b36c7a2e 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -186,7 +186,6 @@ #![feature(ptr_metadata)] #![feature(set_ptr_value)] #![feature(slice_ptr_get)] -#![feature(split_at_checked)] #![feature(str_internals)] #![feature(str_split_inclusive_remainder)] #![feature(str_split_remainder)] diff --git a/library/core/src/mem/manually_drop.rs b/library/core/src/mem/manually_drop.rs index 98cff3493a7ea..955efb9b0f98d 100644 --- a/library/core/src/mem/manually_drop.rs +++ b/library/core/src/mem/manually_drop.rs @@ -1,4 +1,4 @@ -use crate::ops::{Deref, DerefMut}; +use crate::ops::{Deref, DerefMut, DerefPure}; use crate::ptr; /// A wrapper to inhibit compiler from automatically calling `T`’s destructor. @@ -161,3 +161,6 @@ impl DerefMut for ManuallyDrop { &mut self.value } } + +#[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl DerefPure for ManuallyDrop {} diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs index 9effa279b48e1..673144cb32827 100644 --- a/library/core/src/num/uint_macros.rs +++ b/library/core/src/num/uint_macros.rs @@ -77,7 +77,7 @@ macro_rules! uint_impl { without modifying the original"] #[inline(always)] pub const fn count_ones(self) -> u32 { - return intrinsics::ctpop(self as $ActualT); + return intrinsics::ctpop(self); } /// Returns the number of zeros in the binary representation of `self`. @@ -636,6 +636,31 @@ macro_rules! uint_impl { /// If you're just trying to avoid the panic in debug mode, then **do not** /// use this. Instead, you're looking for [`wrapping_sub`]. /// + /// If you find yourself writing code like this: + /// + /// ``` + /// # let foo = 30_u32; + /// # let bar = 20; + /// if foo >= bar { + /// // SAFETY: just checked it will not overflow + /// let diff = unsafe { foo.unchecked_sub(bar) }; + /// // ... use diff ... + /// } + /// ``` + /// + /// Consider changing it to + /// + /// ``` + /// # let foo = 30_u32; + /// # let bar = 20; + /// if let Some(diff) = foo.checked_sub(bar) { + /// // ... use diff ... + /// } + /// ``` + /// + /// As that does exactly the same thing -- including telling the optimizer + /// that the subtraction cannot overflow -- but avoids needing `unsafe`. + /// /// # Safety /// /// This results in undefined behavior when diff --git a/library/core/src/pin.rs b/library/core/src/pin.rs index f7463d170fd8e..d8fc3b7177f38 100644 --- a/library/core/src/pin.rs +++ b/library/core/src/pin.rs @@ -923,7 +923,7 @@ use crate::cmp; use crate::fmt; use crate::hash::{Hash, Hasher}; -use crate::ops::{CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Receiver}; +use crate::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, Receiver}; #[allow(unused_imports)] use crate::{ @@ -1684,6 +1684,9 @@ impl> DerefMut for Pin { } } +#[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl DerefPure for Pin {} + #[unstable(feature = "receiver_trait", issue = "none")] impl Receiver for Pin {} diff --git a/library/core/src/primitive_docs.rs b/library/core/src/primitive_docs.rs index 18a9503cfd2f5..d8597369b9bfd 100644 --- a/library/core/src/primitive_docs.rs +++ b/library/core/src/primitive_docs.rs @@ -1133,6 +1133,12 @@ impl (T,) {} /// bits. Please see [the documentation for [`prim@f32`] or [Wikipedia on /// half-precision values][wikipedia] for more information. /// +/// Note that most common platforms will not support `f16` in hardware without enabling extra target +/// features, with the notable exception of Apple Silicon (also known as M1, M2, etc.) processors. +/// Hardware support on x86-64 requires the avx512fp16 feature, while RISC-V requires Zhf. +/// Usually the fallback implementation will be to use `f32` hardware if it exists, and convert +/// between `f16` and `f32` when performing math. +/// /// *[See also the `std::f16::consts` module](crate::f16::consts).* /// /// [wikipedia]: https://en.wikipedia.org/wiki/Half-precision_floating-point_format @@ -1232,6 +1238,12 @@ mod prim_f64 {} /// as many bits as `f64`. Please see [the documentation for [`prim@f32`] or [Wikipedia on /// quad-precision values][wikipedia] for more information. /// +/// Note that no platforms have hardware support for `f128` without enabling target specific features, +/// as for all instruction set architectures `f128` is considered an optional feature. +/// Only Power ISA ("PowerPC") and RISCV specify it, and only certain microarchitectures +/// actually implement it. For x86-64 and AArch64, ISA support is not even specified, +/// so it will always be a software implementation significantly slower than `f64`. +/// /// *[See also the `std::f128::consts` module](crate::f128::consts).* /// /// [wikipedia]: https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index e9eeb3153307f..73bb256518d89 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -358,6 +358,54 @@ impl *const T { if self.is_null() { None } else { unsafe { Some(&*self) } } } + /// Returns a shared reference to the value behind the pointer. + /// If the pointer may be null or the value may be uninitialized, [`as_uninit_ref`] must be used instead. + /// If the pointer may be null, but the value is known to have been initialized, [`as_ref`] must be used instead. + /// + /// [`as_ref`]: #method.as_ref + /// [`as_uninit_ref`]: #method.as_uninit_ref + /// + /// # Safety + /// + /// When calling this method, you have to ensure that all of the following is true: + /// + /// * The pointer must be properly aligned. + /// + /// * It must be "dereferenceable" in the sense defined in [the module documentation]. + /// + /// * The pointer must point to an initialized instance of `T`. + /// + /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is + /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. + /// In particular, while this reference exists, the memory the pointer points to must + /// not get mutated (except inside `UnsafeCell`). + /// + /// This applies even if the result of this method is unused! + /// (The part about being initialized is not yet fully decided, but until + /// it is, the only safe approach is to ensure that they are indeed initialized.) + /// + /// [the module documentation]: crate::ptr#safety + /// + /// # Examples + /// + /// ``` + /// #![feature(ptr_as_ref_unchecked)] + /// let ptr: *const u8 = &10u8 as *const u8; + /// + /// unsafe { + /// println!("We got back the value: {}!", ptr.as_ref_unchecked()); + /// } + /// ``` + // FIXME: mention it in the docs for `as_ref` and `as_uninit_ref` once stabilized. + #[unstable(feature = "ptr_as_ref_unchecked", issue = "122034")] + #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")] + #[inline] + #[must_use] + pub const unsafe fn as_ref_unchecked<'a>(self) -> &'a T { + // SAFETY: the caller must guarantee that `self` is valid for a reference + unsafe { &*self } + } + /// Returns `None` if the pointer is null, or else returns a shared reference to /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require /// that the value has to be initialized. diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index c5a188dc7d4f2..b67930503e015 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -367,6 +367,57 @@ impl *mut T { if self.is_null() { None } else { unsafe { Some(&*self) } } } + /// Returns a shared reference to the value behind the pointer. + /// If the pointer may be null or the value may be uninitialized, [`as_uninit_ref`] must be used instead. + /// If the pointer may be null, but the value is known to have been initialized, [`as_ref`] must be used instead. + /// + /// For the mutable counterpart see [`as_mut_unchecked`]. + /// + /// [`as_ref`]: #method.as_ref + /// [`as_uninit_ref`]: #method.as_uninit_ref + /// [`as_mut_unchecked`]: #method.as_mut_unchecked + /// + /// # Safety + /// + /// When calling this method, you have to ensure that all of the following is true: + /// + /// * The pointer must be properly aligned. + /// + /// * It must be "dereferenceable" in the sense defined in [the module documentation]. + /// + /// * The pointer must point to an initialized instance of `T`. + /// + /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is + /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. + /// In particular, while this reference exists, the memory the pointer points to must + /// not get mutated (except inside `UnsafeCell`). + /// + /// This applies even if the result of this method is unused! + /// (The part about being initialized is not yet fully decided, but until + /// it is, the only safe approach is to ensure that they are indeed initialized.) + /// + /// [the module documentation]: crate::ptr#safety + /// + /// # Examples + /// + /// ``` + /// #![feature(ptr_as_ref_unchecked)] + /// let ptr: *mut u8 = &mut 10u8 as *mut u8; + /// + /// unsafe { + /// println!("We got back the value: {}!", ptr.as_ref_unchecked()); + /// } + /// ``` + // FIXME: mention it in the docs for `as_ref` and `as_uninit_ref` once stabilized. + #[unstable(feature = "ptr_as_ref_unchecked", issue = "122034")] + #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")] + #[inline] + #[must_use] + pub const unsafe fn as_ref_unchecked<'a>(self) -> &'a T { + // SAFETY: the caller must guarantee that `self` is valid for a reference + unsafe { &*self } + } + /// Returns `None` if the pointer is null, or else returns a shared reference to /// the value wrapped in `Some`. In contrast to [`as_ref`], this does not require /// that the value has to be initialized. @@ -688,6 +739,58 @@ impl *mut T { if self.is_null() { None } else { unsafe { Some(&mut *self) } } } + /// Returns a unique reference to the value behind the pointer. + /// If the pointer may be null or the value may be uninitialized, [`as_uninit_mut`] must be used instead. + /// If the pointer may be null, but the value is known to have been initialized, [`as_mut`] must be used instead. + /// + /// For the shared counterpart see [`as_ref_unchecked`]. + /// + /// [`as_mut`]: #method.as_mut + /// [`as_uninit_mut`]: #method.as_uninit_mut + /// [`as_ref_unchecked`]: #method.as_mut_unchecked + /// + /// # Safety + /// + /// When calling this method, you have to ensure that all of the following is true: + /// + /// * The pointer must be properly aligned. + /// + /// * It must be "dereferenceable" in the sense defined in [the module documentation]. + /// + /// * The pointer must point to an initialized instance of `T`. + /// + /// * You must enforce Rust's aliasing rules, since the returned lifetime `'a` is + /// arbitrarily chosen and does not necessarily reflect the actual lifetime of the data. + /// In particular, while this reference exists, the memory the pointer points to must + /// not get mutated (except inside `UnsafeCell`). + /// + /// This applies even if the result of this method is unused! + /// (The part about being initialized is not yet fully decided, but until + /// it is, the only safe approach is to ensure that they are indeed initialized.) + /// + /// [the module documentation]: crate::ptr#safety + /// + /// # Examples + /// + /// ``` + /// #![feature(ptr_as_ref_unchecked)] + /// let mut s = [1, 2, 3]; + /// let ptr: *mut u32 = s.as_mut_ptr(); + /// let first_value = unsafe { ptr.as_mut_unchecked() }; + /// *first_value = 4; + /// # assert_eq!(s, [4, 2, 3]); + /// println!("{s:?}"); // It'll print: "[4, 2, 3]". + /// ``` + // FIXME: mention it in the docs for `as_mut` and `as_uninit_mut` once stabilized. + #[unstable(feature = "ptr_as_ref_unchecked", issue = "122034")] + #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")] + #[inline] + #[must_use] + pub const unsafe fn as_mut_unchecked<'a>(self) -> &'a mut T { + // SAFETY: the caller must guarantee that `self` is valid for a reference + unsafe { &mut *self } + } + /// Returns `None` if the pointer is null, or else returns a unique reference to /// the value wrapped in `Some`. In contrast to [`as_mut`], this does not require /// that the value has to be initialized. diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index 9c523fd6295d7..ed7bcec89b9f9 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -9,7 +9,7 @@ use crate::cmp::Ordering::{self, Equal, Greater, Less}; use crate::fmt; use crate::hint; -use crate::intrinsics::exact_div; +use crate::intrinsics::{exact_div, unchecked_sub}; use crate::mem::{self, SizedTypeProperties}; use crate::num::NonZero; use crate::ops::{Bound, OneSidedRange, Range, RangeBounds}; @@ -1983,7 +1983,7 @@ impl [T] { ); // SAFETY: Caller has to check that `0 <= mid <= self.len()` - unsafe { (from_raw_parts(ptr, mid), from_raw_parts(ptr.add(mid), len - mid)) } + unsafe { (from_raw_parts(ptr, mid), from_raw_parts(ptr.add(mid), unchecked_sub(len, mid))) } } /// Divides one mutable slice into two at an index, without doing bounds checking. @@ -2035,7 +2035,12 @@ impl [T] { // // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference // is fine. - unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) } + unsafe { + ( + from_raw_parts_mut(ptr, mid), + from_raw_parts_mut(ptr.add(mid), unchecked_sub(len, mid)), + ) + } } /// Divides one slice into two at an index, returning `None` if the slice is @@ -2051,8 +2056,6 @@ impl [T] { /// # Examples /// /// ``` - /// #![feature(split_at_checked)] - /// /// let v = [1, -2, 3, -4, 5, -6]; /// /// { @@ -2075,8 +2078,8 @@ impl [T] { /// /// assert_eq!(None, v.split_at_checked(7)); /// ``` - #[unstable(feature = "split_at_checked", reason = "new API", issue = "119128")] - #[rustc_const_unstable(feature = "split_at_checked", issue = "119128")] + #[stable(feature = "split_at_checked", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_stable(feature = "split_at_checked", since = "CURRENT_RUSTC_VERSION")] #[inline] #[must_use] pub const fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])> { @@ -2102,8 +2105,6 @@ impl [T] { /// # Examples /// /// ``` - /// #![feature(split_at_checked)] - /// /// let mut v = [1, 0, 3, 0, 5, 6]; /// /// if let Some((left, right)) = v.split_at_mut_checked(2) { @@ -2116,8 +2117,8 @@ impl [T] { /// /// assert_eq!(None, v.split_at_mut_checked(7)); /// ``` - #[unstable(feature = "split_at_checked", reason = "new API", issue = "119128")] - #[rustc_const_unstable(feature = "split_at_checked", issue = "119128")] + #[stable(feature = "split_at_checked", since = "CURRENT_RUSTC_VERSION")] + #[rustc_const_unstable(feature = "const_slice_split_at_mut", issue = "101804")] #[inline] #[must_use] pub const fn split_at_mut_checked(&mut self, mid: usize) -> Option<(&mut [T], &mut [T])> { diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index adccbe02d46d4..b6f65907d3c30 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -721,8 +721,6 @@ impl str { /// # Examples /// /// ``` - /// #![feature(split_at_checked)] - /// /// let s = "Per Martin-Löf"; /// /// let (first, last) = s.split_at_checked(3).unwrap(); @@ -734,7 +732,7 @@ impl str { /// ``` #[inline] #[must_use] - #[unstable(feature = "split_at_checked", reason = "new API", issue = "119128")] + #[stable(feature = "split_at_checked", since = "CURRENT_RUSTC_VERSION")] pub fn split_at_checked(&self, mid: usize) -> Option<(&str, &str)> { // is_char_boundary checks that the index is in [0, .len()] if self.is_char_boundary(mid) { @@ -761,8 +759,6 @@ impl str { /// # Examples /// /// ``` - /// #![feature(split_at_checked)] - /// /// let mut s = "Per Martin-Löf".to_string(); /// if let Some((first, last)) = s.split_at_mut_checked(3) { /// first.make_ascii_uppercase(); @@ -776,7 +772,7 @@ impl str { /// ``` #[inline] #[must_use] - #[unstable(feature = "split_at_checked", reason = "new API", issue = "119128")] + #[stable(feature = "split_at_checked", since = "CURRENT_RUSTC_VERSION")] pub fn split_at_mut_checked(&mut self, mid: usize) -> Option<(&mut str, &mut str)> { // is_char_boundary checks that the index is in [0, .len()] if self.is_char_boundary(mid) { diff --git a/library/core/src/time.rs b/library/core/src/time.rs index 78494b866b108..72f6a3b773bb5 100644 --- a/library/core/src/time.rs +++ b/library/core/src/time.rs @@ -1437,10 +1437,10 @@ impl TryFromFloatSecsError { const fn description(&self) -> &'static str { match self.kind { TryFromFloatSecsErrorKind::Negative => { - "can not convert float seconds to Duration: value is negative" + "cannot convert float seconds to Duration: value is negative" } TryFromFloatSecsErrorKind::OverflowOrNan => { - "can not convert float seconds to Duration: value is either too big or NaN" + "cannot convert float seconds to Duration: value is either too big or NaN" } } } diff --git a/library/std/Cargo.toml b/library/std/Cargo.toml index cba9ff4485d05..52729ba1f8456 100644 --- a/library/std/Cargo.toml +++ b/library/std/Cargo.toml @@ -64,12 +64,10 @@ r-efi-alloc = { version = "1.0.0", features = ['rustc-dep-of-std'] } [features] backtrace = [ - "gimli-symbolize", 'addr2line/rustc-dep-of-std', 'object/rustc-dep-of-std', 'miniz_oxide/rustc-dep-of-std', ] -gimli-symbolize = [] panic-unwind = ["panic_unwind"] profiler = ["profiler_builtins"] diff --git a/library/std/src/alloc.rs b/library/std/src/alloc.rs index dc0e302a81088..b98fbbf762fa2 100644 --- a/library/std/src/alloc.rs +++ b/library/std/src/alloc.rs @@ -353,6 +353,12 @@ fn default_alloc_error_hook(layout: Layout) { if unsafe { __rust_alloc_error_handler_should_panic != 0 } { panic!("memory allocation of {} bytes failed", layout.size()); } else { + // This is the default path taken on OOM, and the only path taken on stable with std. + // Crucially, it does *not* call any user-defined code, and therefore users do not have to + // worry about allocation failure causing reentrancy issues. That makes it different from + // the default `__rdl_oom` defined in alloc (i.e., the default alloc error handler that is + // called when there is no `#[alloc_error_handler]`), which triggers a regular panic and + // thus can invoke a user-defined panic hook, executing arbitrary user-defined code. rtprintpanic!("memory allocation of {} bytes failed\n", layout.size()); } } diff --git a/library/std/src/f32.rs b/library/std/src/f32.rs index de9bde51f2a30..4fc82fec0adbc 100644 --- a/library/std/src/f32.rs +++ b/library/std/src/f32.rs @@ -371,9 +371,10 @@ impl f32 { /// It might have a different sequence of rounding operations than `powf`, /// so the results are not guaranteed to agree. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -393,9 +394,10 @@ impl f32 { /// Raises a number to a floating point power. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -444,9 +446,10 @@ impl f32 { /// Returns `e^(self)`, (the exponential function). /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -470,9 +473,10 @@ impl f32 { /// Returns `2^(self)`. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -494,9 +498,10 @@ impl f32 { /// Returns the natural logarithm of the number. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -524,9 +529,10 @@ impl f32 { /// `self.log2()` can produce more accurate results for base 2, and /// `self.log10()` can produce more accurate results for base 10. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -548,9 +554,10 @@ impl f32 { /// Returns the base 2 logarithm of the number. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -572,9 +579,10 @@ impl f32 { /// Returns the base 10 logarithm of the number. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -599,9 +607,10 @@ impl f32 { /// * If `self <= other`: `0.0` /// * Else: `self - other` /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `fdimf` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -637,9 +646,10 @@ impl f32 { /// Returns the cube root of a number. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `cbrtf` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -666,9 +676,10 @@ impl f32 { /// right-angle triangle with other sides having length `x.abs()` and /// `y.abs()`. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `hypotf` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -693,9 +704,10 @@ impl f32 { /// Computes the sine of a number (in radians). /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -716,9 +728,10 @@ impl f32 { /// Computes the cosine of a number (in radians). /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -739,9 +752,10 @@ impl f32 { /// Computes the tangent of a number (in radians). /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `tanf` from libc on Unix and /// Windows. Note that this might change in the future. /// @@ -765,9 +779,10 @@ impl f32 { /// the range [-pi/2, pi/2] or NaN if the number is outside the range /// [-1, 1]. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `asinf` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -794,9 +809,10 @@ impl f32 { /// the range [0, pi] or NaN if the number is outside the range /// [-1, 1]. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `acosf` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -822,9 +838,10 @@ impl f32 { /// Computes the arctangent of a number. Return value is in radians in the /// range [-pi/2, pi/2]; /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `atanf` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -854,9 +871,10 @@ impl f32 { /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]` /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)` /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `atan2f` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -890,9 +908,10 @@ impl f32 { /// Simultaneously computes the sine and cosine of the number, `x`. Returns /// `(sin(x), cos(x))`. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `(f32::sin(x), /// f32::cos(x))`. Note that this might change in the future. /// @@ -919,9 +938,10 @@ impl f32 { /// Returns `e^(self) - 1` in a way that is accurate even if the /// number is close to zero. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `expm1f` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -947,9 +967,10 @@ impl f32 { /// Returns `ln(1+n)` (natural logarithm) more accurately than if /// the operations were performed separately. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `log1pf` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -975,9 +996,10 @@ impl f32 { /// Hyperbolic sine function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `sinhf` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -1004,9 +1026,10 @@ impl f32 { /// Hyperbolic cosine function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `coshf` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -1033,9 +1056,10 @@ impl f32 { /// Hyperbolic tangent function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `tanhf` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -1062,9 +1086,10 @@ impl f32 { /// Inverse hyperbolic sine function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -1089,9 +1114,10 @@ impl f32 { /// Inverse hyperbolic cosine function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -1118,9 +1144,10 @@ impl f32 { /// Inverse hyperbolic tangent function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -1143,9 +1170,10 @@ impl f32 { /// Gamma function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `tgammaf` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -1171,9 +1199,10 @@ impl f32 { /// /// The integer part of the tuple indicates the sign of the gamma function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `lgamma_r` from libc on Unix /// and Windows. Note that this might change in the future. /// diff --git a/library/std/src/f64.rs b/library/std/src/f64.rs index 944186d602c8f..f8c66a3e71752 100644 --- a/library/std/src/f64.rs +++ b/library/std/src/f64.rs @@ -371,9 +371,10 @@ impl f64 { /// It might have a different sequence of rounding operations than `powf`, /// so the results are not guaranteed to agree. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -393,9 +394,10 @@ impl f64 { /// Raises a number to a floating point power. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -444,9 +446,10 @@ impl f64 { /// Returns `e^(self)`, (the exponential function). /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -470,9 +473,10 @@ impl f64 { /// Returns `2^(self)`. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -494,9 +498,10 @@ impl f64 { /// Returns the natural logarithm of the number. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -524,9 +529,10 @@ impl f64 { /// `self.log2()` can produce more accurate results for base 2, and /// `self.log10()` can produce more accurate results for base 10. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -548,9 +554,10 @@ impl f64 { /// Returns the base 2 logarithm of the number. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -572,9 +579,10 @@ impl f64 { /// Returns the base 10 logarithm of the number. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -599,9 +607,10 @@ impl f64 { /// * If `self <= other`: `0.0` /// * Else: `self - other` /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `fdim` from libc on Unix and /// Windows. Note that this might change in the future. /// @@ -637,9 +646,10 @@ impl f64 { /// Returns the cube root of a number. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `cbrt` from libc on Unix and /// Windows. Note that this might change in the future. /// @@ -666,9 +676,10 @@ impl f64 { /// right-angle triangle with other sides having length `x.abs()` and /// `y.abs()`. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `hypot` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -693,9 +704,10 @@ impl f64 { /// Computes the sine of a number (in radians). /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -716,9 +728,10 @@ impl f64 { /// Computes the cosine of a number (in radians). /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -739,9 +752,10 @@ impl f64 { /// Computes the tangent of a number (in radians). /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `tan` from libc on Unix and /// Windows. Note that this might change in the future. /// @@ -765,9 +779,10 @@ impl f64 { /// the range [-pi/2, pi/2] or NaN if the number is outside the range /// [-1, 1]. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `asin` from libc on Unix and /// Windows. Note that this might change in the future. /// @@ -794,9 +809,10 @@ impl f64 { /// the range [0, pi] or NaN if the number is outside the range /// [-1, 1]. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `acos` from libc on Unix and /// Windows. Note that this might change in the future. /// @@ -822,9 +838,10 @@ impl f64 { /// Computes the arctangent of a number. Return value is in radians in the /// range [-pi/2, pi/2]; /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `atan` from libc on Unix and /// Windows. Note that this might change in the future. /// @@ -854,9 +871,10 @@ impl f64 { /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]` /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)` /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `atan2` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -890,9 +908,10 @@ impl f64 { /// Simultaneously computes the sine and cosine of the number, `x`. Returns /// `(sin(x), cos(x))`. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `(f64::sin(x), /// f64::cos(x))`. Note that this might change in the future. /// @@ -919,9 +938,10 @@ impl f64 { /// Returns `e^(self) - 1` in a way that is accurate even if the /// number is close to zero. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `expm1` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -947,9 +967,10 @@ impl f64 { /// Returns `ln(1+n)` (natural logarithm) more accurately than if /// the operations were performed separately. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `log1p` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -975,9 +996,10 @@ impl f64 { /// Hyperbolic sine function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `sinh` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -1004,9 +1026,10 @@ impl f64 { /// Hyperbolic cosine function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `cosh` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -1033,9 +1056,10 @@ impl f64 { /// Hyperbolic tangent function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `tanh` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -1062,9 +1086,10 @@ impl f64 { /// Inverse hyperbolic sine function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -1089,9 +1114,10 @@ impl f64 { /// Inverse hyperbolic cosine function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -1118,9 +1144,10 @@ impl f64 { /// Inverse hyperbolic tangent function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// /// # Examples /// @@ -1143,9 +1170,10 @@ impl f64 { /// Gamma function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `tgamma` from libc on Unix /// and Windows. Note that this might change in the future. /// @@ -1171,9 +1199,10 @@ impl f64 { /// /// The integer part of the tuple indicates the sign of the gamma function. /// - /// # Platform-specific precision + /// # Unspecified precision /// - /// The precision of this function varies by platform and Rust version. + /// The precision of this function is non-deterministic. This means it varies by platform, Rust version, and + /// can even differ within the same execution from one invocation to the next. /// This function currently corresponds to the `lgamma_r` from libc on Unix /// and Windows. Note that this might change in the future. /// diff --git a/library/std/src/io/cursor.rs b/library/std/src/io/cursor.rs index f6680b211c7fa..37492e9efab74 100644 --- a/library/std/src/io/cursor.rs +++ b/library/std/src/io/cursor.rs @@ -364,6 +364,27 @@ where self.pos += n as u64; Ok(()) } + + fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { + let content = self.remaining_slice(); + let len = content.len(); + buf.try_reserve(len)?; + buf.extend_from_slice(content); + self.pos += len as u64; + + Ok(len) + } + + fn read_to_string(&mut self, buf: &mut String) -> io::Result { + let content = + crate::str::from_utf8(self.remaining_slice()).map_err(|_| io::Error::INVALID_UTF8)?; + let len = content.len(); + buf.try_reserve(len)?; + buf.push_str(content); + self.pos += len as u64; + + Ok(len) + } } #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/std/src/io/impls.rs b/library/std/src/io/impls.rs index dd7e0725176e8..46f04c7cd3957 100644 --- a/library/std/src/io/impls.rs +++ b/library/std/src/io/impls.rs @@ -329,8 +329,9 @@ impl Read for &[u8] { #[inline] fn read_to_string(&mut self, buf: &mut String) -> io::Result { let content = str::from_utf8(self).map_err(|_| io::Error::INVALID_UTF8)?; - buf.push_str(content); let len = self.len(); + buf.try_reserve(len)?; + buf.push_str(content); *self = &self[len..]; Ok(len) } @@ -473,14 +474,8 @@ impl Read for VecDeque { #[inline] fn read_to_string(&mut self, buf: &mut String) -> io::Result { - // We have to use a single contiguous slice because the `VecDequeue` might be split in the - // middle of an UTF-8 character. - let len = self.len(); - let content = self.make_contiguous(); - let string = str::from_utf8(content).map_err(|_| io::Error::INVALID_UTF8)?; - buf.push_str(string); - self.clear(); - Ok(len) + // SAFETY: We only append to the buffer + unsafe { io::append_to_string(buf, |buf| self.read_to_end(buf)) } } } diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs index 98973a43e1ded..af055152cbe7f 100644 --- a/library/std/src/io/mod.rs +++ b/library/std/src/io/mod.rs @@ -266,7 +266,7 @@ //! its file descriptors with no operations being performed by any other part of the program. //! //! Note that exclusive ownership of a file descriptor does *not* imply exclusive ownership of the -//! underlying kernel object that the file descriptor references (also called "file description" on +//! underlying kernel object that the file descriptor references (also called "open file description" on //! some operating systems). File descriptors basically work like [`Arc`]: when you receive an owned //! file descriptor, you cannot know whether there are any other file descriptors that reference the //! same kernel object. However, when you create a new kernel object, you know that you are holding @@ -384,7 +384,10 @@ where { let mut g = Guard { len: buf.len(), buf: buf.as_mut_vec() }; let ret = f(g.buf); - if str::from_utf8(&g.buf[g.len..]).is_err() { + + // SAFETY: the caller promises to only append data to `buf` + let appended = g.buf.get_unchecked(g.len..); + if str::from_utf8(appended).is_err() { ret.and_then(|_| Err(Error::INVALID_UTF8)) } else { g.len = g.buf.len(); diff --git a/library/std/src/os/unix/io/mod.rs b/library/std/src/os/unix/io/mod.rs index 827278f8b2605..6d4090ee31cfc 100644 --- a/library/std/src/os/unix/io/mod.rs +++ b/library/std/src/os/unix/io/mod.rs @@ -12,8 +12,8 @@ //! | Type | Analogous to | //! | ------------------ | ------------ | //! | [`RawFd`] | `*const _` | -//! | [`BorrowedFd<'a>`] | `&'a _` | -//! | [`OwnedFd`] | `Box<_>` | +//! | [`BorrowedFd<'a>`] | `&'a Arc<_>` | +//! | [`OwnedFd`] | `Arc<_>` | //! //! Like raw pointers, `RawFd` values are primitive values. And in new code, //! they should be considered unsafe to do I/O on (analogous to dereferencing @@ -23,22 +23,31 @@ //! either by adding `unsafe` to APIs that dereference `RawFd` values, or by //! using to `BorrowedFd` or `OwnedFd` instead. //! +//! The use of `Arc` for borrowed/owned file descriptors may be surprising. Unix file descriptors +//! are mere references to internal kernel objects called "open file descriptions", and the same +//! open file description can be referenced by multiple file descriptors (e.g. if `dup` is used). +//! State such as the offset within the file is shared among all file descriptors that refer to the +//! same open file description, and the kernel internally does reference-counting to only close the +//! underlying resource once all file descriptors referencing it are closed. That's why `Arc` (and +//! not `Box`) is the closest Rust analogy to an "owned" file descriptor. +//! //! Like references, `BorrowedFd` values are tied to a lifetime, to ensure //! that they don't outlive the resource they point to. These are safe to //! use. `BorrowedFd` values may be used in APIs which provide safe access to //! any system call except for: //! //! - `close`, because that would end the dynamic lifetime of the resource -//! without ending the lifetime of the file descriptor. +//! without ending the lifetime of the file descriptor. (Equivalently: +//! an `&Arc<_>` cannot be `drop`ed.) //! //! - `dup2`/`dup3`, in the second argument, because this argument is -//! closed and assigned a new resource, which may break the assumptions +//! closed and assigned a new resource, which may break the assumptions of //! other code using that file descriptor. //! -//! `BorrowedFd` values may be used in APIs which provide safe access to `dup` -//! system calls, so types implementing `AsFd` or `From` should not -//! assume they always have exclusive access to the underlying file -//! description. +//! `BorrowedFd` values may be used in APIs which provide safe access to `dup` system calls, so code +//! working with `OwnedFd` cannot assume to have exclusive access to the underlying open file +//! description. (Equivalently: `&Arc` may be used in APIs that provide safe access to `clone`, so +//! code working with an `Arc` cannot assume that the reference count is 1.) //! //! `BorrowedFd` values may also be used with `mmap`, since `mmap` uses the //! provided file descriptor in a manner similar to `dup` and does not require @@ -52,8 +61,10 @@ //! take full responsibility for ensuring that safe Rust code cannot evoke //! undefined behavior through it. //! -//! Like boxes, `OwnedFd` values conceptually own the resource they point to, -//! and free (close) it when they are dropped. +//! Like `Arc`, `OwnedFd` values conceptually own one reference to the resource they point to, +//! and decrement the reference count when they are dropped (by calling `close`). +//! When the reference count reaches 0, the underlying open file description will be freed +//! by the kernel. //! //! See the [`io` module docs][io-safety] for a general explanation of I/O safety. //! diff --git a/library/std/src/process.rs b/library/std/src/process.rs index 4a73a9be88bc1..d1848224251af 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -486,6 +486,10 @@ impl Read for ChildStderr { fn is_read_vectored(&self) -> bool { self.inner.is_read_vectored() } + + fn read_to_end(&mut self, buf: &mut Vec) -> io::Result { + self.inner.read_to_end(buf) + } } impl AsInner for ChildStderr { diff --git a/library/std/src/rt.rs b/library/std/src/rt.rs index 59e118f81ab1b..46f691d7b7504 100644 --- a/library/std/src/rt.rs +++ b/library/std/src/rt.rs @@ -74,7 +74,7 @@ macro_rules! rtunwrap { // // Since 2014, the Rust runtime on Unix has set the `SIGPIPE` handler to // `SIG_IGN`. Applications have good reasons to want a different behavior -// though, so there is a `#[unix_sigpipe = "..."]` attribute on `fn main()` that +// though, so there is a `-Zon-broken-pipe` compiler flag that // can be used to select how `SIGPIPE` shall be setup (if changed at all) before // `fn main()` is called. See // for more info. diff --git a/library/std/src/sys/pal/sgx/thread.rs b/library/std/src/sys/pal/sgx/thread.rs index e2df57b1a1f53..7d271e6d2b65d 100644 --- a/library/std/src/sys/pal/sgx/thread.rs +++ b/library/std/src/sys/pal/sgx/thread.rs @@ -67,7 +67,7 @@ mod task_queue { pub mod wait_notify { use crate::pin::Pin; use crate::sync::Arc; - use crate::sys_common::thread_parking::Parker; + use crate::sys::sync::Parker; pub struct Notifier(Arc); diff --git a/library/std/src/sys/pal/teeos/mod.rs b/library/std/src/sys/pal/teeos/mod.rs index c392a0ea264b6..6dd465a12ed49 100644 --- a/library/std/src/sys/pal/teeos/mod.rs +++ b/library/std/src/sys/pal/teeos/mod.rs @@ -30,8 +30,6 @@ pub mod thread; pub mod thread_local_dtor; #[path = "../unix/thread_local_key.rs"] pub mod thread_local_key; -#[path = "../unsupported/thread_parking.rs"] -pub mod thread_parking; #[allow(non_upper_case_globals)] #[path = "../unix/time.rs"] pub mod time; diff --git a/library/std/src/sys/pal/uefi/mod.rs b/library/std/src/sys/pal/uefi/mod.rs index 562b00c2c01a0..48b74df138439 100644 --- a/library/std/src/sys/pal/uefi/mod.rs +++ b/library/std/src/sys/pal/uefi/mod.rs @@ -30,8 +30,6 @@ pub mod stdio; pub mod thread; #[path = "../unsupported/thread_local_key.rs"] pub mod thread_local_key; -#[path = "../unsupported/thread_parking.rs"] -pub mod thread_parking; pub mod time; mod helpers; diff --git a/library/std/src/sys/pal/unix/fs.rs b/library/std/src/sys/pal/unix/fs.rs index d2006dfc12b55..32cdd13fbebda 100644 --- a/library/std/src/sys/pal/unix/fs.rs +++ b/library/std/src/sys/pal/unix/fs.rs @@ -860,6 +860,7 @@ impl Drop for Dir { target_os = "hurd", target_os = "espidf", target_os = "fuchsia", + target_os = "horizon", )))] { let fd = unsafe { libc::dirfd(self.0) }; diff --git a/library/std/src/sys/pal/unix/mod.rs b/library/std/src/sys/pal/unix/mod.rs index 01d7fb31d7d6c..1ac5729c02fd4 100644 --- a/library/std/src/sys/pal/unix/mod.rs +++ b/library/std/src/sys/pal/unix/mod.rs @@ -55,8 +55,8 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { // want! // // Hence, we set SIGPIPE to ignore when the program starts up in order - // to prevent this problem. Add `#[unix_sigpipe = "..."]` above `fn main()` to - // alter this behavior. + // to prevent this problem. Use `-Zon-broken-pipe=...` to alter this + // behavior. reset_sigpipe(sigpipe); stack_overflow::init(); @@ -190,7 +190,7 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { _ => unreachable!(), }; if sigpipe_attr_specified { - UNIX_SIGPIPE_ATTR_SPECIFIED.store(true, crate::sync::atomic::Ordering::Relaxed); + ON_BROKEN_PIPE_FLAG_USED.store(true, crate::sync::atomic::Ordering::Relaxed); } if let Some(handler) = handler { rtassert!(signal(libc::SIGPIPE, handler) != libc::SIG_ERR); @@ -210,7 +210,7 @@ pub unsafe fn init(argc: isize, argv: *const *const u8, sigpipe: u8) { target_os = "fuchsia", target_os = "horizon", )))] -static UNIX_SIGPIPE_ATTR_SPECIFIED: crate::sync::atomic::AtomicBool = +static ON_BROKEN_PIPE_FLAG_USED: crate::sync::atomic::AtomicBool = crate::sync::atomic::AtomicBool::new(false); #[cfg(not(any( @@ -219,8 +219,8 @@ static UNIX_SIGPIPE_ATTR_SPECIFIED: crate::sync::atomic::AtomicBool = target_os = "fuchsia", target_os = "horizon", )))] -pub(crate) fn unix_sigpipe_attr_specified() -> bool { - UNIX_SIGPIPE_ATTR_SPECIFIED.load(crate::sync::atomic::Ordering::Relaxed) +pub(crate) fn on_broken_pipe_flag_used() -> bool { + ON_BROKEN_PIPE_FLAG_USED.load(crate::sync::atomic::Ordering::Relaxed) } // SAFETY: must be called only once during runtime cleanup. diff --git a/library/std/src/sys/pal/unix/process/process_unix.rs b/library/std/src/sys/pal/unix/process/process_unix.rs index f2947161cd56d..e2fca8c7e63dc 100644 --- a/library/std/src/sys/pal/unix/process/process_unix.rs +++ b/library/std/src/sys/pal/unix/process/process_unix.rs @@ -353,11 +353,11 @@ impl Command { // Inherit the signal mask from the parent rather than resetting it (i.e. do not call // pthread_sigmask). - // If #[unix_sigpipe] is specified, don't reset SIGPIPE to SIG_DFL. - // If #[unix_sigpipe] is not specified, reset SIGPIPE to SIG_DFL for backward compatibility. + // If -Zon-broken-pipe is used, don't reset SIGPIPE to SIG_DFL. + // If -Zon-broken-pipe is not used, reset SIGPIPE to SIG_DFL for backward compatibility. // - // #[unix_sigpipe] is an opportunity to change the default here. - if !crate::sys::pal::unix_sigpipe_attr_specified() { + // -Zon-broken-pipe is an opportunity to change the default here. + if !crate::sys::pal::on_broken_pipe_flag_used() { #[cfg(target_os = "android")] // see issue #88585 { let mut action: libc::sigaction = mem::zeroed(); @@ -450,7 +450,7 @@ impl Command { ) -> io::Result> { use crate::mem::MaybeUninit; use crate::sys::weak::weak; - use crate::sys::{self, cvt_nz, unix_sigpipe_attr_specified}; + use crate::sys::{self, cvt_nz, on_broken_pipe_flag_used}; if self.get_gid().is_some() || self.get_uid().is_some() @@ -612,11 +612,11 @@ impl Command { // Inherit the signal mask from this process rather than resetting it (i.e. do not call // posix_spawnattr_setsigmask). - // If #[unix_sigpipe] is specified, don't reset SIGPIPE to SIG_DFL. - // If #[unix_sigpipe] is not specified, reset SIGPIPE to SIG_DFL for backward compatibility. + // If -Zon-broken-pipe is used, don't reset SIGPIPE to SIG_DFL. + // If -Zon-broken-pipe is not used, reset SIGPIPE to SIG_DFL for backward compatibility. // - // #[unix_sigpipe] is an opportunity to change the default here. - if !unix_sigpipe_attr_specified() { + // -Zon-broken-pipe is an opportunity to change the default here. + if !on_broken_pipe_flag_used() { let mut default_set = MaybeUninit::::uninit(); cvt(sigemptyset(default_set.as_mut_ptr()))?; cvt(sigaddset(default_set.as_mut_ptr(), libc::SIGPIPE))?; diff --git a/library/std/src/sys/pal/unix/thread_parking/netbsd.rs b/library/std/src/sys/pal/unix/thread_parking.rs similarity index 82% rename from library/std/src/sys/pal/unix/thread_parking/netbsd.rs rename to library/std/src/sys/pal/unix/thread_parking.rs index 5eeb37f87634b..1366410b71edc 100644 --- a/library/std/src/sys/pal/unix/thread_parking/netbsd.rs +++ b/library/std/src/sys/pal/unix/thread_parking.rs @@ -1,7 +1,11 @@ +// Only used on NetBSD. If other platforms start using id-based parking, use +// separate modules for each platform. +#![cfg(target_os = "netbsd")] + use crate::ffi::{c_int, c_void}; use crate::ptr; use crate::time::Duration; -use libc::{_lwp_self, clockid_t, lwpid_t, time_t, timespec, CLOCK_MONOTONIC}; +use libc::{_lwp_self, c_long, clockid_t, lwpid_t, time_t, timespec, CLOCK_MONOTONIC}; extern "C" { fn ___lwp_park60( @@ -34,7 +38,7 @@ pub fn park_timeout(dur: Duration, hint: usize) { // Saturate so that the operation will definitely time out // (even if it is after the heat death of the universe). tv_sec: dur.as_secs().try_into().ok().unwrap_or(time_t::MAX), - tv_nsec: dur.subsec_nanos().into(), + tv_nsec: dur.subsec_nanos() as c_long, }; // Timeout needs to be mutable since it is modified on NetBSD 9.0 and diff --git a/library/std/src/sys/pal/unix/thread_parking/mod.rs b/library/std/src/sys/pal/unix/thread_parking/mod.rs deleted file mode 100644 index c7fa39f07b640..0000000000000 --- a/library/std/src/sys/pal/unix/thread_parking/mod.rs +++ /dev/null @@ -1,24 +0,0 @@ -//! Thread parking on systems without futex support. - -#![cfg(not(any( - target_os = "linux", - target_os = "android", - all(target_os = "emscripten", target_feature = "atomics"), - target_os = "freebsd", - target_os = "openbsd", - target_os = "dragonfly", - target_os = "fuchsia", -)))] - -cfg_if::cfg_if! { - if #[cfg(all(target_vendor = "apple", not(miri)))] { - mod darwin; - pub use darwin::Parker; - } else if #[cfg(target_os = "netbsd")] { - mod netbsd; - pub use netbsd::{current, park, park_timeout, unpark, ThreadId}; - } else { - mod pthread; - pub use pthread::Parker; - } -} diff --git a/library/std/src/sys/pal/unsupported/mod.rs b/library/std/src/sys/pal/unsupported/mod.rs index be344fb7caedc..01f5cfd429753 100644 --- a/library/std/src/sys/pal/unsupported/mod.rs +++ b/library/std/src/sys/pal/unsupported/mod.rs @@ -14,7 +14,6 @@ pub mod thread; #[cfg(target_thread_local)] pub mod thread_local_dtor; pub mod thread_local_key; -pub mod thread_parking; pub mod time; mod common; diff --git a/library/std/src/sys/pal/wasi/mod.rs b/library/std/src/sys/pal/wasi/mod.rs index a78547261adf9..c1266619b36ab 100644 --- a/library/std/src/sys/pal/wasi/mod.rs +++ b/library/std/src/sys/pal/wasi/mod.rs @@ -39,13 +39,6 @@ pub mod thread_local_dtor; pub mod thread_local_key; pub mod time; -cfg_if::cfg_if! { - if #[cfg(not(target_feature = "atomics"))] { - #[path = "../unsupported/thread_parking.rs"] - pub mod thread_parking; - } -} - #[path = "../unsupported/common.rs"] #[deny(unsafe_op_in_unsafe_fn)] #[allow(unused)] diff --git a/library/std/src/sys/pal/wasip2/mod.rs b/library/std/src/sys/pal/wasip2/mod.rs index 94aa458d2f90e..6787ffb4bed8f 100644 --- a/library/std/src/sys/pal/wasip2/mod.rs +++ b/library/std/src/sys/pal/wasip2/mod.rs @@ -41,15 +41,6 @@ pub mod thread_local_key; #[path = "../wasi/time.rs"] pub mod time; -cfg_if::cfg_if! { - if #[cfg(target_feature = "atomics")] { - compile_error!("The wasm32-wasip2 target does not support atomics"); - } else { - #[path = "../unsupported/thread_parking.rs"] - pub mod thread_parking; - } -} - #[path = "../unsupported/common.rs"] #[deny(unsafe_op_in_unsafe_fn)] #[allow(unused)] diff --git a/library/std/src/sys/pal/wasm/mod.rs b/library/std/src/sys/pal/wasm/mod.rs index 5cbc3e4534101..75dd10826cc04 100644 --- a/library/std/src/sys/pal/wasm/mod.rs +++ b/library/std/src/sys/pal/wasm/mod.rs @@ -50,8 +50,6 @@ cfg_if::cfg_if! { } else { #[path = "../unsupported/thread.rs"] pub mod thread; - #[path = "../unsupported/thread_parking.rs"] - pub mod thread_parking; } } diff --git a/library/std/src/sys/pal/windows/mod.rs b/library/std/src/sys/pal/windows/mod.rs index ff41f6e77be7a..402a205977b07 100644 --- a/library/std/src/sys/pal/windows/mod.rs +++ b/library/std/src/sys/pal/windows/mod.rs @@ -33,7 +33,6 @@ pub mod stdio; pub mod thread; pub mod thread_local_dtor; pub mod thread_local_key; -pub mod thread_parking; pub mod time; cfg_if::cfg_if! { if #[cfg(not(target_vendor = "uwp"))] { diff --git a/library/std/src/sys/pal/xous/mod.rs b/library/std/src/sys/pal/xous/mod.rs index 7914a255aeaa1..68189bcc2e377 100644 --- a/library/std/src/sys/pal/xous/mod.rs +++ b/library/std/src/sys/pal/xous/mod.rs @@ -18,7 +18,6 @@ pub mod process; pub mod stdio; pub mod thread; pub mod thread_local_key; -pub mod thread_parking; pub mod time; #[path = "../unsupported/common.rs"] diff --git a/library/std/src/sys/pal/zkvm/mod.rs b/library/std/src/sys/pal/zkvm/mod.rs index 4f79f8c496169..0b22eabca6d82 100644 --- a/library/std/src/sys/pal/zkvm/mod.rs +++ b/library/std/src/sys/pal/zkvm/mod.rs @@ -32,9 +32,6 @@ pub mod time; #[path = "../unsupported/thread.rs"] pub mod thread; -#[path = "../unsupported/thread_parking.rs"] -pub mod thread_parking; - mod abi; use crate::io as std_io; diff --git a/library/std/src/sys/personality/dwarf/eh.rs b/library/std/src/sys/personality/dwarf/eh.rs index 3f3615ea3e0a4..ff88ef4e0e1d0 100644 --- a/library/std/src/sys/personality/dwarf/eh.rs +++ b/library/std/src/sys/personality/dwarf/eh.rs @@ -54,7 +54,14 @@ pub enum EHAction { Terminate, } -pub const USING_SJLJ_EXCEPTIONS: bool = cfg!(all(target_os = "ios", target_arch = "arm")); +/// 32-bit Apple ARM uses SjLj exceptions, except for watchOS. +/// +/// I.e. iOS and tvOS, as those are the only Apple OSes that used 32-bit ARM +/// devices. +/// +/// +pub const USING_SJLJ_EXCEPTIONS: bool = + cfg!(all(target_vendor = "apple", not(target_os = "watchos"), target_arch = "arm")); pub unsafe fn find_eh_action(lsda: *const u8, context: &EHContext<'_>) -> Result { if lsda.is_null() { diff --git a/library/std/src/sys/personality/gcc.rs b/library/std/src/sys/personality/gcc.rs index b0f744dd96605..0dc53550ca943 100644 --- a/library/std/src/sys/personality/gcc.rs +++ b/library/std/src/sys/personality/gcc.rs @@ -92,11 +92,12 @@ const UNWIND_DATA_REG: (i32, i32) = (4, 5); // a0, a1 // https://github.com/gcc-mirror/gcc/blob/trunk/libgcc/unwind-c.c cfg_if::cfg_if! { - if #[cfg(all(target_arch = "arm", not(target_os = "ios"), not(target_os = "tvos"), not(target_os = "watchos"), not(target_os = "visionos"), not(target_os = "netbsd")))] { + if #[cfg(all(not(all(target_vendor = "apple", not(target_os = "watchos"))), target_arch = "arm", not(target_os = "netbsd")))] { // ARM EHABI personality routine. // https://web.archive.org/web/20190728160938/https://infocenter.arm.com/help/topic/com.arm.doc.ihi0038b/IHI0038B_ehabi.pdf // - // iOS uses the default routine instead since it uses SjLj unwinding. + // Apple 32-bit ARM (but not watchOS) uses the default routine instead + // since it uses SjLj unwinding. #[lang = "eh_personality"] unsafe extern "C" fn rust_eh_personality( state: uw::_Unwind_State, diff --git a/library/std/src/sys/sync/mod.rs b/library/std/src/sys/sync/mod.rs index 623e6bccd5151..52fac5902a296 100644 --- a/library/std/src/sys/sync/mod.rs +++ b/library/std/src/sys/sync/mod.rs @@ -2,8 +2,10 @@ mod condvar; mod mutex; mod once; mod rwlock; +mod thread_parking; pub use condvar::Condvar; pub use mutex::Mutex; pub use once::{Once, OnceState}; pub use rwlock::RwLock; +pub use thread_parking::Parker; diff --git a/library/std/src/sys/pal/unix/thread_parking/darwin.rs b/library/std/src/sys/sync/thread_parking/darwin.rs similarity index 99% rename from library/std/src/sys/pal/unix/thread_parking/darwin.rs rename to library/std/src/sys/sync/thread_parking/darwin.rs index 8231f3cba2d3c..973c08f03171e 100644 --- a/library/std/src/sys/pal/unix/thread_parking/darwin.rs +++ b/library/std/src/sys/sync/thread_parking/darwin.rs @@ -10,6 +10,8 @@ //! provided by libdispatch, as the underlying Mach semaphore is only dubiously //! public. +#![allow(non_camel_case_types)] + use crate::pin::Pin; use crate::sync::atomic::{ AtomicI8, diff --git a/library/std/src/sys_common/thread_parking/futex.rs b/library/std/src/sys/sync/thread_parking/futex.rs similarity index 100% rename from library/std/src/sys_common/thread_parking/futex.rs rename to library/std/src/sys/sync/thread_parking/futex.rs diff --git a/library/std/src/sys_common/thread_parking/id.rs b/library/std/src/sys/sync/thread_parking/id.rs similarity index 100% rename from library/std/src/sys_common/thread_parking/id.rs rename to library/std/src/sys/sync/thread_parking/id.rs diff --git a/library/std/src/sys_common/thread_parking/mod.rs b/library/std/src/sys/sync/thread_parking/mod.rs similarity index 56% rename from library/std/src/sys_common/thread_parking/mod.rs rename to library/std/src/sys/sync/thread_parking/mod.rs index c4d3f9ea2f427..ed1a6437faaaf 100644 --- a/library/std/src/sys_common/thread_parking/mod.rs +++ b/library/std/src/sys/sync/thread_parking/mod.rs @@ -18,7 +18,20 @@ cfg_if::cfg_if! { ))] { mod id; pub use id::Parker; + } else if #[cfg(target_os = "windows")] { + mod windows; + pub use windows::Parker; + } else if #[cfg(all(target_vendor = "apple", not(miri)))] { + mod darwin; + pub use darwin::Parker; + } else if #[cfg(target_os = "xous")] { + mod xous; + pub use xous::Parker; + } else if #[cfg(target_family = "unix")] { + mod pthread; + pub use pthread::Parker; } else { - pub use crate::sys::thread_parking::Parker; + mod unsupported; + pub use unsupported::Parker; } } diff --git a/library/std/src/sys/pal/unix/thread_parking/pthread.rs b/library/std/src/sys/sync/thread_parking/pthread.rs similarity index 99% rename from library/std/src/sys/pal/unix/thread_parking/pthread.rs rename to library/std/src/sys/sync/thread_parking/pthread.rs index 8e295453d7675..fdac1096dbfc1 100644 --- a/library/std/src/sys/pal/unix/thread_parking/pthread.rs +++ b/library/std/src/sys/sync/thread_parking/pthread.rs @@ -134,7 +134,7 @@ impl Parker { // This implementation doesn't require `unsafe`, but other implementations // may assume this is only called by the thread that owns the Parker. // - // For memory ordering, see std/src/sys_common/thread_parking/futex.rs + // For memory ordering, see futex.rs pub unsafe fn park(self: Pin<&Self>) { // If we were previously notified then we consume this notification and // return quickly. diff --git a/library/std/src/sys/pal/unsupported/thread_parking.rs b/library/std/src/sys/sync/thread_parking/unsupported.rs similarity index 100% rename from library/std/src/sys/pal/unsupported/thread_parking.rs rename to library/std/src/sys/sync/thread_parking/unsupported.rs diff --git a/library/std/src/sys/pal/windows/thread_parking.rs b/library/std/src/sys/sync/thread_parking/windows.rs similarity index 100% rename from library/std/src/sys/pal/windows/thread_parking.rs rename to library/std/src/sys/sync/thread_parking/windows.rs diff --git a/library/std/src/sys/pal/xous/thread_parking.rs b/library/std/src/sys/sync/thread_parking/xous.rs similarity index 100% rename from library/std/src/sys/pal/xous/thread_parking.rs rename to library/std/src/sys/sync/thread_parking/xous.rs diff --git a/library/std/src/sys_common/mod.rs b/library/std/src/sys_common/mod.rs index cc21560fff505..3a38ba1100f01 100644 --- a/library/std/src/sys_common/mod.rs +++ b/library/std/src/sys_common/mod.rs @@ -26,7 +26,6 @@ pub mod io; pub mod lazy_box; pub mod process; pub mod thread_local_dtor; -pub mod thread_parking; pub mod wstr; pub mod wtf8; diff --git a/library/std/src/thread/mod.rs b/library/std/src/thread/mod.rs index 604eb05040b2d..78bc9af6c4d5c 100644 --- a/library/std/src/thread/mod.rs +++ b/library/std/src/thread/mod.rs @@ -174,8 +174,8 @@ use crate::ptr::addr_of_mut; use crate::str; use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sync::Arc; +use crate::sys::sync::Parker; use crate::sys::thread as imp; -use crate::sys_common::thread_parking::Parker; use crate::sys_common::{AsInner, IntoInner}; use crate::time::{Duration, Instant}; @@ -703,9 +703,14 @@ thread_local! { /// Sets the thread handle for the current thread. /// -/// Panics if the handle has been set already or when called from a TLS destructor. +/// Aborts if the handle has been set already to reduce code size. pub(crate) fn set_current(thread: Thread) { - CURRENT.with(|current| current.set(thread).unwrap()); + // Using `unwrap` here can add ~3kB to the binary size. We have complete + // control over where this is called, so just abort if there is a bug. + CURRENT.with(|current| match current.set(thread) { + Ok(()) => {} + Err(_) => rtabort!("thread::set_current should only be called once per thread"), + }); } /// Gets a handle to the thread that invokes it. diff --git a/library/test/src/lib.rs b/library/test/src/lib.rs index f3a26e2593831..7bd08a0605f83 100644 --- a/library/test/src/lib.rs +++ b/library/test/src/lib.rs @@ -589,7 +589,9 @@ pub fn run_test( // If the platform is single-threaded we're just going to run // the test synchronously, regardless of the concurrency // level. - let supports_threads = !cfg!(target_os = "emscripten") && !cfg!(target_family = "wasm"); + let supports_threads = !cfg!(target_os = "emscripten") + && !cfg!(target_family = "wasm") + && !cfg!(target_os = "zkvm"); if supports_threads { let cfg = thread::Builder::new().name(name.as_slice().to_owned()); let mut runtest = Arc::new(Mutex::new(Some(runtest))); diff --git a/library/unwind/src/libunwind.rs b/library/unwind/src/libunwind.rs index e34e73a351637..e5e28f32e4dbf 100644 --- a/library/unwind/src/libunwind.rs +++ b/library/unwind/src/libunwind.rs @@ -33,10 +33,10 @@ pub const unwinder_private_data_size: usize = 2; #[cfg(all(target_arch = "x86_64", target_os = "windows"))] pub const unwinder_private_data_size: usize = 6; -#[cfg(all(target_arch = "arm", not(any(target_os = "ios", target_os = "watchos"))))] +#[cfg(all(target_arch = "arm", not(all(target_vendor = "apple", not(target_os = "watchos")))))] pub const unwinder_private_data_size: usize = 20; -#[cfg(all(target_arch = "arm", any(target_os = "ios", target_os = "watchos")))] +#[cfg(all(target_arch = "arm", all(target_vendor = "apple", not(target_os = "watchos"))))] pub const unwinder_private_data_size: usize = 5; #[cfg(all(target_arch = "aarch64", target_pointer_width = "64", not(target_os = "windows")))] @@ -123,7 +123,7 @@ extern "C" { } cfg_if::cfg_if! { -if #[cfg(any(target_os = "ios", target_os = "tvos", target_os = "watchos", target_os = "visionos", target_os = "netbsd", not(target_arch = "arm")))] { +if #[cfg(any(all(target_vendor = "apple", not(target_os = "watchos")), target_os = "netbsd", not(target_arch = "arm")))] { // Not ARM EHABI #[repr(C)] #[derive(Copy, Clone, PartialEq)] @@ -258,8 +258,15 @@ if #[cfg(any(target_os = "ios", target_os = "tvos", target_os = "watchos", targe } // cfg_if! cfg_if::cfg_if! { -if #[cfg(not(all(target_os = "ios", target_arch = "arm")))] { - // Not 32-bit iOS +if #[cfg(all(target_vendor = "apple", not(target_os = "watchos"), target_arch = "arm"))] { + // 32-bit ARM Apple (except for watchOS) uses SjLj and does not provide + // _Unwind_Backtrace() + extern "C-unwind" { + pub fn _Unwind_SjLj_RaiseException(e: *mut _Unwind_Exception) -> _Unwind_Reason_Code; + } + + pub use _Unwind_SjLj_RaiseException as _Unwind_RaiseException; +} else { #[cfg_attr( all(feature = "llvm-libunwind", any(target_os = "fuchsia", target_os = "linux", target_os = "xous")), link(name = "unwind", kind = "static", modifiers = "-bundle") @@ -276,13 +283,6 @@ if #[cfg(not(all(target_os = "ios", target_arch = "arm")))] { trace_argument: *mut c_void) -> _Unwind_Reason_Code; } -} else { - // 32-bit iOS uses SjLj and does not provide _Unwind_Backtrace() - extern "C-unwind" { - pub fn _Unwind_SjLj_RaiseException(e: *mut _Unwind_Exception) -> _Unwind_Reason_Code; - } - - pub use _Unwind_SjLj_RaiseException as _Unwind_RaiseException; } } // cfg_if! diff --git a/rustfmt.toml b/rustfmt.toml index 0b0674af8b4a0..850d01ea7cb81 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -13,7 +13,13 @@ ignore = [ # tests for now are not formatted, as they are sometimes pretty-printing constrained # (and generally rustfmt can move around comments in UI-testing incompatible ways) - "/tests/", + "/tests/*", + + # but we still want to format rmake.rs files in tests/run-make/ so we need to do this + # dance to avoid the parent directory from being excluded + "!/tests/run-make/", + "/tests/run-make/*/*.rs", + "!/tests/run-make/*/rmake.rs", # do not format submodules # FIXME: sync submodule list with tidy/bootstrap/etc diff --git a/src/bootstrap/Cargo.toml b/src/bootstrap/Cargo.toml index c7a513d08908a..e9675e204523f 100644 --- a/src/bootstrap/Cargo.toml +++ b/src/bootstrap/Cargo.toml @@ -33,9 +33,9 @@ path = "src/bin/sccache-plus-cl.rs" test = false [dependencies] -# Most of the time updating these dependencies requires modifications -# to the bootstrap codebase; otherwise, some targets will fail. That's -# why these dependencies are explicitly pinned. +# Most of the time updating these dependencies requires modifications to the +# bootstrap codebase(e.g., https://github.com/rust-lang/rust/issues/124565); +# otherwise, some targets will fail. That's why these dependencies are explicitly pinned. cc = "=1.0.73" cmake = "=0.1.48" diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index 1d46a158f9ed2..48a6602e2df7e 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -1006,6 +1006,13 @@ pub fn rustc_cargo( cargo.rustdocflag("-Zcrate-attr=warn(rust_2018_idioms)"); + // If the rustc output is piped to e.g. `head -n1` we want the process to be + // killed, rather than having an error bubble up and cause a panic. + // FIXME: Synthetic #[cfg(bootstrap)]. Remove when the bootstrap compiler supports it. + if compiler.stage != 0 { + cargo.rustflag("-Zon-broken-pipe=kill"); + } + // We currently don't support cross-crate LTO in stage0. This also isn't hugely necessary // and may just be a time sink. if compiler.stage != 0 { diff --git a/src/bootstrap/src/core/build_steps/format.rs b/src/bootstrap/src/core/build_steps/format.rs index 9fc65a0a73a10..d9dc34c013700 100644 --- a/src/bootstrap/src/core/build_steps/format.rs +++ b/src/bootstrap/src/core/build_steps/format.rs @@ -115,7 +115,11 @@ pub fn format(build: &Builder<'_>, check: bool, paths: &[PathBuf]) { let rustfmt_config: RustfmtConfig = t!(toml::from_str(&rustfmt_config)); let mut fmt_override = ignore::overrides::OverrideBuilder::new(&build.src); for ignore in rustfmt_config.ignore { - fmt_override.add(&format!("!{ignore}")).expect(&ignore); + if let Some(ignore) = ignore.strip_prefix('!') { + fmt_override.add(ignore).expect(ignore); + } else { + fmt_override.add(&format!("!{ignore}")).expect(&ignore); + } } let git_available = match Command::new("git") .arg("--version") diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 9a585a39e1eeb..360bd3840d456 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -1892,15 +1892,16 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the .to_string() }) }; - let lldb_exe = "lldb"; - let lldb_version = Command::new(lldb_exe) + + let lldb_exe = builder.config.lldb.clone().unwrap_or_else(|| PathBuf::from("lldb")); + let lldb_version = Command::new(&lldb_exe) .arg("--version") .output() .map(|output| String::from_utf8_lossy(&output.stdout).to_string()) .ok(); if let Some(ref vers) = lldb_version { cmd.arg("--lldb-version").arg(vers); - let lldb_python_dir = run(Command::new(lldb_exe).arg("-P")).ok(); + let lldb_python_dir = run(Command::new(&lldb_exe).arg("-P")).ok(); if let Some(ref dir) = lldb_python_dir { cmd.arg("--lldb-python-dir").arg(dir); } diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index 2e2c5e9e6f8b2..21344a4224e40 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -471,7 +471,7 @@ impl Step for Rustdoc { features.push("jemalloc".to_string()); } - let cargo = prepare_tool_cargo( + let mut cargo = prepare_tool_cargo( builder, build_compiler, Mode::ToolRustc, @@ -482,6 +482,14 @@ impl Step for Rustdoc { features.as_slice(), ); + // If the rustdoc output is piped to e.g. `head -n1` we want the process + // to be killed, rather than having an error bubble up and cause a + // panic. + // FIXME: Synthetic #[cfg(bootstrap)]. Remove when the bootstrap compiler supports it. + if build_compiler.stage > 0 { + cargo.rustflag("-Zon-broken-pipe=kill"); + } + let _guard = builder.msg_tool( Kind::Build, Mode::ToolRustc, diff --git a/src/bootstrap/src/core/builder.rs b/src/bootstrap/src/core/builder.rs index 0ad6c959309a2..6c4b26ec2195f 100644 --- a/src/bootstrap/src/core/builder.rs +++ b/src/bootstrap/src/core/builder.rs @@ -2221,13 +2221,8 @@ impl<'a> Builder<'a> { out } - /// Return paths of all submodules managed by git. - /// If the current checkout is not managed by git, returns an empty slice. + /// Return paths of all submodules. pub fn get_all_submodules(&self) -> &[String] { - if !self.rust_info().is_managed_git_subrepository() { - return &[]; - } - static SUBMODULES_PATHS: OnceLock> = OnceLock::new(); let init_submodules_paths = |src: &PathBuf| { diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index ed45bc30362a5..0167c51fc7e2e 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -329,6 +329,7 @@ pub struct Config { pub nodejs: Option, pub npm: Option, pub gdb: Option, + pub lldb: Option, pub python: Option, pub reuse: Option, pub cargo_native_static: bool, @@ -834,6 +835,7 @@ define_config! { docs_minification: Option = "docs-minification", submodules: Option = "submodules", gdb: Option = "gdb", + lldb: Option = "lldb", nodejs: Option = "nodejs", npm: Option = "npm", python: Option = "python", @@ -1410,6 +1412,7 @@ impl Config { docs_minification, submodules, gdb, + lldb, nodejs, npm, python, @@ -1502,6 +1505,7 @@ impl Config { config.nodejs = nodejs.map(PathBuf::from); config.npm = npm.map(PathBuf::from); config.gdb = gdb.map(PathBuf::from); + config.lldb = lldb.map(PathBuf::from); config.python = python.map(PathBuf::from); config.reuse = reuse.map(PathBuf::from); config.submodules = submodules; diff --git a/src/bootstrap/src/core/sanity.rs b/src/bootstrap/src/core/sanity.rs index 6ccf29fb6cbef..0c069a540696f 100644 --- a/src/bootstrap/src/core/sanity.rs +++ b/src/bootstrap/src/core/sanity.rs @@ -26,6 +26,17 @@ pub struct Finder { path: OsString, } +// During sanity checks, we search for target names to determine if they exist in the compiler's built-in +// target list (`rustc --print target-list`). While a target name may be present in the stage2 compiler, +// it might not yet be included in stage0. In such cases, we handle the targets missing from stage0 in this list. +// +// Targets can be removed from this list once they are present in the stage0 compiler (usually by updating the beta compiler of the bootstrap). +const STAGE0_MISSING_TARGETS: &[&str] = &[ + // just a dummy comment so the list doesn't get onelined + "aarch64-apple-visionos", + "aarch64-apple-visionos-sim", +]; + impl Finder { pub fn new() -> Self { Self { cache: HashMap::new(), path: env::var_os("PATH").unwrap_or_default() } @@ -178,32 +189,40 @@ than building it. continue; } - // Check if there exists a built-in target in the list of supported targets. - let mut has_target = false; let target_str = target.to_string(); - let supported_target_list = - output(Command::new(&build.config.initial_rustc).args(["--print", "target-list"])); + // Ignore fake targets that are only used for unit tests in bootstrap. + if !["A", "B", "C"].contains(&target_str.as_str()) { + let mut has_target = false; + + let supported_target_list = + output(Command::new(&build.config.initial_rustc).args(["--print", "target-list"])); + + // Check if it's a built-in target. + has_target |= supported_target_list.contains(&target_str); + has_target |= STAGE0_MISSING_TARGETS.contains(&target_str.as_str()); - has_target |= supported_target_list.contains(&target_str); + if !has_target { + // This might also be a custom target, so check the target file that could have been specified by the user. + if let Some(custom_target_path) = env::var_os("RUST_TARGET_PATH") { + let mut target_filename = OsString::from(&target_str); + // Target filename ends with `.json`. + target_filename.push(".json"); - // If not, check for a valid file location that may have been specified - // by the user for the custom target. - if let Some(custom_target_path) = env::var_os("RUST_TARGET_PATH") { - let mut target_os_str = OsString::from(&target_str); - target_os_str.push(".json"); - // Recursively traverse through nested directories. - let walker = WalkDir::new(custom_target_path).into_iter(); - for entry in walker.filter_map(|e| e.ok()) { - has_target |= entry.file_name() == target_os_str; + // Recursively traverse through nested directories. + let walker = WalkDir::new(custom_target_path).into_iter(); + for entry in walker.filter_map(|e| e.ok()) { + has_target |= entry.file_name() == target_filename; + } + } } - } - if !has_target && !["A", "B", "C"].contains(&target_str.as_str()) { - panic!( - "No such target exists in the target list, + if !has_target { + panic!( + "No such target exists in the target list, specify a correct location of the JSON specification file for custom targets!" - ); + ); + } } if !build.config.dry_run() { diff --git a/src/bootstrap/src/utils/change_tracker.rs b/src/bootstrap/src/utils/change_tracker.rs index db3df598a0c63..c3a03693f714f 100644 --- a/src/bootstrap/src/utils/change_tracker.rs +++ b/src/bootstrap/src/utils/change_tracker.rs @@ -175,4 +175,9 @@ pub const CONFIG_CHANGE_HISTORY: &[ChangeInfo] = &[ severity: ChangeSeverity::Warning, summary: "The deprecated field `changelog-seen` has been removed. Using that field in `config.toml` from now on will result in breakage.", }, + ChangeInfo { + change_id: 124501, + severity: ChangeSeverity::Info, + summary: "New option `build.lldb` that will override the default lldb binary path used in debuginfo tests", + }, ]; diff --git a/src/ci/docker/run.sh b/src/ci/docker/run.sh index fcc507b572c27..22dcb808c743e 100755 --- a/src/ci/docker/run.sh +++ b/src/ci/docker/run.sh @@ -50,39 +50,35 @@ fi CACHE_DOMAIN="${CACHE_DOMAIN:-ci-caches.rust-lang.org}" if [ -f "$docker_dir/$image/Dockerfile" ]; then - if isCI; then - hash_key=/tmp/.docker-hash-key.txt - rm -f "${hash_key}" - echo $image >> $hash_key - - cat "$docker_dir/$image/Dockerfile" >> $hash_key - # Look for all source files involves in the COPY command - copied_files=/tmp/.docker-copied-files.txt - rm -f "$copied_files" - for i in $(sed -n -e '/^COPY --from=/! s/^COPY \(.*\) .*$/\1/p' \ - "$docker_dir/$image/Dockerfile"); do - # List the file names - find "$script_dir/$i" -type f >> $copied_files - done - # Sort the file names and cat the content into the hash key - sort $copied_files | xargs cat >> $hash_key - - # Include the architecture in the hash key, since our Linux CI does not - # only run in x86_64 machines. - uname -m >> $hash_key - - docker --version >> $hash_key - - # Include cache version. Can be used to manually bust the Docker cache. - echo "2" >> $hash_key - - echo "Image input" - cat $hash_key - - cksum=$(sha512sum $hash_key | \ - awk '{print $1}') - echo "Image input checksum ${cksum}" - fi + hash_key=/tmp/.docker-hash-key.txt + rm -f "${hash_key}" + echo $image >> $hash_key + + cat "$docker_dir/$image/Dockerfile" >> $hash_key + # Look for all source files involves in the COPY command + copied_files=/tmp/.docker-copied-files.txt + rm -f "$copied_files" + for i in $(sed -n -e '/^COPY --from=/! s/^COPY \(.*\) .*$/\1/p' \ + "$docker_dir/$image/Dockerfile"); do + # List the file names + find "$script_dir/$i" -type f >> $copied_files + done + # Sort the file names and cat the content into the hash key + sort $copied_files | xargs cat >> $hash_key + + # Include the architecture in the hash key, since our Linux CI does not + # only run in x86_64 machines. + uname -m >> $hash_key + + # Include cache version. Can be used to manually bust the Docker cache. + echo "2" >> $hash_key + + echo "Image input" + cat $hash_key + + cksum=$(sha512sum $hash_key | \ + awk '{print $1}') + echo "Image input checksum ${cksum}" dockerfile="$docker_dir/$image/Dockerfile" if [ -x /usr/bin/cygpath ]; then @@ -105,10 +101,18 @@ if [ -f "$docker_dir/$image/Dockerfile" ]; then # It seems that it cannot be the same as $IMAGE_TAG, otherwise it overwrites the cache CACHE_IMAGE_TAG=${REGISTRY}/${REGISTRY_USERNAME}/rust-ci-cache:${cksum} - # On non-CI jobs, we don't do any caching. + # On non-CI jobs, we try to download a pre-built image from the rust-lang-ci + # ghcr.io registry. If it is not possible, we fall back to building the image + # locally. if ! isCI; then - retry docker build --rm -t rust-ci -f "$dockerfile" "$context" + if docker pull "${IMAGE_TAG}"; then + echo "Downloaded Docker image from CI" + docker tag "${IMAGE_TAG}" rust-ci + else + echo "Building local Docker image" + retry docker build --rm -t rust-ci -f "$dockerfile" "$context" + fi # On PR CI jobs, we don't have permissions to write to the registry cache, # but we can still read from it. elif [[ "$PR_CI_JOB" == "1" ]]; diff --git a/src/ci/github-actions/jobs.yml b/src/ci/github-actions/jobs.yml index 1fabf889e38a1..20b1a55ffb879 100644 --- a/src/ci/github-actions/jobs.yml +++ b/src/ci/github-actions/jobs.yml @@ -25,10 +25,18 @@ runners: <<: *base-job - &job-windows-8c - os: windows-2019-8core-32gb + os: windows-2022-8core-32gb <<: *base-job - &job-windows-16c + os: windows-2022-16core-64gb + <<: *base-job + + - &job-windows-2019-8c + os: windows-2019-8core-32gb + <<: *base-job + + - &job-windows-2019-16c os: windows-2019-16core-64gb <<: *base-job @@ -36,6 +44,17 @@ runners: os: [ self-hosted, ARM64, linux ] envs: + env-x86_64-apple-tests: &env-x86_64-apple-tests + SCRIPT: ./x.py --stage 2 test --skip tests/ui --skip tests/rustdoc --skip tests/run-make-fulldeps + RUST_CONFIGURE_ARGS: --build=x86_64-apple-darwin --enable-sanitizers --enable-profiler --set rust.jemalloc + RUSTC_RETRY_LINKER_ON_SEGFAULT: 1 + MACOSX_DEPLOYMENT_TARGET: 10.12 + MACOSX_STD_DEPLOYMENT_TARGET: 10.12 + SELECT_XCODE: /Applications/Xcode_14.3.1.app + NO_LLVM_ASSERTIONS: 1 + NO_DEBUG_ASSERTIONS: 1 + NO_OVERFLOW_CHECKS: 1 + production: &production DEPLOY_BUCKET: rust-lang-ci2 @@ -272,16 +291,8 @@ auto: <<: *job-macos-xl - image: x86_64-apple-1 - env: &env-x86_64-apple-tests - SCRIPT: ./x.py --stage 2 test --skip tests/ui --skip tests/rustdoc --skip tests/run-make-fulldeps - RUST_CONFIGURE_ARGS: --build=x86_64-apple-darwin --enable-sanitizers --enable-profiler --set rust.jemalloc - RUSTC_RETRY_LINKER_ON_SEGFAULT: 1 - MACOSX_DEPLOYMENT_TARGET: 10.12 - MACOSX_STD_DEPLOYMENT_TARGET: 10.12 - SELECT_XCODE: /Applications/Xcode_14.3.1.app - NO_LLVM_ASSERTIONS: 1 - NO_DEBUG_ASSERTIONS: 1 - NO_OVERFLOW_CHECKS: 1 + env: + <<: *env-x86_64-apple-tests <<: *job-macos-xl - image: x86_64-apple-2 @@ -338,13 +349,13 @@ auto: env: RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-msvc --enable-profiler SCRIPT: make ci-msvc - <<: *job-windows-8c + <<: *job-windows-2019-8c - image: i686-msvc env: RUST_CONFIGURE_ARGS: --build=i686-pc-windows-msvc SCRIPT: make ci-msvc - <<: *job-windows-8c + <<: *job-windows-2019-8c - image: x86_64-msvc-ext env: @@ -352,7 +363,7 @@ auto: HOST_TARGET: x86_64-pc-windows-msvc RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-msvc --enable-lld --save-toolstates=/tmp/toolstate/toolstates.json DEPLOY_TOOLSTATES_JSON: toolstates-windows.json - <<: *job-windows-8c + <<: *job-windows-2019-8c # 32/64-bit MinGW builds. # @@ -403,7 +414,7 @@ auto: --set rust.codegen-units=1 SCRIPT: python x.py build --set rust.debug=true opt-dist && PGO_HOST=x86_64-pc-windows-msvc ./build/x86_64-pc-windows-msvc/stage0-tools-bin/opt-dist windows-ci -- python x.py dist bootstrap --include-default-paths DIST_REQUIRE_ALL_TOOLS: 1 - <<: *job-windows-8c + <<: *job-windows-2019-8c - image: dist-i686-msvc env: @@ -415,7 +426,7 @@ auto: --enable-profiler SCRIPT: python x.py dist bootstrap --include-default-paths DIST_REQUIRE_ALL_TOOLS: 1 - <<: *job-windows-8c + <<: *job-windows-2019-8c - image: dist-aarch64-msvc env: @@ -426,7 +437,7 @@ auto: --enable-profiler SCRIPT: python x.py dist bootstrap --include-default-paths DIST_REQUIRE_ALL_TOOLS: 1 - <<: *job-windows-8c + <<: *job-windows-2019-8c - image: dist-i686-mingw env: @@ -460,4 +471,4 @@ auto: env: RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-msvc --enable-extended --enable-profiler SCRIPT: python x.py dist bootstrap --include-default-paths - <<: *job-windows-8c + <<: *job-windows-2019-8c diff --git a/src/doc/rustc/src/check-cfg.md b/src/doc/rustc/src/check-cfg.md index 37708bda1f3dc..56198437ee97d 100644 --- a/src/doc/rustc/src/check-cfg.md +++ b/src/doc/rustc/src/check-cfg.md @@ -71,7 +71,7 @@ Those well known names and values follows the same stability as what they refer Well known names and values checking is always enabled as long as at least one `--check-cfg` argument is present. -As of `2024-04-06T`, the list of known names is as follows: +As of `2024-05-06T`, the list of known names is as follows: @@ -84,6 +84,7 @@ As of `2024-04-06T`, the list of known names is as follows: - `panic` - `proc_macro` - `relocation_model` + - `rustfmt` - `sanitize` - `sanitizer_cfi_generalize_pointers` - `sanitizer_cfi_normalize_integers` diff --git a/src/doc/rustc/src/platform-support/hermit.md b/src/doc/rustc/src/platform-support/hermit.md index 146079e36f44c..5aa787e53e1eb 100644 --- a/src/doc/rustc/src/platform-support/hermit.md +++ b/src/doc/rustc/src/platform-support/hermit.md @@ -4,7 +4,7 @@ The [Hermit] unikernel target allows compiling your applications into self-contained, specialized unikernel images that can be run in small virtual machines. -[Hermit]: https://github.com/hermitcore +[Hermit]: https://github.com/hermit-os Target triplets available so far: @@ -56,9 +56,9 @@ Rust does not yet ship pre-compiled artifacts for these targets. To compile for these targets, you will either need to build Rust with the targets enabled (see “Building the targets†above), or build your own copy of `core` by using `build-std` or similar. -Building Rust programs can be done by following the tutorial in our starter application [rusty-demo]. +As all Hermit programs are unikernels, building a Rust program also requires including the operating system code. A guide for doing so is provided in our starter [hermit-rs-template]. -[rusty-demo]: https://github.com/hermitcore/rusty-demo +[hermit-rs-template]: https://github.com/hermit-os/hermit-rs-template ## Testing @@ -67,8 +67,8 @@ These images can be chainloaded by Hermit's [loader] or hypervisor ([Uhyve]). QEMU can be used to boot Hermit binaries using the loader on any architecture. The targets do not support running the Rust test suite. -[loader]: https://github.com/hermitcore/rusty-loader -[Uhyve]: https://github.com/hermitcore/uhyve +[loader]: https://github.com/hermit-os/loader +[Uhyve]: https://github.com/hermit-os/uhyve ## Cross-compilation toolchains and C code diff --git a/src/doc/rustdoc/src/read-documentation/search.md b/src/doc/rustdoc/src/read-documentation/search.md index e2def14b357ea..e912ca0fe5b45 100644 --- a/src/doc/rustdoc/src/read-documentation/search.md +++ b/src/doc/rustdoc/src/read-documentation/search.md @@ -146,6 +146,7 @@ and number of matches. For example, a function with the signature `fn read_all(&mut self: impl Read) -> Result, Error>` will match these queries: +* `&mut Read -> Result, Error>` * `Read -> Result, Error>` * `Read -> Result` * `Read -> Result>` @@ -166,6 +167,10 @@ but you need to know which one you want. | Shorthand | Explicit names | | ---------------- | ------------------------------------------------- | +| `&` | `primitive:reference` | +| `&T` | `primitive:reference` | +| `&mut` | `primitive:reference` | +| `&mut T` | `primitive:reference` | | `[]` | `primitive:slice` and/or `primitive:array` | | `[T]` | `primitive:slice` and/or `primitive:array` | | `()` | `primitive:unit` and/or `primitive:tuple` | @@ -253,7 +258,8 @@ ident = *(ALPHA / DIGIT / "_") path = ident *(DOUBLE-COLON ident) [BANG] slice-like = OPEN-SQUARE-BRACKET [ nonempty-arg-list ] CLOSE-SQUARE-BRACKET tuple-like = OPEN-PAREN [ nonempty-arg-list ] CLOSE-PAREN -arg = [type-filter *WS COLON *WS] (path [generics] / slice-like / tuple-like) +borrow-ref = AMP *WS [MUT] *WS [arg] +arg = [type-filter *WS COLON *WS] (path [generics] / slice-like / tuple-like / borrow-ref) type-sep = COMMA/WS *(COMMA/WS) nonempty-arg-list = *(type-sep) arg *(type-sep arg) *(type-sep) [ return-args ] generic-arg-list = *(type-sep) arg [ EQUAL arg ] *(type-sep arg [ EQUAL arg ]) *(type-sep) @@ -310,6 +316,8 @@ COMMA = "," RETURN-ARROW = "->" EQUAL = "=" BANG = "!" +AMP = "&" +MUT = "mut" ALPHA = %x41-5A / %x61-7A ; A-Z / a-z DIGIT = %x30-39 diff --git a/src/doc/unstable-book/src/compiler-flags/on-broken-pipe.md b/src/doc/unstable-book/src/compiler-flags/on-broken-pipe.md new file mode 100644 index 0000000000000..bdc175f3b0a32 --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/on-broken-pipe.md @@ -0,0 +1,84 @@ +# `on-broken-pipe` + +-------------------- + +The tracking issue for this feature is: [#97889] + +Note: The ui for this feature was previously an attribute named `#[unix_sigpipe = "..."]`. + +[#97889]: https://github.com/rust-lang/rust/issues/97889 + +--- + + +## Overview + +The `-Zon-broken-pipe=...` compiler flag can be used to specify how libstd shall setup `SIGPIPE` on Unix platforms before invoking `fn main()`. This flag is ignored on non-Unix targets. The flag can be used with three different values or be omitted entirely. It affects `SIGPIPE` before `fn main()` and before children get `exec()`'ed: + +| Compiler flag | `SIGPIPE` before `fn main()` | `SIGPIPE` before child `exec()` | +|----------------------------|------------------------------|---------------------------------| +| not used | `SIG_IGN` | `SIG_DFL` | +| `-Zon-broken-pipe=kill` | `SIG_DFL` | not touched | +| `-Zon-broken-pipe=error` | `SIG_IGN` | not touched | +| `-Zon-broken-pipe=inherit` | not touched | not touched | + + +## `-Zon-broken-pipe` not used + +If `-Zon-broken-pipe` is not used, libstd will behave in the manner it has since 2014, before Rust 1.0. `SIGPIPE` will be set to `SIG_IGN` before `fn main()` and result in `EPIPE` errors which are converted to `std::io::ErrorKind::BrokenPipe`. + +When spawning child processes, `SIGPIPE` will be set to `SIG_DFL` before doing the underlying `exec()` syscall. + + +## `-Zon-broken-pipe=kill` + +Set the `SIGPIPE` handler to `SIG_DFL` before invoking `fn main()`. This will result in your program getting killed if it tries to write to a closed pipe. This is normally what you want if your program produces textual output. + +When spawning child processes, `SIGPIPE` will not be touched. This normally means child processes inherit `SIG_DFL` for `SIGPIPE`. + +### Example + +```rust,no_run +fn main() { + loop { + println!("hello world"); + } +} +``` + +```console +$ rustc -Zon-broken-pipe=kill main.rs +$ ./main | head -n1 +hello world +``` + +## `-Zon-broken-pipe=error` + +Set the `SIGPIPE` handler to `SIG_IGN` before invoking `fn main()`. This will result in `ErrorKind::BrokenPipe` errors if you program tries to write to a closed pipe. This is normally what you want if you for example write socket servers, socket clients, or pipe peers. + +When spawning child processes, `SIGPIPE` will not be touched. This normally means child processes inherit `SIG_IGN` for `SIGPIPE`. + +### Example + +```rust,no_run +fn main() { + loop { + println!("hello world"); + } +} +``` + +```console +$ rustc -Zon-broken-pipe=error main.rs +$ ./main | head -n1 +hello world +thread 'main' panicked at library/std/src/io/stdio.rs:1118:9: +failed printing to stdout: Broken pipe (os error 32) +note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace +``` + +## `-Zon-broken-pipe=inherit` + +Leave `SIGPIPE` untouched before entering `fn main()`. Unless the parent process has changed the default `SIGPIPE` handler from `SIG_DFL` to something else, this will behave the same as `-Zon-broken-pipe=kill`. + +When spawning child processes, `SIGPIPE` will not be touched. This normally means child processes inherit `SIG_DFL` for `SIGPIPE`. diff --git a/src/doc/unstable-book/src/language-features/exclusive-range-pattern.md b/src/doc/unstable-book/src/language-features/exclusive-range-pattern.md deleted file mode 100644 index d26512703f494..0000000000000 --- a/src/doc/unstable-book/src/language-features/exclusive-range-pattern.md +++ /dev/null @@ -1,26 +0,0 @@ -# `exclusive_range_pattern` - -The tracking issue for this feature is: [#37854]. - - -[#67264]: https://github.com/rust-lang/rust/issues/67264 -[#37854]: https://github.com/rust-lang/rust/issues/37854 ------ - -The `exclusive_range_pattern` feature allows non-inclusive range -patterns (`0..10`) to be used in appropriate pattern matching -contexts. It also can be combined with `#![feature(half_open_range_patterns]` -to be able to use RangeTo patterns (`..10`). - -It also enabled RangeFrom patterns but that has since been -stabilized. - -```rust -#![feature(exclusive_range_pattern)] - let x = 5; - match x { - 0..10 => println!("single digit"), - 10 => println!("ten isn't part of the above range"), - _ => println!("nor is everything else.") - } -``` diff --git a/src/doc/unstable-book/src/language-features/half-open-range-patterns-in-slices.md b/src/doc/unstable-book/src/language-features/half-open-range-patterns-in-slices.md index 56a1a97df1629..93e9bc32ff064 100644 --- a/src/doc/unstable-book/src/language-features/half-open-range-patterns-in-slices.md +++ b/src/doc/unstable-book/src/language-features/half-open-range-patterns-in-slices.md @@ -1,7 +1,7 @@ # `half_open_range_patterns_in_slices` The tracking issue for this feature is: [#67264] -It is part of the `exclusive_range_pattern` feature, +It is a future part of the `exclusive_range_pattern` feature, tracked at [#37854]. [#67264]: https://github.com/rust-lang/rust/issues/67264 @@ -12,7 +12,6 @@ This feature allow using top-level half-open range patterns in slices. ```rust #![feature(half_open_range_patterns_in_slices)] -#![feature(exclusive_range_pattern)] fn main() { let xs = [13, 1, 5, 2, 3, 1, 21, 8]; diff --git a/src/doc/unstable-book/src/language-features/result-ffi-guarantees.md b/src/doc/unstable-book/src/language-features/result-ffi-guarantees.md new file mode 100644 index 0000000000000..dc9c196524ed4 --- /dev/null +++ b/src/doc/unstable-book/src/language-features/result-ffi-guarantees.md @@ -0,0 +1,14 @@ +# `result_ffi_guarantees` + +The tracking issue for this feature is: [#110503] + +[#110503]: https://github.com/rust-lang/rust/issues/110503 + +------------------------ + +This feature adds the possibility of using `Result` in FFI if T's niche +value can be used to describe E or vise-versa. + +See [RFC 3391] for more information. + +[RFC 3391]: https://github.com/rust-lang/rfcs/blob/master/text/3391-result_ffi_guarantees.md diff --git a/src/doc/unstable-book/src/language-features/unix-sigpipe.md b/src/doc/unstable-book/src/language-features/unix-sigpipe.md deleted file mode 100644 index 7ed6a7de895c1..0000000000000 --- a/src/doc/unstable-book/src/language-features/unix-sigpipe.md +++ /dev/null @@ -1,62 +0,0 @@ -# `unix_sigpipe` - -The tracking issue for this feature is: [#97889] - -[#97889]: https://github.com/rust-lang/rust/issues/97889 - ---- - -The `#[unix_sigpipe = "..."]` attribute on `fn main()` can be used to specify how libstd shall setup `SIGPIPE` on Unix platforms before invoking `fn main()`. This attribute is ignored on non-Unix targets. There are three variants: -* `#[unix_sigpipe = "inherit"]` -* `#[unix_sigpipe = "sig_dfl"]` -* `#[unix_sigpipe = "sig_ign"]` - -## `#[unix_sigpipe = "inherit"]` - -Leave `SIGPIPE` untouched before entering `fn main()`. Unless the parent process has changed the default `SIGPIPE` handler from `SIG_DFL` to something else, this will behave the same as `#[unix_sigpipe = "sig_dfl"]`. - -## `#[unix_sigpipe = "sig_dfl"]` - -Set the `SIGPIPE` handler to `SIG_DFL`. This will result in your program getting killed if it tries to write to a closed pipe. This is normally what you want if your program produces textual output. - -### Example - -```rust,no_run -#![feature(unix_sigpipe)] -#[unix_sigpipe = "sig_dfl"] -fn main() { loop { println!("hello world"); } } -``` - -```bash -% ./main | head -n 1 -hello world -``` - -## `#[unix_sigpipe = "sig_ign"]` - -Set the `SIGPIPE` handler to `SIG_IGN` before invoking `fn main()`. This will result in `ErrorKind::BrokenPipe` errors if you program tries to write to a closed pipe. This is normally what you want if you for example write socket servers, socket clients, or pipe peers. - -This is what libstd has done by default since 2014. (However, see the note on child processes below.) - -### Example - -```rust,no_run -#![feature(unix_sigpipe)] -#[unix_sigpipe = "sig_ign"] -fn main() { loop { println!("hello world"); } } -``` - -```bash -% ./main | head -n 1 -hello world -thread 'main' panicked at 'failed printing to stdout: Broken pipe (os error 32)', library/std/src/io/stdio.rs:1016:9 -note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace -``` - -### Note on child processes - -When spawning child processes, the legacy Rust behavior if `#[unix_sigpipe]` is not specified is to -reset `SIGPIPE` to `SIG_DFL`. - -If `#[unix_sigpipe = "..."]` is specified, no matter what its value is, the signal disposition of -`SIGPIPE` is no longer reset. This means that the child inherits the parent's `SIGPIPE` behavior. diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index fc4f48262e5dc..f437c7d319d75 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -281,7 +281,10 @@ fn clean_lifetime<'tcx>(lifetime: &hir::Lifetime, cx: &mut DocContext<'tcx>) -> Lifetime(lifetime.ident.name) } -pub(crate) fn clean_const<'tcx>(constant: &hir::ConstArg, cx: &mut DocContext<'tcx>) -> Constant { +pub(crate) fn clean_const<'tcx>( + constant: &hir::ConstArg<'_>, + cx: &mut DocContext<'tcx>, +) -> Constant { let def_id = cx.tcx.hir().body_owner_def_id(constant.value.body).to_def_id(); Constant { type_: Box::new(clean_middle_ty( @@ -2450,7 +2453,7 @@ pub(crate) fn clean_variant_def_with_args<'tcx>( fn clean_variant_data<'tcx>( variant: &hir::VariantData<'tcx>, - disr_expr: &Option, + disr_expr: &Option<&hir::AnonConst>, cx: &mut DocContext<'tcx>, ) -> Variant { let discriminant = disr_expr diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 09a53affb14c0..075d94bd33707 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -182,6 +182,7 @@ pub(crate) enum RenderTypeId { Primitive(clean::PrimitiveType), AssociatedType(Symbol), Index(isize), + Mut, } impl RenderTypeId { diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index 6d2bb31ee133e..e635c1e611de7 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -7,7 +7,7 @@ use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_middle::ty::TyCtxt; use rustc_span::def_id::DefId; use rustc_span::sym; -use rustc_span::symbol::Symbol; +use rustc_span::symbol::{kw, Symbol}; use serde::ser::{Serialize, SerializeSeq, SerializeStruct, Serializer}; use thin_vec::ThinVec; @@ -163,6 +163,15 @@ pub(crate) fn build_index<'tcx>( ) -> Option { let Cache { ref paths, ref external_paths, ref exact_paths, .. } = *cache; match id { + RenderTypeId::Mut => Some(insert_into_map( + primitives, + kw::Mut, + lastpathid, + crate_paths, + ItemType::Keyword, + &[kw::Mut], + None, + )), RenderTypeId::DefId(defid) => { if let Some(&(ref fqp, item_type)) = paths.get(&defid).or_else(|| external_paths.get(&defid)) @@ -765,9 +774,8 @@ fn get_index_type_id( bounds.get(0).map(|b| RenderTypeId::DefId(b.trait_.def_id())) } clean::Primitive(p) => Some(RenderTypeId::Primitive(p)), - clean::BorrowedRef { ref type_, .. } | clean::RawPointer(_, ref type_) => { - get_index_type_id(type_, rgen) - } + clean::BorrowedRef { .. } => Some(RenderTypeId::Primitive(clean::PrimitiveType::Reference)), + clean::RawPointer(_, ref type_) => get_index_type_id(type_, rgen), // The type parameters are converted to generics in `simplify_fn_type` clean::Slice(_) => Some(RenderTypeId::Primitive(clean::PrimitiveType::Slice)), clean::Array(_, _) => Some(RenderTypeId::Primitive(clean::PrimitiveType::Array)), @@ -833,28 +841,14 @@ fn simplify_fn_type<'tcx, 'a>( } // First, check if it's "Self". - let mut is_self = false; - let mut arg = if let Some(self_) = self_ { - match &*arg { - Type::BorrowedRef { type_, .. } if type_.is_self_type() => { - is_self = true; - self_ - } - type_ if type_.is_self_type() => { - is_self = true; - self_ - } - arg => arg, - } + let (is_self, arg) = if let Some(self_) = self_ + && arg.is_self_type() + { + (true, self_) } else { - arg + (false, arg) }; - // strip references from the argument type - while let Type::BorrowedRef { type_, .. } = &*arg { - arg = &*type_; - } - // If this argument is a type parameter and not a trait bound or a type, we need to look // for its bounds. if let Type::Generic(arg_s) = *arg { @@ -1027,6 +1021,27 @@ fn simplify_fn_type<'tcx, 'a>( bindings: Some(ty_bindings), generics: Some(ty_generics), }); + } else if let Type::BorrowedRef { lifetime: _, mutability, ref type_ } = *arg { + let mut ty_generics = Vec::new(); + if mutability.is_mut() { + ty_generics.push(RenderType { + id: Some(RenderTypeId::Mut), + generics: None, + bindings: None, + }); + } + simplify_fn_type( + self_, + generics, + &type_, + tcx, + recurse + 1, + &mut ty_generics, + rgen, + is_return, + cache, + ); + res.push(get_index_type(arg, ty_generics, rgen)); } else { // This is not a type parameter. So for example if we have `T, U: Option`, and we're // looking at `Option`, we enter this "else" condition, otherwise if it's `T`, we don't. diff --git a/src/librustdoc/html/static/css/noscript.css b/src/librustdoc/html/static/css/noscript.css index ccb97d7df4c3b..6e10cf21537bc 100644 --- a/src/librustdoc/html/static/css/noscript.css +++ b/src/librustdoc/html/static/css/noscript.css @@ -85,6 +85,7 @@ nav.sub { --search-tab-button-not-selected-background: #e6e6e6; --search-tab-button-selected-border-top-color: #0089ff; --search-tab-button-selected-background: #fff; + --settings-menu-filter: none; --stab-background-color: #fff5d6; --stab-code-color: #000; --code-highlight-kw-color: #8959a8; diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css index 80a4ea0424a26..4c0ba75d26129 100644 --- a/src/librustdoc/html/static/css/rustdoc.css +++ b/src/librustdoc/html/static/css/rustdoc.css @@ -1625,6 +1625,7 @@ a.tooltip:hover::after { ,5.1715698,7.5,6 S6.8284302,7.5,6,7.5z" fill="black"/>'); width: 22px; height: 22px; + filter: var(--settings-menu-filter); } #sidebar-button > a:before { @@ -2419,6 +2420,7 @@ by default. --search-tab-button-not-selected-background: #e6e6e6; --search-tab-button-selected-border-top-color: #0089ff; --search-tab-button-selected-background: #fff; + --settings-menu-filter: none; --stab-background-color: #fff5d6; --stab-code-color: #000; --code-highlight-kw-color: #8959a8; @@ -2524,6 +2526,7 @@ by default. --search-tab-button-not-selected-background: #252525; --search-tab-button-selected-border-top-color: #0089ff; --search-tab-button-selected-background: #353535; + --settings-menu-filter: none; --stab-background-color: #314559; --stab-code-color: #e6e1cf; --code-highlight-kw-color: #ab8ac1; @@ -2636,6 +2639,7 @@ Original by Dempfi (https://github.com/dempfi/ayu) --search-tab-button-not-selected-background: transparent !important; --search-tab-button-selected-border-top-color: none; --search-tab-button-selected-background: #141920 !important; + --settings-menu-filter: invert(100%); --stab-background-color: #314559; --stab-code-color: #e6e1cf; --code-highlight-kw-color: #ff7733; diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index 41a9897de6dfb..76a6fc9008eaa 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -786,6 +786,37 @@ function initSearch(rawSearchIndex) { } elems.push(makePrimitiveElement(name, { bindingName, generics })); } + } else if (parserState.userQuery[parserState.pos] === "&") { + if (parserState.typeFilter !== null && parserState.typeFilter !== "primitive") { + throw [ + "Invalid search type: primitive ", + "&", + " and ", + parserState.typeFilter, + " both specified", + ]; + } + parserState.typeFilter = null; + parserState.pos += 1; + let c = parserState.userQuery[parserState.pos]; + while (c === " " && parserState.pos < parserState.length) { + parserState.pos += 1; + c = parserState.userQuery[parserState.pos]; + } + const generics = []; + if (parserState.userQuery.slice(parserState.pos, parserState.pos + 3) === "mut") { + generics.push(makePrimitiveElement("mut", { typeFilter: "keyword"})); + parserState.pos += 3; + c = parserState.userQuery[parserState.pos]; + } + while (c === " " && parserState.pos < parserState.length) { + parserState.pos += 1; + c = parserState.userQuery[parserState.pos]; + } + if (!isEndCharacter(c) && parserState.pos < parserState.length) { + getFilteredNextElem(query, parserState, generics, isInGenerics); + } + elems.push(makePrimitiveElement("reference", { generics })); } else { const isStringElem = parserState.userQuery[start] === "\""; // We handle the strings on their own mostly to make code easier to follow. diff --git a/src/tools/cargo b/src/tools/cargo index 6087566b3fa73..05364cb2f61a2 160000 --- a/src/tools/cargo +++ b/src/tools/cargo @@ -1 +1 @@ -Subproject commit 6087566b3fa73bfda29702632493e938b12d19e5 +Subproject commit 05364cb2f61a2c2b091e061c1f42b207dfb5f81f diff --git a/src/tools/clippy/clippy_utils/src/hir_utils.rs b/src/tools/clippy/clippy_utils/src/hir_utils.rs index 07c443acb05f7..c921168df290b 100644 --- a/src/tools/clippy/clippy_utils/src/hir_utils.rs +++ b/src/tools/clippy/clippy_utils/src/hir_utils.rs @@ -224,7 +224,7 @@ impl HirEqInterExpr<'_, '_, '_> { }) } - pub fn eq_array_length(&mut self, left: ArrayLen, right: ArrayLen) -> bool { + pub fn eq_array_length(&mut self, left: ArrayLen<'_>, right: ArrayLen<'_>) -> bool { match (left, right) { (ArrayLen::Infer(..), ArrayLen::Infer(..)) => true, (ArrayLen::Body(l_ct), ArrayLen::Body(r_ct)) => self.eq_body(l_ct.body, r_ct.body), @@ -1116,7 +1116,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { } } - pub fn hash_array_length(&mut self, length: ArrayLen) { + pub fn hash_array_length(&mut self, length: ArrayLen<'_>) { match length { ArrayLen::Infer(..) => {}, ArrayLen::Body(anon_const) => self.hash_body(anon_const.body), diff --git a/src/tools/clippy/tests/ui/almost_complete_range.fixed b/src/tools/clippy/tests/ui/almost_complete_range.fixed index 21caeb153e77d..6c2b2f117437d 100644 --- a/src/tools/clippy/tests/ui/almost_complete_range.fixed +++ b/src/tools/clippy/tests/ui/almost_complete_range.fixed @@ -1,7 +1,6 @@ //@edition:2018 //@aux-build:proc_macros.rs -#![feature(exclusive_range_pattern)] #![feature(stmt_expr_attributes)] #![warn(clippy::almost_complete_range)] #![allow(ellipsis_inclusive_range_patterns)] diff --git a/src/tools/clippy/tests/ui/almost_complete_range.rs b/src/tools/clippy/tests/ui/almost_complete_range.rs index 556110a5c8aae..813668a530966 100644 --- a/src/tools/clippy/tests/ui/almost_complete_range.rs +++ b/src/tools/clippy/tests/ui/almost_complete_range.rs @@ -1,7 +1,6 @@ //@edition:2018 //@aux-build:proc_macros.rs -#![feature(exclusive_range_pattern)] #![feature(stmt_expr_attributes)] #![warn(clippy::almost_complete_range)] #![allow(ellipsis_inclusive_range_patterns)] diff --git a/src/tools/clippy/tests/ui/almost_complete_range.stderr b/src/tools/clippy/tests/ui/almost_complete_range.stderr index 0195e59226d51..bfc2beb07d857 100644 --- a/src/tools/clippy/tests/ui/almost_complete_range.stderr +++ b/src/tools/clippy/tests/ui/almost_complete_range.stderr @@ -1,5 +1,5 @@ error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:18:17 + --> tests/ui/almost_complete_range.rs:17:17 | LL | let _ = ('a') ..'z'; | ^^^^^^--^^^ @@ -10,7 +10,7 @@ LL | let _ = ('a') ..'z'; = help: to override `-D warnings` add `#[allow(clippy::almost_complete_range)]` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:19:17 + --> tests/ui/almost_complete_range.rs:18:17 | LL | let _ = 'A' .. ('Z'); | ^^^^--^^^^^^ @@ -18,7 +18,7 @@ LL | let _ = 'A' .. ('Z'); | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:20:17 + --> tests/ui/almost_complete_range.rs:19:17 | LL | let _ = ((('0'))) .. ('9'); | ^^^^^^^^^^--^^^^^^ @@ -26,7 +26,7 @@ LL | let _ = ((('0'))) .. ('9'); | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:27:13 + --> tests/ui/almost_complete_range.rs:26:13 | LL | let _ = (b'a')..(b'z'); | ^^^^^^--^^^^^^ @@ -34,7 +34,7 @@ LL | let _ = (b'a')..(b'z'); | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:28:13 + --> tests/ui/almost_complete_range.rs:27:13 | LL | let _ = b'A'..b'Z'; | ^^^^--^^^^ @@ -42,7 +42,7 @@ LL | let _ = b'A'..b'Z'; | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:29:13 + --> tests/ui/almost_complete_range.rs:28:13 | LL | let _ = b'0'..b'9'; | ^^^^--^^^^ @@ -50,7 +50,7 @@ LL | let _ = b'0'..b'9'; | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:35:13 + --> tests/ui/almost_complete_range.rs:34:13 | LL | let _ = inline!('a')..'z'; | ^^^^^^^^^^^^--^^^ @@ -58,7 +58,7 @@ LL | let _ = inline!('a')..'z'; | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:36:13 + --> tests/ui/almost_complete_range.rs:35:13 | LL | let _ = inline!('A')..'Z'; | ^^^^^^^^^^^^--^^^ @@ -66,7 +66,7 @@ LL | let _ = inline!('A')..'Z'; | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:37:13 + --> tests/ui/almost_complete_range.rs:36:13 | LL | let _ = inline!('0')..'9'; | ^^^^^^^^^^^^--^^^ @@ -74,7 +74,7 @@ LL | let _ = inline!('0')..'9'; | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:40:9 + --> tests/ui/almost_complete_range.rs:39:9 | LL | b'a'..b'z' if true => 1, | ^^^^--^^^^ @@ -82,7 +82,7 @@ LL | b'a'..b'z' if true => 1, | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:41:9 + --> tests/ui/almost_complete_range.rs:40:9 | LL | b'A'..b'Z' if true => 2, | ^^^^--^^^^ @@ -90,7 +90,7 @@ LL | b'A'..b'Z' if true => 2, | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:42:9 + --> tests/ui/almost_complete_range.rs:41:9 | LL | b'0'..b'9' if true => 3, | ^^^^--^^^^ @@ -98,7 +98,7 @@ LL | b'0'..b'9' if true => 3, | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:50:9 + --> tests/ui/almost_complete_range.rs:49:9 | LL | 'a'..'z' if true => 1, | ^^^--^^^ @@ -106,7 +106,7 @@ LL | 'a'..'z' if true => 1, | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:51:9 + --> tests/ui/almost_complete_range.rs:50:9 | LL | 'A'..'Z' if true => 2, | ^^^--^^^ @@ -114,7 +114,7 @@ LL | 'A'..'Z' if true => 2, | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:52:9 + --> tests/ui/almost_complete_range.rs:51:9 | LL | '0'..'9' if true => 3, | ^^^--^^^ @@ -122,7 +122,7 @@ LL | '0'..'9' if true => 3, | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:65:17 + --> tests/ui/almost_complete_range.rs:64:17 | LL | let _ = 'a'..'z'; | ^^^--^^^ @@ -132,7 +132,7 @@ LL | let _ = 'a'..'z'; = note: this error originates in the macro `__inline_mac_fn_main` (in Nightly builds, run with -Z macro-backtrace for more info) error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:66:17 + --> tests/ui/almost_complete_range.rs:65:17 | LL | let _ = 'A'..'Z'; | ^^^--^^^ @@ -142,7 +142,7 @@ LL | let _ = 'A'..'Z'; = note: this error originates in the macro `__inline_mac_fn_main` (in Nightly builds, run with -Z macro-backtrace for more info) error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:67:17 + --> tests/ui/almost_complete_range.rs:66:17 | LL | let _ = '0'..'9'; | ^^^--^^^ @@ -152,7 +152,7 @@ LL | let _ = '0'..'9'; = note: this error originates in the macro `__inline_mac_fn_main` (in Nightly builds, run with -Z macro-backtrace for more info) error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:74:9 + --> tests/ui/almost_complete_range.rs:73:9 | LL | 'a'..'z' => 1, | ^^^--^^^ @@ -160,7 +160,7 @@ LL | 'a'..'z' => 1, | help: use an inclusive range: `...` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:75:9 + --> tests/ui/almost_complete_range.rs:74:9 | LL | 'A'..'Z' => 2, | ^^^--^^^ @@ -168,7 +168,7 @@ LL | 'A'..'Z' => 2, | help: use an inclusive range: `...` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:76:9 + --> tests/ui/almost_complete_range.rs:75:9 | LL | '0'..'9' => 3, | ^^^--^^^ @@ -176,7 +176,7 @@ LL | '0'..'9' => 3, | help: use an inclusive range: `...` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:83:13 + --> tests/ui/almost_complete_range.rs:82:13 | LL | let _ = 'a'..'z'; | ^^^--^^^ @@ -184,7 +184,7 @@ LL | let _ = 'a'..'z'; | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:84:13 + --> tests/ui/almost_complete_range.rs:83:13 | LL | let _ = 'A'..'Z'; | ^^^--^^^ @@ -192,7 +192,7 @@ LL | let _ = 'A'..'Z'; | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:85:13 + --> tests/ui/almost_complete_range.rs:84:13 | LL | let _ = '0'..'9'; | ^^^--^^^ @@ -200,7 +200,7 @@ LL | let _ = '0'..'9'; | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:87:9 + --> tests/ui/almost_complete_range.rs:86:9 | LL | 'a'..'z' => 1, | ^^^--^^^ @@ -208,7 +208,7 @@ LL | 'a'..'z' => 1, | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:88:9 + --> tests/ui/almost_complete_range.rs:87:9 | LL | 'A'..'Z' => 1, | ^^^--^^^ @@ -216,7 +216,7 @@ LL | 'A'..'Z' => 1, | help: use an inclusive range: `..=` error: almost complete ascii range - --> tests/ui/almost_complete_range.rs:89:9 + --> tests/ui/almost_complete_range.rs:88:9 | LL | '0'..'9' => 3, | ^^^--^^^ diff --git a/src/tools/clippy/tests/ui/manual_range_patterns.fixed b/src/tools/clippy/tests/ui/manual_range_patterns.fixed index e9f6fbcc3fc8c..f1b99637afdba 100644 --- a/src/tools/clippy/tests/ui/manual_range_patterns.fixed +++ b/src/tools/clippy/tests/ui/manual_range_patterns.fixed @@ -1,7 +1,6 @@ #![allow(unused)] #![allow(non_contiguous_range_endpoints)] #![warn(clippy::manual_range_patterns)] -#![feature(exclusive_range_pattern)] fn main() { let f = 6; diff --git a/src/tools/clippy/tests/ui/manual_range_patterns.rs b/src/tools/clippy/tests/ui/manual_range_patterns.rs index d525aaa24ad1b..869ffbe80b973 100644 --- a/src/tools/clippy/tests/ui/manual_range_patterns.rs +++ b/src/tools/clippy/tests/ui/manual_range_patterns.rs @@ -1,7 +1,6 @@ #![allow(unused)] #![allow(non_contiguous_range_endpoints)] #![warn(clippy::manual_range_patterns)] -#![feature(exclusive_range_pattern)] fn main() { let f = 6; diff --git a/src/tools/clippy/tests/ui/manual_range_patterns.stderr b/src/tools/clippy/tests/ui/manual_range_patterns.stderr index af9256aeea390..7c19fdd475f19 100644 --- a/src/tools/clippy/tests/ui/manual_range_patterns.stderr +++ b/src/tools/clippy/tests/ui/manual_range_patterns.stderr @@ -1,5 +1,5 @@ error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:9:25 + --> tests/ui/manual_range_patterns.rs:8:25 | LL | let _ = matches!(f, 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1..=10` @@ -8,109 +8,109 @@ LL | let _ = matches!(f, 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10); = help: to override `-D warnings` add `#[allow(clippy::manual_range_patterns)]` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:10:25 + --> tests/ui/manual_range_patterns.rs:9:25 | LL | let _ = matches!(f, 4 | 2 | 3 | 1 | 5 | 6 | 9 | 7 | 8 | 10); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1..=10` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:17:25 + --> tests/ui/manual_range_patterns.rs:16:25 | LL | let _ = matches!(f, 1 | (2..=4)); | ^^^^^^^^^^^ help: try: `1..=4` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:18:25 + --> tests/ui/manual_range_patterns.rs:17:25 | LL | let _ = matches!(f, 1 | (2..4)); | ^^^^^^^^^^ help: try: `1..4` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:19:25 + --> tests/ui/manual_range_patterns.rs:18:25 | LL | let _ = matches!(f, (1..=10) | (2..=13) | (14..=48324728) | 48324729); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1..=48324729` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:20:25 + --> tests/ui/manual_range_patterns.rs:19:25 | LL | let _ = matches!(f, 0 | (1..=10) | 48324730 | (2..=13) | (14..=48324728) | 48324729); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `0..=48324730` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:21:25 + --> tests/ui/manual_range_patterns.rs:20:25 | LL | let _ = matches!(f, 0..=1 | 0..=2 | 0..=3); | ^^^^^^^^^^^^^^^^^^^^^ help: try: `0..=3` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:24:9 + --> tests/ui/manual_range_patterns.rs:23:9 | LL | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 => true, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1..=10` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:27:25 + --> tests/ui/manual_range_patterns.rs:26:25 | LL | let _ = matches!(f, -1 | -5 | 3 | -2 | -4 | -3 | 0 | 1 | 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `-5..=3` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:29:25 + --> tests/ui/manual_range_patterns.rs:28:25 | LL | let _ = matches!(f, -1_000_000..=1_000_000 | -1_000_001 | 1_000_001); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `-1_000_001..=1_000_001` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:32:17 + --> tests/ui/manual_range_patterns.rs:31:17 | LL | matches!(f, 0x00 | 0x01 | 0x02 | 0x03); | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `0x00..=0x03` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:33:17 + --> tests/ui/manual_range_patterns.rs:32:17 | LL | matches!(f, 0x00..=0x05 | 0x06 | 0x07); | ^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `0x00..=0x07` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:34:17 + --> tests/ui/manual_range_patterns.rs:33:17 | LL | matches!(f, -0x09 | -0x08 | -0x07..=0x00); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `-0x09..=0x00` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:36:17 + --> tests/ui/manual_range_patterns.rs:35:17 | LL | matches!(f, 0..5 | 5); | ^^^^^^^^ help: try: `0..=5` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:37:17 + --> tests/ui/manual_range_patterns.rs:36:17 | LL | matches!(f, 0 | 1..5); | ^^^^^^^^ help: try: `0..5` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:39:17 + --> tests/ui/manual_range_patterns.rs:38:17 | LL | matches!(f, 0..=5 | 6..10); | ^^^^^^^^^^^^^ help: try: `0..10` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:40:17 + --> tests/ui/manual_range_patterns.rs:39:17 | LL | matches!(f, 0..5 | 5..=10); | ^^^^^^^^^^^^^ help: try: `0..=10` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:41:17 + --> tests/ui/manual_range_patterns.rs:40:17 | LL | matches!(f, 5..=10 | 0..5); | ^^^^^^^^^^^^^ help: try: `0..=10` error: this OR pattern can be rewritten using a range - --> tests/ui/manual_range_patterns.rs:45:26 + --> tests/ui/manual_range_patterns.rs:44:26 | LL | matches!($e, 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10) | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try: `1..=10` diff --git a/src/tools/clippy/tests/ui/match_overlapping_arm.rs b/src/tools/clippy/tests/ui/match_overlapping_arm.rs index c2c2f28392d77..4457ae73da2f0 100644 --- a/src/tools/clippy/tests/ui/match_overlapping_arm.rs +++ b/src/tools/clippy/tests/ui/match_overlapping_arm.rs @@ -1,4 +1,3 @@ -#![feature(exclusive_range_pattern)] #![warn(clippy::match_overlapping_arm)] #![allow(clippy::redundant_pattern_matching)] #![allow(clippy::if_same_then_else, clippy::equatable_if_let, clippy::needless_if)] diff --git a/src/tools/clippy/tests/ui/match_overlapping_arm.stderr b/src/tools/clippy/tests/ui/match_overlapping_arm.stderr index 1a6c5746c3dd2..65092ffbb5558 100644 --- a/src/tools/clippy/tests/ui/match_overlapping_arm.stderr +++ b/src/tools/clippy/tests/ui/match_overlapping_arm.stderr @@ -1,11 +1,11 @@ error: some ranges overlap - --> tests/ui/match_overlapping_arm.rs:12:9 + --> tests/ui/match_overlapping_arm.rs:11:9 | LL | 0..=10 => println!("0..=10"), | ^^^^^^ | note: overlaps with this - --> tests/ui/match_overlapping_arm.rs:14:9 + --> tests/ui/match_overlapping_arm.rs:13:9 | LL | 0..=11 => println!("0..=11"), | ^^^^^^ @@ -13,85 +13,85 @@ LL | 0..=11 => println!("0..=11"), = help: to override `-D warnings` add `#[allow(clippy::match_overlapping_arm)]` error: some ranges overlap - --> tests/ui/match_overlapping_arm.rs:19:9 + --> tests/ui/match_overlapping_arm.rs:18:9 | LL | 0..=5 => println!("0..=5"), | ^^^^^ | note: overlaps with this - --> tests/ui/match_overlapping_arm.rs:22:9 + --> tests/ui/match_overlapping_arm.rs:21:9 | LL | FOO..=11 => println!("FOO..=11"), | ^^^^^^^^ error: some ranges overlap - --> tests/ui/match_overlapping_arm.rs:57:9 + --> tests/ui/match_overlapping_arm.rs:56:9 | LL | 0..11 => println!("0..11"), | ^^^^^ | note: overlaps with this - --> tests/ui/match_overlapping_arm.rs:59:9 + --> tests/ui/match_overlapping_arm.rs:58:9 | LL | 0..=11 => println!("0..=11"), | ^^^^^^ error: some ranges overlap - --> tests/ui/match_overlapping_arm.rs:83:9 + --> tests/ui/match_overlapping_arm.rs:82:9 | LL | 0..=10 => println!("0..=10"), | ^^^^^^ | note: overlaps with this - --> tests/ui/match_overlapping_arm.rs:82:9 + --> tests/ui/match_overlapping_arm.rs:81:9 | LL | 5..14 => println!("5..14"), | ^^^^^ error: some ranges overlap - --> tests/ui/match_overlapping_arm.rs:89:9 + --> tests/ui/match_overlapping_arm.rs:88:9 | LL | 0..7 => println!("0..7"), | ^^^^ | note: overlaps with this - --> tests/ui/match_overlapping_arm.rs:91:9 + --> tests/ui/match_overlapping_arm.rs:90:9 | LL | 0..=10 => println!("0..=10"), | ^^^^^^ error: some ranges overlap - --> tests/ui/match_overlapping_arm.rs:102:9 + --> tests/ui/match_overlapping_arm.rs:101:9 | LL | ..=23 => println!("..=23"), | ^^^^^ | note: overlaps with this - --> tests/ui/match_overlapping_arm.rs:104:9 + --> tests/ui/match_overlapping_arm.rs:103:9 | LL | ..26 => println!("..26"), | ^^^^ error: some ranges overlap - --> tests/ui/match_overlapping_arm.rs:112:9 + --> tests/ui/match_overlapping_arm.rs:111:9 | LL | 21..=30 => (), | ^^^^^^^ | note: overlaps with this - --> tests/ui/match_overlapping_arm.rs:114:9 + --> tests/ui/match_overlapping_arm.rs:113:9 | LL | 21..=40 => (), | ^^^^^^^ error: some ranges overlap - --> tests/ui/match_overlapping_arm.rs:127:9 + --> tests/ui/match_overlapping_arm.rs:126:9 | LL | 0..=0x0000_0000_0000_00ff => (), | ^^^^^^^^^^^^^^^^^^^^^^^^^ | note: overlaps with this - --> tests/ui/match_overlapping_arm.rs:129:9 + --> tests/ui/match_overlapping_arm.rs:128:9 | LL | 0..=0x0000_0000_0000_ffff => (), | ^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/tools/clippy/tests/ui/match_wild_err_arm.rs b/src/tools/clippy/tests/ui/match_wild_err_arm.rs index 7bdd75d7f4639..8e670ce5bda2c 100644 --- a/src/tools/clippy/tests/ui/match_wild_err_arm.rs +++ b/src/tools/clippy/tests/ui/match_wild_err_arm.rs @@ -1,4 +1,3 @@ -#![feature(exclusive_range_pattern)] #![allow(clippy::match_same_arms, dead_code)] #![warn(clippy::match_wild_err_arm)] diff --git a/src/tools/clippy/tests/ui/match_wild_err_arm.stderr b/src/tools/clippy/tests/ui/match_wild_err_arm.stderr index 3145665a341e8..f98065d9a591f 100644 --- a/src/tools/clippy/tests/ui/match_wild_err_arm.stderr +++ b/src/tools/clippy/tests/ui/match_wild_err_arm.stderr @@ -1,5 +1,5 @@ error: `Err(_)` matches all errors - --> tests/ui/match_wild_err_arm.rs:24:9 + --> tests/ui/match_wild_err_arm.rs:23:9 | LL | Err(_) => panic!("err"), | ^^^^^^ @@ -9,7 +9,7 @@ LL | Err(_) => panic!("err"), = help: to override `-D warnings` add `#[allow(clippy::match_wild_err_arm)]` error: `Err(_)` matches all errors - --> tests/ui/match_wild_err_arm.rs:32:9 + --> tests/ui/match_wild_err_arm.rs:31:9 | LL | Err(_) => panic!(), | ^^^^^^ @@ -17,7 +17,7 @@ LL | Err(_) => panic!(), = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_)` matches all errors - --> tests/ui/match_wild_err_arm.rs:40:9 + --> tests/ui/match_wild_err_arm.rs:39:9 | LL | Err(_) => { | ^^^^^^ @@ -25,7 +25,7 @@ LL | Err(_) => { = note: match each error separately or use the error output, or use `.expect(msg)` if the error case is unreachable error: `Err(_e)` matches all errors - --> tests/ui/match_wild_err_arm.rs:50:9 + --> tests/ui/match_wild_err_arm.rs:49:9 | LL | Err(_e) => panic!(), | ^^^^^^^ diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs index 34e65c7d61fe5..42159b147d582 100644 --- a/src/tools/compiletest/src/header.rs +++ b/src/tools/compiletest/src/header.rs @@ -208,6 +208,8 @@ pub struct TestProps { pub llvm_cov_flags: Vec, /// Extra flags to pass to LLVM's `filecheck` tool, in tests that use it. pub filecheck_flags: Vec, + /// Don't automatically insert any `--check-cfg` args + pub no_auto_check_cfg: bool, } mod directives { @@ -249,6 +251,7 @@ mod directives { pub const COMPARE_OUTPUT_LINES_BY_SUBSET: &'static str = "compare-output-lines-by-subset"; pub const LLVM_COV_FLAGS: &'static str = "llvm-cov-flags"; pub const FILECHECK_FLAGS: &'static str = "filecheck-flags"; + pub const NO_AUTO_CHECK_CFG: &'static str = "no-auto-check-cfg"; // This isn't a real directive, just one that is probably mistyped often pub const INCORRECT_COMPILER_FLAGS: &'static str = "compiler-flags"; } @@ -304,6 +307,7 @@ impl TestProps { remap_src_base: false, llvm_cov_flags: vec![], filecheck_flags: vec![], + no_auto_check_cfg: false, } } @@ -567,6 +571,8 @@ impl TestProps { if let Some(flags) = config.parse_name_value_directive(ln, FILECHECK_FLAGS) { self.filecheck_flags.extend(split_flags(&flags)); } + + config.set_name_directive(ln, NO_AUTO_CHECK_CFG, &mut self.no_auto_check_cfg); }, ); @@ -860,6 +866,7 @@ const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "needs-unwind", "needs-wasmtime", "needs-xray", + "no-auto-check-cfg", "no-prefer-dynamic", "normalize-stderr-32bit", "normalize-stderr-64bit", diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 0a861d62c3726..1d69ed598591f 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -1028,12 +1028,31 @@ impl<'test> TestCx<'test> { } fn set_revision_flags(&self, cmd: &mut Command) { + // Normalize revisions to be lowercase and replace `-`s with `_`s. + // Otherwise the `--cfg` flag is not valid. + let normalize_revision = |revision: &str| revision.to_lowercase().replace("-", "_"); + if let Some(revision) = self.revision { - // Normalize revisions to be lowercase and replace `-`s with `_`s. - // Otherwise the `--cfg` flag is not valid. - let normalized_revision = revision.to_lowercase().replace("-", "_"); + let normalized_revision = normalize_revision(revision); cmd.args(&["--cfg", &normalized_revision]); } + + if !self.props.no_auto_check_cfg { + let mut check_cfg = String::with_capacity(25); + + // Generate `cfg(FALSE, REV1, ..., REVN)` (for all possible revisions) + // + // For compatibility reason we consider the `FALSE` cfg to be expected + // since it is extensively used in the testsuite. + check_cfg.push_str("cfg(FALSE"); + for revision in &self.props.revisions { + check_cfg.push_str(","); + check_cfg.push_str(&normalize_revision(&revision)); + } + check_cfg.push_str(")"); + + cmd.args(&["--check-cfg", &check_cfg]); + } } fn typecheck_source(&self, src: String) -> ProcRes { diff --git a/src/tools/miri/.github/workflows/ci.yml b/src/tools/miri/.github/workflows/ci.yml index 0af334a654b40..3bc4163ab5246 100644 --- a/src/tools/miri/.github/workflows/ci.yml +++ b/src/tools/miri/.github/workflows/ci.yml @@ -45,7 +45,7 @@ jobs: # over time). - name: Add cache for cargo id: cache - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: | # Taken from . @@ -61,7 +61,7 @@ jobs: restore-keys: cargo-${{ runner.os }}-reset20240425 - name: Install tools - if: ${{ steps.cache.outputs.cache-hit != 'true' }} + if: steps.cache.outputs.cache-hit != 'true' run: cargo install -f rustup-toolchain-install-master hyperfine - name: Install miri toolchain @@ -78,6 +78,12 @@ jobs: rustc -Vv cargo -V + # The `style` job only runs on Linux; this makes sure the Windows-host-specific + # code is also covered by clippy. + - name: Check clippy + if: matrix.os == 'windows-latest' + run: ./miri clippy -- -D warnings + - name: Test Miri run: ./ci/ci.sh @@ -95,7 +101,7 @@ jobs: # over time). - name: Add cache for cargo id: cache - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: | # Taken from . @@ -111,7 +117,7 @@ jobs: restore-keys: cargo-${{ runner.os }}-reset20240331 - name: Install rustup-toolchain-install-master - if: ${{ steps.cache.outputs.cache-hit != 'true' }} + if: steps.cache.outputs.cache-hit != 'true' run: cargo install -f rustup-toolchain-install-master - name: Install "master" toolchain diff --git a/src/tools/miri/Cargo.lock b/src/tools/miri/Cargo.lock index 293b937a5e52b..417ecb09b3196 100644 --- a/src/tools/miri/Cargo.lock +++ b/src/tools/miri/Cargo.lock @@ -30,28 +30,13 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "1.1.2" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0" +checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] -[[package]] -name = "android-tzdata" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" - -[[package]] -name = "android_system_properties" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" -dependencies = [ - "libc", -] - [[package]] name = "annotate-snippets" version = "0.9.2" @@ -73,21 +58,21 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.80" +version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ad32ce52e4161730f7098c077cd2ed6229b5804ccf99e5366be1ab72a98b4e1" +checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519" [[package]] name = "autocfg" -version = "1.1.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" +checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" [[package]] name = "backtrace" -version = "0.3.69" +version = "0.3.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837" +checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d" dependencies = [ "addr2line", "cc", @@ -100,33 +85,21 @@ dependencies = [ [[package]] name = "bitflags" -version = "1.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.4.2" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" [[package]] name = "bstr" -version = "1.9.0" +version = "1.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c48f0051a4b4c5e0b6d365cd04af53aeaa209e3cc15ec2cdb69e73cc87fbd0dc" +checksum = "05efc5cfd9110c8416e471df0e96702d58690178e206e61b7173706673c93706" dependencies = [ "memchr", "regex-automata", "serde", ] -[[package]] -name = "bumpalo" -version = "3.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" - [[package]] name = "camino" version = "1.1.6" @@ -138,9 +111,9 @@ dependencies = [ [[package]] name = "cargo-platform" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "694c8807f2ae16faecc43dc17d74b3eb042482789fd0eb64b39a2e04e087053f" +checksum = "24b1f0365a6c6bb4020cd05806fd0d33c44d38046b8bd7f0e40814b9763cabfc" dependencies = [ "serde", ] @@ -161,9 +134,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.86" +version = "1.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f9fa1897e4325be0d68d48df6aa1a71ac2ed4d27723887e7754192705350730" +checksum = "065a29261d53ba54260972629f9ca6bffa69bac13cd1fed61420f7fa68b9f8bd" [[package]] name = "cfg-if" @@ -171,16 +144,41 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + [[package]] name = "chrono" version = "0.4.38" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401" dependencies = [ - "android-tzdata", - "iana-time-zone", "num-traits", - "windows-targets 0.52.3", +] + +[[package]] +name = "chrono-tz" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93698b29de5e97ad0ae26447b344c482a7284c737d9ddc5f9e52b74a336671bb" +dependencies = [ + "chrono", + "chrono-tz-build", + "phf", +] + +[[package]] +name = "chrono-tz-build" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c088aee841df9c3041febbb73934cfc39708749bf96dc827e3359cd39ef11b1" +dependencies = [ + "parse-zoneinfo", + "phf", + "phf_codegen", ] [[package]] @@ -195,9 +193,9 @@ dependencies = [ [[package]] name = "color-eyre" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a667583cca8c4f8436db8de46ea8233c42a7d9ae424a82d338f2e4675229204" +checksum = "55146f5e46f237f7423d74111267d4597b59b0dad0ffaf7303bce9945d843ad5" dependencies = [ "backtrace", "color-spantrace", @@ -249,12 +247,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "core-foundation-sys" -version = "0.8.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" - [[package]] name = "cpufeatures" version = "0.2.12" @@ -266,9 +258,9 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.11" +version = "0.5.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "176dc175b78f56c0f321911d9c8eb2b77a78a4860b9c19db83835fea1a46649b" +checksum = "ab3db02a9c5b5121e1e42fbdb1aeb65f5e02624cc58c43f2884c6ccac0b82f95" dependencies = [ "crossbeam-utils", ] @@ -291,9 +283,9 @@ dependencies = [ [[package]] name = "ctrlc" -version = "3.4.2" +version = "3.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b467862cc8610ca6fc9a1532d7777cee0804e678ab45410897b9396495994a0b" +checksum = "672465ae37dc1bc6380a6547a8883d5dd397b0f1faaad4f265726cc7042a5345" dependencies = [ "nix", "windows-sys 0.52.0", @@ -348,9 +340,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "generic-array" @@ -364,9 +356,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.12" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" +checksum = "94b22e06ecb0110981051723910cbf0b5f5e09a2062dd7663334ee79a9d1286c" dependencies = [ "cfg-if", "libc", @@ -379,29 +371,6 @@ version = "0.28.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" -[[package]] -name = "iana-time-zone" -version = "0.1.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7ffbb5a1b541ea2561f8c41c087286cc091e21e556a4f09a8f6cbf17b69b141" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "indenter" version = "0.3.3" @@ -441,9 +410,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "jemalloc-sys" @@ -455,15 +424,6 @@ dependencies = [ "libc", ] -[[package]] -name = "js-sys" -version = "0.3.69" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" -dependencies = [ - "wasm-bindgen", -] - [[package]] name = "lazy_static" version = "1.4.0" @@ -478,9 +438,9 @@ checksum = "db13adb97ab515a3691f56e4dbab09283d0b86cb45abd991d8634a9d6f501760" [[package]] name = "libc" -version = "0.2.153" +version = "0.2.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" +checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346" [[package]] name = "libffi" @@ -503,12 +463,12 @@ dependencies = [ [[package]] name = "libloading" -version = "0.8.1" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c571b676ddfc9a8c12f1f3d3085a7b163966a8fd8098a90640953ce5f6170161" +checksum = "0c2a198fb6b0eada2a8df47933734e6d35d350665a33a3593d7164fa52c75c19" dependencies = [ "cfg-if", - "windows-sys 0.48.0", + "windows-targets 0.52.5", ] [[package]] @@ -517,7 +477,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ - "bitflags 2.4.2", + "bitflags", "libc", ] @@ -529,9 +489,9 @@ checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" [[package]] name = "lock_api" -version = "0.4.11" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" dependencies = [ "autocfg", "scopeguard", @@ -539,9 +499,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.20" +version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" [[package]] name = "measureme" @@ -559,9 +519,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.7.1" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" +checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" [[package]] name = "memmap2" @@ -587,12 +547,12 @@ version = "0.1.0" dependencies = [ "aes", "chrono", + "chrono-tz", "colored", "ctrlc", "directories", "getrandom", "jemalloc-sys", - "lazy_static", "libc", "libffi", "libloading", @@ -607,20 +567,21 @@ dependencies = [ [[package]] name = "nix" -version = "0.27.1" +version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2eb04e9c688eff1c89d72b407f168cf79bb9e867a9d3323ed6c01519eb9cc053" +checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" dependencies = [ - "bitflags 2.4.2", + "bitflags", "cfg-if", + "cfg_aliases", "libc", ] [[package]] name = "num-traits" -version = "0.2.18" +version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0df0e5185db44f69b44f26786fe401b6c293d1907744beaa7fa62b2e5a517a" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", ] @@ -669,9 +630,9 @@ dependencies = [ [[package]] name = "parking_lot" -version = "0.12.1" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +checksum = "7e4af0ca4f6caed20e900d564c242b8e5d4903fdacf31d3daf527b66fe6f42fb" dependencies = [ "lock_api", "parking_lot_core", @@ -679,15 +640,24 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.9" +version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", "redox_syscall", "smallvec", - "windows-targets 0.48.5", + "windows-targets 0.52.5", +] + +[[package]] +name = "parse-zoneinfo" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f2a05b18d44e2957b88f96ba460715e295bc1d7510468a2f3d3b44535d26c24" +dependencies = [ + "regex", ] [[package]] @@ -699,11 +669,49 @@ dependencies = [ "libc", ] +[[package]] +name = "phf" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ade2d8b8f33c7333b51bcf0428d37e217e9f32192ae4772156f65063b8ce03dc" +dependencies = [ + "phf_shared", +] + +[[package]] +name = "phf_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8d39688d359e6b34654d328e262234662d16cc0f60ec8dcbe5e718709342a5a" +dependencies = [ + "phf_generator", + "phf_shared", +] + +[[package]] +name = "phf_generator" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e4cc64c2ad9ebe670cb8fd69dd50ae301650392e81c05f9bfcb2d5bdbc24b0" +dependencies = [ + "phf_shared", + "rand", +] + +[[package]] +name = "phf_shared" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project-lite" -version = "0.2.13" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" +checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" [[package]] name = "portable-atomic" @@ -729,18 +737,18 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.78" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae" +checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.35" +version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] @@ -777,11 +785,11 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.4.1" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +checksum = "469052894dcb553421e483e4209ee581a45100d31b4018de03e5a7ad86374a7e" dependencies = [ - "bitflags 1.3.2", + "bitflags", ] [[package]] @@ -797,9 +805,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.10.3" +version = "1.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b62dbe01f0b06f9d8dc7d49e05a0785f153b00b2c227856282f671e0318c9b15" +checksum = "c117dbdfde9c8308975b6a18d71f3f385c89461f7b3fb054288ecf2a2058ba4c" dependencies = [ "aho-corasick", "memchr", @@ -809,9 +817,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.5" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bb987efffd3c6d0d8f5f89510bb458559eab11e4f869acb20bf845e016259cd" +checksum = "86b83b8b9847f9bf95ef68afb0b8e6cdb80f498442f5179a29fad448fcc1eaea" dependencies = [ "aho-corasick", "memchr", @@ -820,9 +828,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f" +checksum = "adad44e29e4c806119491a7f06f03de4d1af22c3a680dd47f1e6e179439d1f56" [[package]] name = "rustc-demangle" @@ -859,11 +867,11 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.31" +version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949" +checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ - "bitflags 2.4.2", + "bitflags", "errno", "libc", "linux-raw-sys", @@ -893,18 +901,18 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.197" +version = "1.0.200" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" +checksum = "ddc6f9cc94d67c0e21aaf7eda3a010fd3af78ebf6e096aa6e2e13c79749cce4f" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.197" +version = "1.0.200" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" +checksum = "856f046b9400cee3c8c94ed572ecdb752444c24528c035cd35882aad6f492bcb" dependencies = [ "proc-macro2", "quote", @@ -913,9 +921,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.114" +version = "1.0.116" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" +checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813" dependencies = [ "itoa", "ryu", @@ -931,17 +939,23 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + [[package]] name = "smallvec" -version = "1.13.1" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6ecd384b10a64542d77071bd64bd7b231f4ed5940fba55e98c3de13824cf3d7" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "syn" -version = "2.0.50" +version = "2.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74f1bdc9872430ce9b75da68329d1c1746faf50ffac5f19e02b71e37ff881ffb" +checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3" dependencies = [ "proc-macro2", "quote", @@ -950,9 +964,9 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.10.0" +version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a365e8cd18e44762ef95d87f284f4b5cd04107fec2ff3052bd6a3e6069669e67" +checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", @@ -962,18 +976,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.57" +version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e45bcbe8ed29775f228095caf2cd67af7a4ccf756ebff23a306bf3e8b47b24b" +checksum = "f0126ad08bff79f29fc3ae6a55cc72352056dfff61e3ff8bb7129476d44b23aa" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.57" +version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81" +checksum = "d1cd413b5d558b4c5bf3680e324a6fa5014e7b7c067a51e69dbdf47eb7148b66" dependencies = [ "proc-macro2", "quote", @@ -1072,9 +1086,9 @@ checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "unicode-width" -version = "0.1.11" +version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51733f11c9c4f72aa0c160008246859e340b00807569a0da0e7a1079b27ba85" +checksum = "68f5e5f3158ecfd4b8ff6fe086db7c8467a2dfdac97fe420f2b7c4aa97af66d6" [[package]] name = "valuable" @@ -1094,60 +1108,6 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" -[[package]] -name = "wasm-bindgen" -version = "0.2.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" -dependencies = [ - "cfg-if", - "wasm-bindgen-macro", -] - -[[package]] -name = "wasm-bindgen-backend" -version = "0.2.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" -dependencies = [ - "bumpalo", - "log", - "once_cell", - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-macro" -version = "0.2.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" -dependencies = [ - "quote", - "wasm-bindgen-macro-support", -] - -[[package]] -name = "wasm-bindgen-macro-support" -version = "0.2.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" -dependencies = [ - "proc-macro2", - "quote", - "syn", - "wasm-bindgen-backend", - "wasm-bindgen-shared", -] - -[[package]] -name = "wasm-bindgen-shared" -version = "0.2.92" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" - [[package]] name = "winapi" version = "0.3.9" @@ -1170,15 +1130,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "windows-core" -version = "0.52.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" -dependencies = [ - "windows-targets 0.52.3", -] - [[package]] name = "windows-sys" version = "0.48.0" @@ -1194,7 +1145,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.3", + "windows-targets 0.52.5", ] [[package]] @@ -1214,17 +1165,18 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d380ba1dc7187569a8a9e91ed34b8ccfc33123bbacb8c0aed2d1ad7f3ef2dc5f" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" dependencies = [ - "windows_aarch64_gnullvm 0.52.3", - "windows_aarch64_msvc 0.52.3", - "windows_i686_gnu 0.52.3", - "windows_i686_msvc 0.52.3", - "windows_x86_64_gnu 0.52.3", - "windows_x86_64_gnullvm 0.52.3", - "windows_x86_64_msvc 0.52.3", + "windows_aarch64_gnullvm 0.52.5", + "windows_aarch64_msvc 0.52.5", + "windows_i686_gnu 0.52.5", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.5", + "windows_x86_64_gnu 0.52.5", + "windows_x86_64_gnullvm 0.52.5", + "windows_x86_64_msvc 0.52.5", ] [[package]] @@ -1235,9 +1187,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68e5dcfb9413f53afd9c8f86e56a7b4d86d9a2fa26090ea2dc9e40fba56c6ec6" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" [[package]] name = "windows_aarch64_msvc" @@ -1247,9 +1199,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dab469ebbc45798319e69eebf92308e541ce46760b49b18c6b3fe5e8965b30f" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" [[package]] name = "windows_i686_gnu" @@ -1259,9 +1211,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.52.3" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a4e9b6a7cac734a8b4138a4e1044eac3404d8326b6c0f939276560687a033fb" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" [[package]] name = "windows_i686_msvc" @@ -1271,9 +1229,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b0ec9c422ca95ff34a78755cfa6ad4a51371da2a5ace67500cf7ca5f232c58" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" [[package]] name = "windows_x86_64_gnu" @@ -1283,9 +1241,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "704131571ba93e89d7cd43482277d6632589b18ecf4468f591fbae0a8b101614" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" [[package]] name = "windows_x86_64_gnullvm" @@ -1295,9 +1253,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42079295511643151e98d61c38c0acc444e52dd42ab456f7ccfd5152e8ecf21c" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" [[package]] name = "windows_x86_64_msvc" @@ -1307,9 +1265,9 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0770833d60a970638e989b3fa9fd2bb1aaadcf88963d1659fd7d9990196ed2d6" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" [[package]] name = "yansi-term" diff --git a/src/tools/miri/Cargo.toml b/src/tools/miri/Cargo.toml index ac8b4b37e9200..976bd080867eb 100644 --- a/src/tools/miri/Cargo.toml +++ b/src/tools/miri/Cargo.toml @@ -24,7 +24,8 @@ smallvec = "1.7" aes = { version = "0.8.3", features = ["hazmat"] } measureme = "11" ctrlc = "3.2.5" -chrono = { version = "0.4.38", default-features = false, features = ["clock"] } +chrono = { version = "0.4.38", default-features = false } +chrono-tz = "0.9" directories = "5" # Copied from `compiler/rustc/Cargo.toml`. diff --git a/src/tools/miri/README.md b/src/tools/miri/README.md index ef01ca25fb0b4..5b3e2a588b4fa 100644 --- a/src/tools/miri/README.md +++ b/src/tools/miri/README.md @@ -141,7 +141,7 @@ interpreter will explicitly tell you when it finds something unsupported: error: unsupported operation: can't call foreign function: bind ... = help: this is likely not a bug in the program; it indicates that the program \ - performed an operation that the interpreter does not support + performed an operation that Miri does not support ``` ### Cross-interpretation: running for different targets @@ -224,8 +224,12 @@ degree documented below): - `s390x-unknown-linux-gnu` is supported as our "big-endian target of choice". - For every other target with OS `linux`, `macos`, or `windows`, Miri should generally work, but we make no promises and we don't run tests for such targets. -- For targets on other operating systems, even basic operations such as printing to the standard - output might not work, and Miri might fail before even reaching the `main` function. +- We have unofficial support (not maintained by the Miri team itself) for some further operating systems. + - `freebsd`: **maintainer wanted**. Supports `std::env` and parts of `std::{thread, fs}`, but not `std::sync`. + - `android`: **maintainer wanted**. Support very incomplete, but a basic "hello world" works. + - `illumos`: maintained by @devnexen. Support very incomplete, but a basic "hello world" works. + - `wasm`: **maintainer wanted**. Support very incomplete, not even standard output works, but an empty `main` function works. +- For targets on other operating systems, Miri might fail before even reaching the `main` function. However, even for targets that we do support, the degree of support for accessing platform APIs (such as the file system) differs between targets: generally, Linux targets have the best support, diff --git a/src/tools/miri/bench-cargo-miri/mse/src/main.rs b/src/tools/miri/bench-cargo-miri/mse/src/main.rs index c09dc2484d380..e16ccd2c0d735 100644 --- a/src/tools/miri/bench-cargo-miri/mse/src/main.rs +++ b/src/tools/miri/bench-cargo-miri/mse/src/main.rs @@ -4,9 +4,6 @@ static EXPECTED: &[u8] = &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, static PCM: &[i16] = &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, -2, 0, -2, 0, -2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 1, 0, 1, 0, 0, -2, 0, -2, 0, -2, 0, -2, -2, -2, -3, -3, -3, -3, -4, -2, -5, -2, -5, -2, -4, 0, -4, 0, -4, 0, -4, 1, -4, 1, -4, 2, -4, 2, -4, 2, -4, 2, -4, 2, -3, 1, -4, 0, -4, 0, -5, 0, -5, 0, -5, 0, -4, 2, -4, 3, -4, 4, -3, 5, -2, 5, -3, 6, -3, 6, -3, 5, -3, 5, -2, 4, -2, 3, -5, 0, -6, 0, -3, -2, -4, -4, -9, -5, -9, -4, -4, -2, -4, -2, -4, 0, -2, 1, 1, 1, 4, 2, 8, 2, 12, 1, 13, 0, 12, 0, 11, 0, 8, -2, 7, 0, 7, -3, 11, -8, 15, -9, 17, -6, 17, -5, 13, -3, 7, 0, 3, 0, -2, 0, -4, 0, -4, -2, -6, 0, -14, -2, -17, -4, -8, 0, -7, 5, -17, 7, -18, 10, -7, 18, -2, 25, -3, 27, 0, 31, 4, 34, 4, 34, 8, 36, 8, 37, 2, 36, 4, 34, 8, 28, 3, 15, 0, 11, 0, 12, -5, 8, -4, 10, 0, 23, -4, 31, -8, 30, -2, 30, 0, 26, -6, 22, -6, 20, -12, 15, -19, 10, -10, 13, -14, 6, -43, -13, -43, -16, -9, -12, -10, -29, -42, -40, -37, -28, -5, -21, 1, -24, -8, -20, 4, -18, 26, -24, 44, -26, 66, -30, 86, -37, 88, -41, 72, -46, 50, -31, 28, 23, 14, 64, 16, 51, 26, 32, 34, 39, 42, 48, 35, 58, 0, 72, -36, 69, -59, 58, -98, 54, -124, 36, -103, 12, -110, 5, -173, -19, -146, -59, -4, -42, 51, 1, -23, -6, -30, -6, 45, 46, 47, 70, 6, 55, 19, 60, 38, 62, 42, 47, 61, 46, 40, 42, -19, 22, -34, 6, -35, -50, -61, -141, -37, -171, 17, -163, 26, -180, 46, -154, 80, -63, 48, -4, 18, 20, 50, 47, 58, 53, 44, 61, 57, 85, 37, 80, 0, 86, -8, 106, -95, 49, -213, -8, -131, 47, 49, 63, 40, -39, -69, -74, -37, -20, 63, -12, 58, -14, -12, 25, -31, 41, 11, 45, 76, 47, 167, 5, 261, -37, 277, -83, 183, -172, 35, -122, -79, 138, -70, 266, 69, 124, 228, 0, 391, -29, 594, -84, 702, -78, 627, -8, 551, -13, 509, 13, 372, 120, 352, 125, 622, 127, 691, 223, 362, 126, 386, -33, 915, 198, 958, 457, 456, 298, 500, 233, 1027, 469, 1096, 426, 918, 160, 1067, 141, 1220, 189, 1245, 164, 1375, 297, 1378, 503, 1299, 702, 1550, 929, 1799, 855, 1752, 547, 1830, 602, 1928, 832, 1736, 796, 1735, 933, 1961, 1385, 1935, 1562, 2105, 1485, 2716, 1449, 2948, 1305, 2768, 1205, 2716, 1346, 2531, 1450, 2470, 1653, 3117, 2111, 3370, 2176, 2696, 1947, 2925, 2305, 3846, 2658, 2425, 2184, -877, 1981, -2261, 2623, -1645, 2908, -1876, 2732, -2704, 2953, -2484, 3116, -2120, 2954, -2442, 3216, -2466, 3499, -2192, 3234, -2392, 3361, -2497, 3869, -2078, 3772, -1858, 3915, -2066, 4438, -2285, 2934, -2294, -280, -2066, -1762, -1992, -1412, -2298, -1535, -2399, -1789, -2223, -1419, -2244, -1334, -2092, -1476, -1777, -1396, -2014, -1571, -2199, -1574, -1843, -1167, -1910, -1446, -2007, -1818]; fn main() { - #[cfg(increase_thread_usage)] - let thread = std::thread::spawn(|| 4); - for _ in 0..2 { mse(PCM.len(), PCM, EXPECTED); } diff --git a/src/tools/miri/cargo-miri/Cargo.lock b/src/tools/miri/cargo-miri/Cargo.lock index a1dbc85605f86..b8ead460249fb 100644 --- a/src/tools/miri/cargo-miri/Cargo.lock +++ b/src/tools/miri/cargo-miri/Cargo.lock @@ -4,21 +4,15 @@ version = 3 [[package]] name = "anyhow" -version = "1.0.80" +version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ad32ce52e4161730f7098c077cd2ed6229b5804ccf99e5366be1ab72a98b4e1" +checksum = "f538837af36e6f6a9be0faa67f9a314f8119e4e4b5867c6ab40ed60360142519" [[package]] name = "bitflags" -version = "1.3.2" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf" +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" [[package]] name = "camino" @@ -44,9 +38,9 @@ dependencies = [ [[package]] name = "cargo-platform" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "694c8807f2ae16faecc43dc17d74b3eb042482789fd0eb64b39a2e04e087053f" +checksum = "24b1f0365a6c6bb4020cd05806fd0d33c44d38046b8bd7f0e40814b9763cabfc" dependencies = [ "serde", ] @@ -104,15 +98,15 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "getrandom" -version = "0.2.12" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" +checksum = "94b22e06ecb0110981051723910cbf0b5f5e09a2062dd7663334ee79a9d1286c" dependencies = [ "cfg-if", "libc", @@ -121,25 +115,24 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.10" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" [[package]] name = "libc" -version = "0.2.153" +version = "0.2.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" +checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346" [[package]] name = "libredox" -version = "0.0.1" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85c833ca1e66078851dba29046874e38f08b2c883700aa29a03ddd3b23814ee8" +checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d" dependencies = [ - "bitflags 2.4.2", + "bitflags", "libc", - "redox_syscall", ] [[package]] @@ -156,36 +149,27 @@ checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] name = "proc-macro2" -version = "1.0.78" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae" +checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.35" +version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] -[[package]] -name = "redox_syscall" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" -dependencies = [ - "bitflags 1.3.2", -] - [[package]] name = "redox_users" -version = "0.4.4" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a18479200779601e498ada4e8c1e1f50e3ee19deb0259c25825a98b5603b2cb4" +checksum = "bd283d9651eeda4b2a83a43c1c91b266c40fd76ecd39a50a8c630ae69dc72891" dependencies = [ "getrandom", "libredox", @@ -194,9 +178,9 @@ dependencies = [ [[package]] name = "rustc-build-sysroot" -version = "0.4.6" +version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9bf37423495cd3a6a9ef8c75fc4566de0d26de0ab75f36f67a426e58df5768c" +checksum = "ab1dbbd1bdf65fdac44c885f6cca147ba179108ce284b60a08ccc04b1f1dbac0" dependencies = [ "anyhow", "rustc_version", @@ -221,11 +205,11 @@ dependencies = [ [[package]] name = "rustix" -version = "0.38.31" +version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949" +checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ - "bitflags 2.4.2", + "bitflags", "errno", "libc", "linux-raw-sys", @@ -258,18 +242,18 @@ dependencies = [ [[package]] name = "serde" -version = "1.0.197" +version = "1.0.200" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" +checksum = "ddc6f9cc94d67c0e21aaf7eda3a010fd3af78ebf6e096aa6e2e13c79749cce4f" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.197" +version = "1.0.200" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" +checksum = "856f046b9400cee3c8c94ed572ecdb752444c24528c035cd35882aad6f492bcb" dependencies = [ "proc-macro2", "quote", @@ -278,9 +262,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.114" +version = "1.0.116" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" +checksum = "3e17db7126d17feb94eb3fad46bf1a96b034e8aacbc2e775fe81505f8b0b2813" dependencies = [ "itoa", "ryu", @@ -289,9 +273,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.50" +version = "2.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "74f1bdc9872430ce9b75da68329d1c1746faf50ffac5f19e02b71e37ff881ffb" +checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3" dependencies = [ "proc-macro2", "quote", @@ -300,9 +284,9 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.10.0" +version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a365e8cd18e44762ef95d87f284f4b5cd04107fec2ff3052bd6a3e6069669e67" +checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", @@ -312,18 +296,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.57" +version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e45bcbe8ed29775f228095caf2cd67af7a4ccf756ebff23a306bf3e8b47b24b" +checksum = "f0126ad08bff79f29fc3ae6a55cc72352056dfff61e3ff8bb7129476d44b23aa" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.57" +version = "1.0.59" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a953cb265bef375dae3de6663da4d3804eee9682ea80d8e2542529b73c531c81" +checksum = "d1cd413b5d558b4c5bf3680e324a6fa5014e7b7c067a51e69dbdf47eb7148b66" dependencies = [ "proc-macro2", "quote", @@ -338,9 +322,9 @@ checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "walkdir" -version = "2.4.0" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" dependencies = [ "same-file", "winapi-util", @@ -352,37 +336,15 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" -[[package]] -name = "winapi" -version = "0.3.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" -dependencies = [ - "winapi-i686-pc-windows-gnu", - "winapi-x86_64-pc-windows-gnu", -] - -[[package]] -name = "winapi-i686-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" - [[package]] name = "winapi-util" -version = "0.1.6" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596" +checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b" dependencies = [ - "winapi", + "windows-sys 0.52.0", ] -[[package]] -name = "winapi-x86_64-pc-windows-gnu" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" - [[package]] name = "windows-sys" version = "0.48.0" @@ -398,7 +360,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.3", + "windows-targets 0.52.5", ] [[package]] @@ -418,17 +380,18 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d380ba1dc7187569a8a9e91ed34b8ccfc33123bbacb8c0aed2d1ad7f3ef2dc5f" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" dependencies = [ - "windows_aarch64_gnullvm 0.52.3", - "windows_aarch64_msvc 0.52.3", - "windows_i686_gnu 0.52.3", - "windows_i686_msvc 0.52.3", - "windows_x86_64_gnu 0.52.3", - "windows_x86_64_gnullvm 0.52.3", - "windows_x86_64_msvc 0.52.3", + "windows_aarch64_gnullvm 0.52.5", + "windows_aarch64_msvc 0.52.5", + "windows_i686_gnu 0.52.5", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.5", + "windows_x86_64_gnu 0.52.5", + "windows_x86_64_gnullvm 0.52.5", + "windows_x86_64_msvc 0.52.5", ] [[package]] @@ -439,9 +402,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68e5dcfb9413f53afd9c8f86e56a7b4d86d9a2fa26090ea2dc9e40fba56c6ec6" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" [[package]] name = "windows_aarch64_msvc" @@ -451,9 +414,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8dab469ebbc45798319e69eebf92308e541ce46760b49b18c6b3fe5e8965b30f" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" [[package]] name = "windows_i686_gnu" @@ -463,9 +426,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.52.3" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a4e9b6a7cac734a8b4138a4e1044eac3404d8326b6c0f939276560687a033fb" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" [[package]] name = "windows_i686_msvc" @@ -475,9 +444,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28b0ec9c422ca95ff34a78755cfa6ad4a51371da2a5ace67500cf7ca5f232c58" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" [[package]] name = "windows_x86_64_gnu" @@ -487,9 +456,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "704131571ba93e89d7cd43482277d6632589b18ecf4468f591fbae0a8b101614" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" [[package]] name = "windows_x86_64_gnullvm" @@ -499,9 +468,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42079295511643151e98d61c38c0acc444e52dd42ab456f7ccfd5152e8ecf21c" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" [[package]] name = "windows_x86_64_msvc" @@ -511,6 +480,6 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.52.3" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0770833d60a970638e989b3fa9fd2bb1aaadcf88963d1659fd7d9990196ed2d6" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" diff --git a/src/tools/miri/cargo-miri/src/phases.rs b/src/tools/miri/cargo-miri/src/phases.rs index b774ca8fa7252..e2fc2a0c2779b 100644 --- a/src/tools/miri/cargo-miri/src/phases.rs +++ b/src/tools/miri/cargo-miri/src/phases.rs @@ -28,7 +28,7 @@ Examples: cargo miri run cargo miri test -- test-suite-filter - cargo miri setup --print sysroot + cargo miri setup --print-sysroot This will print the path to the generated sysroot (and nothing else) on stdout. stderr will still contain progress information about how the build is doing. @@ -87,6 +87,7 @@ pub fn phase_cargo_miri(mut args: impl Iterator) { ), }; let verbose = num_arg_flag("-v"); + let quiet = has_arg_flag("-q") || has_arg_flag("--quiet"); // Determine the involved architectures. let rustc_version = VersionMeta::for_command(miri_for_host()).unwrap_or_else(|err| { @@ -110,7 +111,7 @@ pub fn phase_cargo_miri(mut args: impl Iterator) { } // We always setup. - let miri_sysroot = setup(&subcommand, target, &rustc_version, verbose); + let miri_sysroot = setup(&subcommand, target, &rustc_version, verbose, quiet); // Invoke actual cargo for the job, but with different flags. // We re-use `cargo test` and `cargo run`, which makes target and binary handling very easy but diff --git a/src/tools/miri/cargo-miri/src/setup.rs b/src/tools/miri/cargo-miri/src/setup.rs index 401e9158faec5..9a58e6fa018da 100644 --- a/src/tools/miri/cargo-miri/src/setup.rs +++ b/src/tools/miri/cargo-miri/src/setup.rs @@ -19,6 +19,7 @@ pub fn setup( target: &str, rustc_version: &VersionMeta, verbose: usize, + quiet: bool, ) -> PathBuf { let only_setup = matches!(subcommand, MiriCommand::Setup); let ask_user = !only_setup; @@ -119,6 +120,9 @@ pub fn setup( for _ in 0..verbose { command.arg("-v"); } + if quiet { + command.arg("--quiet"); + } } else { // Suppress output. command.stdout(process::Stdio::null()); @@ -134,7 +138,7 @@ pub fn setup( let rustflags = &["-Cdebug-assertions=off", "-Coverflow-checks=on"]; // Do the build. - if print_sysroot { + if print_sysroot || quiet { // Be silent. } else { let mut msg = String::new(); @@ -169,7 +173,7 @@ pub fn setup( ) } }); - if print_sysroot { + if print_sysroot || quiet { // Be silent. } else if only_setup { eprintln!("A sysroot for Miri is now available in `{}`.", sysroot_dir.display()); diff --git a/src/tools/miri/ci/ci.sh b/src/tools/miri/ci/ci.sh index c1ffb80783ef6..713c97830a5a2 100755 --- a/src/tools/miri/ci/ci.sh +++ b/src/tools/miri/ci/ci.sh @@ -13,15 +13,6 @@ function endgroup { begingroup "Building Miri" -# Special Windows hacks -if [ "$HOST_TARGET" = i686-pc-windows-msvc ]; then - # The $BASH variable is `/bin/bash` here, but that path does not actually work. There are some - # hacks in place somewhere to try to paper over this, but the hacks dont work either (see - # ). So we hard-code the correct location for Github - # CI instead. - BASH="C:/Program Files/Git/usr/bin/bash" -fi - # Global configuration export RUSTFLAGS="-D warnings" export CARGO_INCREMENTAL=0 @@ -71,10 +62,9 @@ function run_tests { time MIRIFLAGS="${MIRIFLAGS-} -O -Zmir-opt-level=4 -Cdebug-assertions=yes" MIRI_SKIP_UI_CHECKS=1 ./miri test -- tests/{pass,panic} fi if [ -n "${MANY_SEEDS-}" ]; then - # Also run some many-seeds tests. 64 seeds means this takes around a minute per test. - # (Need to invoke via explicit `bash -c` for Windows.) + # Also run some many-seeds tests. time for FILE in tests/many-seeds/*.rs; do - MIRI_SEEDS=$MANY_SEEDS ./miri many-seeds "$BASH" -c "./miri run '$FILE'" + ./miri run "--many-seeds=0..$MANY_SEEDS" "$FILE" done fi if [ -n "${TEST_BENCH-}" ]; then @@ -117,10 +107,10 @@ function run_tests_minimal { exit 1 fi - ./miri test -- "$@" + time ./miri test -- "$@" # Ensure that a small smoke test of cargo-miri works. - cargo miri run --manifest-path test-cargo-miri/no-std-smoke/Cargo.toml --target ${MIRI_TEST_TARGET-$HOST_TARGET} + time cargo miri run --manifest-path test-cargo-miri/no-std-smoke/Cargo.toml --target ${MIRI_TEST_TARGET-$HOST_TARGET} endgroup } @@ -135,23 +125,11 @@ case $HOST_TARGET in GC_STRESS=1 MIR_OPT=1 MANY_SEEDS=64 TEST_BENCH=1 CARGO_MIRI_ENV=1 run_tests # Extra tier 1 # With reduced many-seed count to avoid spending too much time on that. - # (All OSes are run with 64 seeds at least once though via the macOS runner.) + # (All OSes and ABIs are run with 64 seeds at least once though via the macOS runner.) MANY_SEEDS=16 MIRI_TEST_TARGET=i686-unknown-linux-gnu run_tests MANY_SEEDS=16 MIRI_TEST_TARGET=aarch64-unknown-linux-gnu run_tests MANY_SEEDS=16 MIRI_TEST_TARGET=x86_64-apple-darwin run_tests MANY_SEEDS=16 MIRI_TEST_TARGET=x86_64-pc-windows-gnu run_tests - # Extra tier 2 - MIRI_TEST_TARGET=aarch64-apple-darwin run_tests - MIRI_TEST_TARGET=arm-unknown-linux-gnueabi run_tests - # Partially supported targets (tier 2) - MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthread-threadname libc-getentropy libc-getrandom libc-misc libc-fs atomic env align num_cpus - MIRI_TEST_TARGET=i686-unknown-freebsd run_tests_minimal hello integer vec panic/panic concurrency/simple pthread-threadname libc-getentropy libc-getrandom libc-misc libc-fs atomic env align num_cpus - MIRI_TEST_TARGET=aarch64-linux-android run_tests_minimal hello integer vec panic/panic - MIRI_TEST_TARGET=wasm32-wasi run_tests_minimal no_std integer strings wasm - MIRI_TEST_TARGET=wasm32-unknown-unknown run_tests_minimal no_std integer strings wasm - MIRI_TEST_TARGET=thumbv7em-none-eabihf run_tests_minimal no_std - # Custom target JSON file - MIRI_TEST_TARGET=tests/avr.json MIRI_NO_STD=1 run_tests_minimal no_std ;; aarch64-apple-darwin) # Host (tier 2) @@ -160,13 +138,28 @@ case $HOST_TARGET in MANY_SEEDS=64 MIRI_TEST_TARGET=i686-pc-windows-gnu run_tests MANY_SEEDS=64 MIRI_TEST_TARGET=x86_64-pc-windows-msvc CARGO_MIRI_ENV=1 run_tests # Extra tier 2 - MIRI_TEST_TARGET=s390x-unknown-linux-gnu run_tests # big-endian architecture + MIRI_TEST_TARGET=arm-unknown-linux-gnueabi run_tests + MIRI_TEST_TARGET=s390x-unknown-linux-gnu run_tests # big-endian architecture of choice + # Partially supported targets (tier 2) + VERY_BASIC="integer vec string btreemap" # common things we test on all of them (if they have std), requires no target-specific shims + BASIC="$VERY_BASIC hello hashmap alloc align" # ensures we have the shims for stdout and basic data structures + MIRI_TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal $BASIC panic/panic concurrency/simple atomic threadname libc-misc libc-random libc-time fs env num_cpus + MIRI_TEST_TARGET=i686-unknown-freebsd run_tests_minimal $BASIC panic/panic concurrency/simple atomic threadname libc-misc libc-random libc-time fs env num_cpus + MIRI_TEST_TARGET=x86_64-unknown-illumos run_tests_minimal $VERY_BASIC hello panic/panic concurrency/simple pthread-sync libc-misc libc-random + # TODO fix solaris stack guard + # MIRI_TEST_TARGET=x86_64-pc-solaris run_tests_minimal $VERY_BASIC hello panic/panic pthread-sync + MIRI_TEST_TARGET=aarch64-linux-android run_tests_minimal $VERY_BASIC hello panic/panic + MIRI_TEST_TARGET=wasm32-wasi run_tests_minimal $VERY_BASIC wasm + MIRI_TEST_TARGET=wasm32-unknown-unknown run_tests_minimal $VERY_BASIC wasm + MIRI_TEST_TARGET=thumbv7em-none-eabihf run_tests_minimal no_std + # Custom target JSON file + MIRI_TEST_TARGET=tests/avr.json MIRI_NO_STD=1 run_tests_minimal no_std ;; i686-pc-windows-msvc) # Host - # Only smoke-test `many-seeds`; 64 runs of just the scoped-thread-leak test take 15min here! - # See . - GC_STRESS=1 MIR_OPT=1 MANY_SEEDS=1 TEST_BENCH=1 run_tests + # Without GC_STRESS and with reduced many-seeds count as this is the slowest runner. + # (The macOS runner checks windows-msvc with full many-seeds count.) + MIR_OPT=1 MANY_SEEDS=16 TEST_BENCH=1 run_tests # Extra tier 1 # We really want to ensure a Linux target works on a Windows host, # and a 64bit target works on a 32bit host. diff --git a/src/tools/miri/miri-script/Cargo.lock b/src/tools/miri/miri-script/Cargo.lock index a6f7467f0a2f7..5e792abac175d 100644 --- a/src/tools/miri/miri-script/Cargo.lock +++ b/src/tools/miri/miri-script/Cargo.lock @@ -466,15 +466,15 @@ checksum = "0770833d60a970638e989b3fa9fd2bb1aaadcf88963d1659fd7d9990196ed2d6" [[package]] name = "xshell" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce2107fe03e558353b4c71ad7626d58ed82efaf56c54134228608893c77023ad" +checksum = "6db0ab86eae739efd1b054a8d3d16041914030ac4e01cd1dca0cf252fd8b6437" dependencies = [ "xshell-macros", ] [[package]] name = "xshell-macros" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7e2c411759b501fb9501aac2b1b2d287a6e93e5bdcf13c25306b23e1b716dd0e" +checksum = "9d422e8e38ec76e2f06ee439ccc765e9c6a9638b9e7c9f2e8255e4d41e8bd852" diff --git a/src/tools/miri/miri-script/Cargo.toml b/src/tools/miri/miri-script/Cargo.toml index 79d0b13600d4f..631d3a82102b5 100644 --- a/src/tools/miri/miri-script/Cargo.toml +++ b/src/tools/miri/miri-script/Cargo.toml @@ -19,7 +19,7 @@ itertools = "0.11" path_macro = "1.0" shell-words = "1.1" anyhow = "1.0" -xshell = "0.2" +xshell = "0.2.6" rustc_version = "0.4" dunce = "1.0.4" directories = "5" diff --git a/src/tools/miri/miri-script/src/commands.rs b/src/tools/miri/miri-script/src/commands.rs index 66707dee5e75e..6d07455c0deb6 100644 --- a/src/tools/miri/miri-script/src/commands.rs +++ b/src/tools/miri/miri-script/src/commands.rs @@ -2,6 +2,7 @@ use std::env; use std::ffi::OsString; use std::io::Write; use std::ops::Not; +use std::ops::Range; use std::path::PathBuf; use std::process; use std::thread; @@ -150,7 +151,6 @@ impl Command { | Command::Fmt { .. } | Command::Clippy { .. } | Command::Cargo { .. } => Self::auto_actions()?, - | Command::ManySeeds { .. } | Command::Toolchain { .. } | Command::Bench { .. } | Command::RustcPull { .. } @@ -162,11 +162,11 @@ impl Command { Command::Build { flags } => Self::build(flags), Command::Check { flags } => Self::check(flags), Command::Test { bless, flags } => Self::test(bless, flags), - Command::Run { dep, flags } => Self::run(dep, flags), + Command::Run { dep, verbose, many_seeds, flags } => + Self::run(dep, verbose, many_seeds, flags), Command::Fmt { flags } => Self::fmt(flags), Command::Clippy { flags } => Self::clippy(flags), Command::Cargo { flags } => Self::cargo(flags), - Command::ManySeeds { command } => Self::many_seeds(command), Command::Bench { benches } => Self::bench(benches), Command::Toolchain { flags } => Self::toolchain(flags), Command::RustcPull { commit } => Self::rustc_pull(commit.clone()), @@ -239,6 +239,8 @@ impl Command { // the merge has confused the heck out of josh in the past. // We pass `--no-verify` to avoid running git hooks like `./miri fmt` that could in turn // trigger auto-actions. + // We do this before the merge so that if there are merge conflicts, we have + // the right rust-version file while resolving them. sh.write_file("rust-version", format!("{commit}\n"))?; const PREPARING_COMMIT_MESSAGE: &str = "Preparing for merge from rustc"; cmd!(sh, "git commit rust-version --no-verify -m {PREPARING_COMMIT_MESSAGE}") @@ -257,12 +259,26 @@ impl Command { }) .context("FAILED to fetch new commits, something went wrong (committing the rust-version file has been undone)")?; + // This should not add any new root commits. So count those before and after merging. + let num_roots = || -> Result { + Ok(cmd!(sh, "git rev-list HEAD --max-parents=0 --count") + .read() + .context("failed to determine the number of root commits")? + .parse::()?) + }; + let num_roots_before = num_roots()?; + // Merge the fetched commit. const MERGE_COMMIT_MESSAGE: &str = "Merge from rustc"; cmd!(sh, "git merge FETCH_HEAD --no-verify --no-ff -m {MERGE_COMMIT_MESSAGE}") .run() .context("FAILED to merge new commits, something went wrong")?; + // Check that the number of roots did not increase. + if num_roots()? != num_roots_before { + bail!("Josh created a new root commit. This is probably not the history you want."); + } + drop(josh); Ok(()) } @@ -353,43 +369,6 @@ impl Command { Ok(()) } - fn many_seeds(command: Vec) -> Result<()> { - let seed_start: u64 = env::var("MIRI_SEED_START") - .unwrap_or_else(|_| "0".into()) - .parse() - .context("failed to parse MIRI_SEED_START")?; - let seed_end: u64 = match (env::var("MIRI_SEEDS"), env::var("MIRI_SEED_END")) { - (Ok(_), Ok(_)) => bail!("Only one of MIRI_SEEDS and MIRI_SEED_END may be set"), - (Ok(seeds), Err(_)) => - seed_start + seeds.parse::().context("failed to parse MIRI_SEEDS")?, - (Err(_), Ok(seed_end)) => seed_end.parse().context("failed to parse MIRI_SEED_END")?, - (Err(_), Err(_)) => seed_start + 256, - }; - if seed_end <= seed_start { - bail!("the end of the seed range must be larger than the start."); - } - - let Some((command_name, trailing_args)) = command.split_first() else { - bail!("expected many-seeds command to be non-empty"); - }; - let sh = Shell::new()?; - sh.set_var("MIRI_AUTO_OPS", "no"); // just in case we get recursively invoked - for seed in seed_start..seed_end { - println!("Trying seed: {seed}"); - let mut miriflags = env::var_os("MIRIFLAGS").unwrap_or_default(); - miriflags.push(format!(" -Zlayout-seed={seed} -Zmiri-seed={seed}")); - let status = cmd!(sh, "{command_name} {trailing_args...}") - .env("MIRIFLAGS", miriflags) - .quiet() - .run(); - if let Err(err) = status { - println!("Failing seed: {seed}"); - return Err(err.into()); - } - } - Ok(()) - } - fn bench(benches: Vec) -> Result<()> { // The hyperfine to use let hyperfine = env::var("HYPERFINE"); @@ -481,7 +460,12 @@ impl Command { Ok(()) } - fn run(dep: bool, mut flags: Vec) -> Result<()> { + fn run( + dep: bool, + verbose: bool, + many_seeds: Option>, + mut flags: Vec, + ) -> Result<()> { let mut e = MiriEnv::new()?; // Scan for "--target" to overwrite the "MIRI_TEST_TARGET" env var so // that we set the MIRI_SYSROOT up the right way. We must make sure that @@ -508,26 +492,49 @@ impl Command { } // Prepare a sysroot, and add it to the flags. - let miri_sysroot = e.build_miri_sysroot(/* quiet */ true)?; + let miri_sysroot = e.build_miri_sysroot(/* quiet */ !verbose)?; flags.push("--sysroot".into()); flags.push(miri_sysroot.into()); - // Then run the actual command. Also add MIRIFLAGS. + // Compute everything needed to run the actual command. Also add MIRIFLAGS. let miri_manifest = path!(e.miri_dir / "Cargo.toml"); let miri_flags = e.sh.var("MIRIFLAGS").unwrap_or_default(); let miri_flags = flagsplit(&miri_flags); let toolchain = &e.toolchain; let extra_flags = &e.cargo_extra_flags; - if dep { - cmd!( - e.sh, - "cargo +{toolchain} --quiet test {extra_flags...} --manifest-path {miri_manifest} --test ui -- --miri-run-dep-mode {miri_flags...} {flags...}" - ).quiet().run()?; + let quiet_flag = if verbose { None } else { Some("--quiet") }; + // This closure runs the command with the given `seed_flag` added between the MIRIFLAGS and + // the `flags` given on the command-line. + let run_miri = |sh: &Shell, seed_flag: Option| -> Result<()> { + // The basic command that executes the Miri driver. + let mut cmd = if dep { + cmd!( + sh, + "cargo +{toolchain} {quiet_flag...} test {extra_flags...} --manifest-path {miri_manifest} --test ui -- --miri-run-dep-mode" + ) + } else { + cmd!( + sh, + "cargo +{toolchain} {quiet_flag...} run {extra_flags...} --manifest-path {miri_manifest} --" + ) + }; + cmd.set_quiet(!verbose); + // Add Miri flags + let cmd = cmd.args(&miri_flags).args(seed_flag).args(&flags); + // And run the thing. + Ok(cmd.run()?) + }; + // Run the closure once or many times. + if let Some(seed_range) = many_seeds { + e.run_many_times(seed_range, |sh, seed| { + eprintln!("Trying seed: {seed}"); + run_miri(sh, Some(format!("-Zmiri-seed={seed}"))).map_err(|err| { + eprintln!("FAILING SEED: {seed}"); + err + }) + })?; } else { - cmd!( - e.sh, - "cargo +{toolchain} --quiet run {extra_flags...} --manifest-path {miri_manifest} -- {miri_flags...} {flags...}" - ).quiet().run()?; + run_miri(&e.sh, None)?; } Ok(()) } diff --git a/src/tools/miri/miri-script/src/main.rs b/src/tools/miri/miri-script/src/main.rs index 712180be2825a..f0ebbc846906e 100644 --- a/src/tools/miri/miri-script/src/main.rs +++ b/src/tools/miri/miri-script/src/main.rs @@ -3,10 +3,10 @@ mod commands; mod util; -use std::env; use std::ffi::OsString; +use std::{env, ops::Range}; -use anyhow::{anyhow, bail, Result}; +use anyhow::{anyhow, bail, Context, Result}; #[derive(Clone, Debug)] pub enum Command { @@ -38,6 +38,8 @@ pub enum Command { /// (Also respects MIRIFLAGS environment variable.) Run { dep: bool, + verbose: bool, + many_seeds: Option>, /// Flags that are passed through to `miri`. flags: Vec, }, @@ -54,10 +56,6 @@ pub enum Command { /// Runs just `cargo ` with the Miri-specific environment variables. /// Mainly meant to be invoked by rust-analyzer. Cargo { flags: Vec }, - /// Runs over and over again with different seeds for Miri. The MIRIFLAGS - /// variable is set to its original value appended with ` -Zmiri-seed=$SEED` for - /// many different seeds. - ManySeeds { command: Vec }, /// Runs the benchmarks from bench-cargo-miri in hyperfine. hyperfine needs to be installed. Bench { /// List of benchmarks to run. By default all benchmarks are run. @@ -90,9 +88,11 @@ Just check miri. are passed to `cargo check`. Build miri, set up a sysroot and then run the test suite. are passed to the final `cargo test` invocation. -./miri run [--dep] : +./miri run [--dep] [-v|--verbose] [--many-seeds|--many-seeds=..to|--many-seeds=from..to] : Build miri, set up a sysroot and then run the driver with the given . (Also respects MIRIFLAGS environment variable.) +If `--many-seeds` is present, Miri is run many times in parallel with different seeds. +The range defaults to `0..256`. ./miri fmt : Format all sources and tests. are passed to `rustfmt`. @@ -110,13 +110,6 @@ install`. Sets up the rpath such that the installed binary should work in any working directory. Note that the binaries are placed in the `miri` toolchain sysroot, to prevent conflicts with other toolchains. -./miri many-seeds : -Runs over and over again with different seeds for Miri. The MIRIFLAGS -variable is set to its original value appended with ` -Zmiri-seed=$SEED` for -many different seeds. MIRI_SEED_START controls the first seed to try (default: 0). -MIRI_SEEDS controls how many seeds are being tried (default: 256); -alternatively, MIRI_SEED_END controls the end of the (exclusive) seed range to try. - ./miri bench : Runs the benchmarks from bench-cargo-miri in hyperfine. hyperfine needs to be installed. can explicitly list the benchmarks to run; by default, all of them are run. @@ -132,10 +125,10 @@ Pull and merge Miri changes from the rustc repo. Defaults to fetching the latest rustc commit. The fetched commit is stored in the `rust-version` file, so the next `./miri toolchain` will install the rustc that just got pulled. -./miri rustc-push : +./miri rustc-push []: Push Miri changes back to the rustc repo. This will pull a copy of the rustc history into the Miri repo, unless you set the RUSTC_GIT env var to an existing -clone of the rustc repo. +clone of the rustc repo. The branch defaults to `miri-sync`. ENVIRONMENT VARIABLES @@ -162,18 +155,39 @@ fn main() -> Result<()> { Command::Test { bless, flags: args.collect() } } Some("run") => { - let dep = args.peek().is_some_and(|a| a.to_str() == Some("--dep")); - if dep { - // Consume the flag. + let mut dep = false; + let mut verbose = false; + let mut many_seeds = None; + while let Some(arg) = args.peek().and_then(|s| s.to_str()) { + if arg == "--dep" { + dep = true; + } else if arg == "-v" || arg == "--verbose" { + verbose = true; + } else if arg == "--many-seeds" { + many_seeds = Some(0..256); + } else if let Some(val) = arg.strip_prefix("--many-seeds=") { + let (from, to) = val.split_once("..").ok_or_else(|| { + anyhow!("invalid format for `--many-seeds`: expected `from..to`") + })?; + let from: u32 = if from.is_empty() { + 0 + } else { + from.parse().context("invalid `from` in `--many-seeds=from..to")? + }; + let to: u32 = to.parse().context("invalid `to` in `--many-seeds=from..to")?; + many_seeds = Some(from..to); + } else { + break; // not for us + } + // Consume the flag, look at the next one. args.next().unwrap(); } - Command::Run { dep, flags: args.collect() } + Command::Run { dep, verbose, many_seeds, flags: args.collect() } } Some("fmt") => Command::Fmt { flags: args.collect() }, Some("clippy") => Command::Clippy { flags: args.collect() }, Some("cargo") => Command::Cargo { flags: args.collect() }, Some("install") => Command::Install { flags: args.collect() }, - Some("many-seeds") => Command::ManySeeds { command: args.collect() }, Some("bench") => Command::Bench { benches: args.collect() }, Some("toolchain") => Command::Toolchain { flags: args.collect() }, Some("rustc-pull") => { @@ -187,17 +201,12 @@ fn main() -> Result<()> { let github_user = args .next() .ok_or_else(|| { - anyhow!("Missing first argument for `./miri rustc-push GITHUB_USER BRANCH`") - })? - .to_string_lossy() - .into_owned(); - let branch = args - .next() - .ok_or_else(|| { - anyhow!("Missing second argument for `./miri rustc-push GITHUB_USER BRANCH`") + anyhow!("Missing first argument for `./miri rustc-push GITHUB_USER [BRANCH]`") })? .to_string_lossy() .into_owned(); + let branch = + args.next().unwrap_or_else(|| "miri-sync".into()).to_string_lossy().into_owned(); if args.next().is_some() { bail!("Too many arguments for `./miri rustc-push GITHUB_USER BRANCH`"); } diff --git a/src/tools/miri/miri-script/src/util.rs b/src/tools/miri/miri-script/src/util.rs index 361a4ca0cf769..23b5e936edd81 100644 --- a/src/tools/miri/miri-script/src/util.rs +++ b/src/tools/miri/miri-script/src/util.rs @@ -1,5 +1,8 @@ use std::ffi::{OsStr, OsString}; +use std::ops::Range; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::thread; use anyhow::{anyhow, Context, Result}; use dunce::canonicalize; @@ -189,4 +192,54 @@ impl MiriEnv { Ok(()) } + + /// Run the given closure many times in parallel with access to the shell, once for each value in the `range`. + pub fn run_many_times( + &self, + range: Range, + run: impl Fn(&Shell, u32) -> Result<()> + Sync, + ) -> Result<()> { + // `next` is atomic so threads can concurrently fetch their next value to run. + let next = AtomicU32::new(range.start); + let end = range.end; // exclusive! + let failed = AtomicBool::new(false); + thread::scope(|s| { + let mut handles = Vec::new(); + // Spawn one worker per core. + for _ in 0..thread::available_parallelism()?.get() { + // Create a copy of the shell for this thread. + let local_shell = self.sh.clone(); + let handle = s.spawn(|| -> Result<()> { + let local_shell = local_shell; // move the copy into this thread. + // Each worker thread keeps asking for numbers until we're all done. + loop { + let cur = next.fetch_add(1, Ordering::Relaxed); + if cur >= end { + // We hit the upper limit and are done. + break; + } + // Run the command with this seed. + run(&local_shell, cur).map_err(|err| { + // If we failed, tell everyone about this. + failed.store(true, Ordering::Relaxed); + err + })?; + // Check if some other command failed (in which case we'll stop as well). + if failed.load(Ordering::Relaxed) { + return Ok(()); + } + } + Ok(()) + }); + handles.push(handle); + } + // Wait for all workers to be done. + for handle in handles { + handle.join().unwrap()?; + } + // If all workers succeeded, we can't have failed. + assert!(!failed.load(Ordering::Relaxed)); + Ok(()) + }) + } } diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version index a45ecda15c4c0..ca6f4d50917e9 100644 --- a/src/tools/miri/rust-version +++ b/src/tools/miri/rust-version @@ -1 +1 @@ -6acb9e75ebc936df737381a9d0b7a7bccd6f0b2f +d568423a7a4ddb4b49323d96078a22f94df55fbd diff --git a/src/tools/miri/src/borrow_tracker/tree_borrows/tree.rs b/src/tools/miri/src/borrow_tracker/tree_borrows/tree.rs index 2470624181e74..ff4589657aff2 100644 --- a/src/tools/miri/src/borrow_tracker/tree_borrows/tree.rs +++ b/src/tools/miri/src/borrow_tracker/tree_borrows/tree.rs @@ -106,6 +106,8 @@ impl LocationState { let old_perm = self.permission; let transition = Permission::perform_access(access_kind, rel_pos, old_perm, protected) .ok_or(TransitionError::ChildAccessForbidden(old_perm))?; + self.initialized |= !rel_pos.is_foreign(); + self.permission = transition.applied(old_perm).unwrap(); // Why do only initialized locations cause protector errors? // Consider two mutable references `x`, `y` into disjoint parts of // the same allocation. A priori, these may actually both be used to @@ -123,8 +125,6 @@ impl LocationState { if protected && self.initialized && transition.produces_disabled() { return Err(TransitionError::ProtectedDisabled(old_perm)); } - self.permission = transition.applied(old_perm).unwrap(); - self.initialized |= !rel_pos.is_foreign(); Ok(transition) } diff --git a/src/tools/miri/src/concurrency/sync.rs b/src/tools/miri/src/concurrency/sync.rs index d3cef8bf5f32b..9467695599966 100644 --- a/src/tools/miri/src/concurrency/sync.rs +++ b/src/tools/miri/src/concurrency/sync.rs @@ -305,6 +305,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let this = self.eval_context_mut(); let next_index = this.machine.threads.sync.mutexes.next_index(); if let Some(old) = existing(this, next_index)? { + if this.machine.threads.sync.mutexes.get(old).is_none() { + throw_ub_format!("mutex has invalid ID"); + } Ok(old) } else { let new_index = this.machine.threads.sync.mutexes.push(Default::default()); @@ -399,6 +402,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let this = self.eval_context_mut(); let next_index = this.machine.threads.sync.rwlocks.next_index(); if let Some(old) = existing(this, next_index)? { + if this.machine.threads.sync.rwlocks.get(old).is_none() { + throw_ub_format!("rwlock has invalid ID"); + } Ok(old) } else { let new_index = this.machine.threads.sync.rwlocks.push(Default::default()); @@ -563,6 +569,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let this = self.eval_context_mut(); let next_index = this.machine.threads.sync.condvars.next_index(); if let Some(old) = existing(this, next_index)? { + if this.machine.threads.sync.condvars.get(old).is_none() { + throw_ub_format!("condvar has invalid ID"); + } Ok(old) } else { let new_index = this.machine.threads.sync.condvars.push(Default::default()); diff --git a/src/tools/miri/src/concurrency/thread.rs b/src/tools/miri/src/concurrency/thread.rs index 0116bd0281adc..6953ce81c5e82 100644 --- a/src/tools/miri/src/concurrency/thread.rs +++ b/src/tools/miri/src/concurrency/thread.rs @@ -78,6 +78,13 @@ impl TryFrom for ThreadId { } } +impl TryFrom for ThreadId { + type Error = TryFromIntError; + fn try_from(id: i128) -> Result { + u32::try_from(id).map(Self) + } +} + impl From for ThreadId { fn from(id: u32) -> Self { Self(id) diff --git a/src/tools/miri/src/diagnostics.rs b/src/tools/miri/src/diagnostics.rs index 9fa786332e3cd..cb5ed27b6cf18 100644 --- a/src/tools/miri/src/diagnostics.rs +++ b/src/tools/miri/src/diagnostics.rs @@ -48,6 +48,7 @@ pub enum TerminationInfo { extra: Option<&'static str>, retag_explain: bool, }, + UnsupportedForeignItem(String), } pub struct RacingOp { @@ -85,6 +86,7 @@ impl fmt::Display for TerminationInfo { op2.action, op2.thread_info ), + UnsupportedForeignItem(msg) => write!(f, "{msg}"), } } } @@ -214,7 +216,7 @@ pub fn report_error<'tcx, 'mir>( let title = match info { Exit { code, leak_check } => return Some((*code, *leak_check)), Abort(_) => Some("abnormal termination"), - UnsupportedInIsolation(_) | Int2PtrWithStrictProvenance => + UnsupportedInIsolation(_) | Int2PtrWithStrictProvenance | UnsupportedForeignItem(_) => Some("unsupported operation"), StackedBorrowsUb { .. } | TreeBorrowsUb { .. } | DataRace { .. } => Some("Undefined Behavior"), @@ -228,6 +230,12 @@ pub fn report_error<'tcx, 'mir>( (None, format!("pass the flag `-Zmiri-disable-isolation` to disable isolation;")), (None, format!("or pass `-Zmiri-isolation-error=warn` to configure Miri to return an error code from isolated operations (if supported for that operation) and continue with a warning")), ], + UnsupportedForeignItem(_) => { + vec![ + (None, format!("if this is a basic API commonly used on this target, please report an issue with Miri")), + (None, format!("however, note that Miri does not aim to support every FFI function out there; for instance, we will not support APIs for things such as GUIs, scripting languages, or databases")), + ] + } StackedBorrowsUb { help, history, .. } => { msg.extend(help.clone()); let mut helps = vec![ @@ -320,7 +328,9 @@ pub fn report_error<'tcx, 'mir>( #[rustfmt::skip] let helps = match e.kind() { Unsupported(_) => - vec![(None, format!("this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support"))], + vec![ + (None, format!("this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support")), + ], UndefinedBehavior(AlignmentCheckFailed { .. }) if ecx.machine.check_alignment == AlignmentCheck::Symbolic => @@ -344,7 +354,7 @@ pub fn report_error<'tcx, 'mir>( } AbiMismatchArgument { .. } | AbiMismatchReturn { .. } => { helps.push((None, format!("this means these two types are not *guaranteed* to be ABI-compatible across all targets"))); - helps.push((None, format!("if you think this code should be accepted anyway, please report an issue"))); + helps.push((None, format!("if you think this code should be accepted anyway, please report an issue with Miri"))); } _ => {}, } diff --git a/src/tools/miri/src/eval.rs b/src/tools/miri/src/eval.rs index 2242768a56827..97c5e9a0eac97 100644 --- a/src/tools/miri/src/eval.rs +++ b/src/tools/miri/src/eval.rs @@ -387,7 +387,7 @@ pub fn create_ecx<'mir, 'tcx: 'mir>( let main_ptr = ecx.fn_ptr(FnVal::Instance(entry_instance)); // Always using DEFAULT is okay since we don't support signals in Miri anyway. - // (This means we are effectively ignoring `#[unix_sigpipe]`.) + // (This means we are effectively ignoring `-Zon-broken-pipe`.) let sigpipe = rustc_session::config::sigpipe::DEFAULT; ecx.call_function( diff --git a/src/tools/miri/src/helpers.rs b/src/tools/miri/src/helpers.rs index 92bdaf301704b..40c2008ac9435 100644 --- a/src/tools/miri/src/helpers.rs +++ b/src/tools/miri/src/helpers.rs @@ -255,14 +255,19 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } /// Evaluates the scalar at the specified path. - fn eval_path_scalar(&self, path: &[&str]) -> Scalar { + fn eval_path(&self, path: &[&str]) -> OpTy<'tcx, Provenance> { let this = self.eval_context_ref(); let instance = this.resolve_path(path, Namespace::ValueNS); // We don't give a span -- this isn't actually used directly by the program anyway. let const_val = this.eval_global(instance).unwrap_or_else(|err| { panic!("failed to evaluate required Rust item: {path:?}\n{err:?}") }); - this.read_scalar(&const_val) + const_val.into() + } + fn eval_path_scalar(&self, path: &[&str]) -> Scalar { + let this = self.eval_context_ref(); + let val = this.eval_path(path); + this.read_scalar(&val) .unwrap_or_else(|err| panic!("failed to read required Rust item: {path:?}\n{err:?}")) } @@ -1067,20 +1072,18 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { crate_name == "std" || crate_name == "std_miri_test" } - /// Handler that should be called when unsupported functionality is encountered. + /// Handler that should be called when an unsupported foreign item is encountered. /// This function will either panic within the context of the emulated application /// or return an error in the Miri process context - /// - /// Return value of `Ok(bool)` indicates whether execution should continue. - fn handle_unsupported>(&mut self, error_msg: S) -> InterpResult<'tcx, ()> { + fn handle_unsupported_foreign_item(&mut self, error_msg: String) -> InterpResult<'tcx, ()> { let this = self.eval_context_mut(); if this.machine.panic_on_unsupported { // message is slightly different here to make automated analysis easier - let error_msg = format!("unsupported Miri functionality: {}", error_msg.as_ref()); + let error_msg = format!("unsupported Miri functionality: {error_msg}"); this.start_panic(error_msg.as_ref(), mir::UnwindAction::Continue)?; Ok(()) } else { - throw_unsup_format!("{}", error_msg.as_ref()); + throw_machine_stop!(TerminationInfo::UnsupportedForeignItem(error_msg)); } } diff --git a/src/tools/miri/src/shims/intrinsics/atomic.rs b/src/tools/miri/src/intrinsics/atomic.rs similarity index 98% rename from src/tools/miri/src/shims/intrinsics/atomic.rs rename to src/tools/miri/src/intrinsics/atomic.rs index 865886a7fc151..40f6b8a64efad 100644 --- a/src/tools/miri/src/shims/intrinsics/atomic.rs +++ b/src/tools/miri/src/intrinsics/atomic.rs @@ -14,12 +14,13 @@ pub enum AtomicOp { impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { /// Calls the atomic intrinsic `intrinsic`; the `atomic_` prefix has already been removed. + /// Returns `Ok(true)` if the intrinsic was handled. fn emulate_atomic_intrinsic( &mut self, intrinsic_name: &str, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); let intrinsic_structure: Vec<_> = intrinsic_name.split('_').collect(); @@ -113,9 +114,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { this.atomic_rmw_op(args, dest, AtomicOp::Max, rw_ord(ord)?)?; } - _ => throw_unsup_format!("unimplemented intrinsic: `atomic_{intrinsic_name}`"), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(()) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs similarity index 83% rename from src/tools/miri/src/shims/intrinsics/mod.rs rename to src/tools/miri/src/intrinsics/mod.rs index d16d5d99e9c01..effd7f6d5435f 100644 --- a/src/tools/miri/src/shims/intrinsics/mod.rs +++ b/src/tools/miri/src/intrinsics/mod.rs @@ -10,6 +10,7 @@ use rustc_middle::{ mir, ty::{self, FloatTy}, }; +use rustc_span::{sym, Symbol}; use rustc_target::abi::Size; use crate::*; @@ -26,54 +27,60 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { dest: &MPlaceTy<'tcx, Provenance>, ret: Option, _unwind: mir::UnwindAction, - ) -> InterpResult<'tcx> { + ) -> InterpResult<'tcx, Option>> { let this = self.eval_context_mut(); // See if the core engine can handle this intrinsic. if this.emulate_intrinsic(instance, args, dest, ret)? { - return Ok(()); + return Ok(None); } let intrinsic_name = this.tcx.item_name(instance.def_id()); let intrinsic_name = intrinsic_name.as_str(); - // Handle intrinsics without return place. - match intrinsic_name { - "abort" => { - throw_machine_stop!(TerminationInfo::Abort( - "the program aborted execution".to_owned() - )) + match this.emulate_intrinsic_by_name(intrinsic_name, instance.args, args, dest, ret)? { + EmulateItemResult::NotSupported => { + // We haven't handled the intrinsic, let's see if we can use a fallback body. + if this.tcx.intrinsic(instance.def_id()).unwrap().must_be_overridden { + throw_unsup_format!("unimplemented intrinsic: `{intrinsic_name}`") + } + let intrinsic_fallback_checks_ub = Symbol::intern("intrinsic_fallback_checks_ub"); + if this + .tcx + .get_attrs_by_path( + instance.def_id(), + &[sym::miri, intrinsic_fallback_checks_ub], + ) + .next() + .is_none() + { + throw_unsup_format!( + "miri can only use intrinsic fallback bodies that check UB. After verifying that `{intrinsic_name}` does so, add the `#[miri::intrinsic_fallback_checks_ub]` attribute to it; also ping @rust-lang/miri when you do that" + ); + } + Ok(Some(ty::Instance { + def: ty::InstanceDef::Item(instance.def_id()), + args: instance.args, + })) } - _ => {} - } - - // All remaining supported intrinsics have a return place. - let ret = match ret { - None => throw_unsup_format!("unimplemented (diverging) intrinsic: `{intrinsic_name}`"), - Some(p) => p, - }; - - // Some intrinsics are special and need the "ret". - match intrinsic_name { - "catch_unwind" => return this.handle_catch_unwind(args, dest, ret), - _ => {} + EmulateItemResult::NeedsJumping => { + trace!("{:?}", this.dump_place(&dest.clone().into())); + this.return_to_block(ret)?; + Ok(None) + } + EmulateItemResult::AlreadyJumped => Ok(None), } - - // The rest jumps to `ret` immediately. - this.emulate_intrinsic_by_name(intrinsic_name, instance.args, args, dest)?; - - trace!("{:?}", this.dump_place(&dest.clone().into())); - this.go_to_block(ret); - Ok(()) } /// Emulates a Miri-supported intrinsic (not supported by the core engine). + /// Returns `Ok(true)` if the intrinsic was handled. fn emulate_intrinsic_by_name( &mut self, intrinsic_name: &str, generic_args: ty::GenericArgsRef<'tcx>, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx> { + ret: Option, + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); if let Some(name) = intrinsic_name.strip_prefix("atomic_") { @@ -84,22 +91,16 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } match intrinsic_name { - // Miri overwriting CTFE intrinsics. - "ptr_guaranteed_cmp" => { - let [left, right] = check_arg_count(args)?; - let left = this.read_immediate(left)?; - let right = this.read_immediate(right)?; - let val = this.wrapping_binary_op(mir::BinOp::Eq, &left, &right)?; - // We're type punning a bool as an u8 here. - this.write_scalar(val.to_scalar(), dest)?; - } - "const_allocate" => { - // For now, for compatibility with the run-time implementation of this, we just return null. - // See . - this.write_null(dest)?; + // Basic control flow + "abort" => { + throw_machine_stop!(TerminationInfo::Abort( + "the program aborted execution".to_owned() + )); } - "const_deallocate" => { - // complete NOP + "catch_unwind" => { + this.handle_catch_unwind(args, dest, ret)?; + // This pushed a stack frame, don't jump to `ret`. + return Ok(EmulateItemResult::AlreadyJumped); } // Raw memory accesses @@ -193,12 +194,12 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { => { let [f] = check_arg_count(args)?; let f = this.read_scalar(f)?.to_f32()?; - // FIXME: Using host floats. + // Using host floats (but it's fine, these operations do not have guaranteed precision). let f_host = f.to_host(); let res = match intrinsic_name { "sinf32" => f_host.sin(), "cosf32" => f_host.cos(), - "sqrtf32" => f_host.sqrt(), + "sqrtf32" => f_host.sqrt(), // FIXME Using host floats, this should use full-precision soft-floats "expf32" => f_host.exp(), "exp2f32" => f_host.exp2(), "logf32" => f_host.ln(), @@ -238,12 +239,12 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { => { let [f] = check_arg_count(args)?; let f = this.read_scalar(f)?.to_f64()?; - // FIXME: Using host floats. + // Using host floats (but it's fine, these operations do not have guaranteed precision). let f_host = f.to_host(); let res = match intrinsic_name { "sinf64" => f_host.sin(), "cosf64" => f_host.cos(), - "sqrtf64" => f_host.sqrt(), + "sqrtf64" => f_host.sqrt(), // FIXME Using host floats, this should use full-precision soft-floats "expf64" => f_host.exp(), "exp2f64" => f_host.exp2(), "logf64" => f_host.ln(), @@ -366,7 +367,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let [f1, f2] = check_arg_count(args)?; let f1 = this.read_scalar(f1)?.to_f32()?; let f2 = this.read_scalar(f2)?.to_f32()?; - // FIXME: Using host floats. + // Using host floats (but it's fine, this operation does not have guaranteed precision). let res = f1.to_host().powf(f2.to_host()).to_soft(); let res = this.adjust_nan(res, &[f1, f2]); this.write_scalar(res, dest)?; @@ -376,7 +377,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let [f1, f2] = check_arg_count(args)?; let f1 = this.read_scalar(f1)?.to_f64()?; let f2 = this.read_scalar(f2)?.to_f64()?; - // FIXME: Using host floats. + // Using host floats (but it's fine, this operation does not have guaranteed precision). let res = f1.to_host().powf(f2.to_host()).to_soft(); let res = this.adjust_nan(res, &[f1, f2]); this.write_scalar(res, dest)?; @@ -386,7 +387,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let [f, i] = check_arg_count(args)?; let f = this.read_scalar(f)?.to_f32()?; let i = this.read_scalar(i)?.to_i32()?; - // FIXME: Using host floats. + // Using host floats (but it's fine, this operation does not have guaranteed precision). let res = f.to_host().powi(i).to_soft(); let res = this.adjust_nan(res, &[f]); this.write_scalar(res, dest)?; @@ -396,7 +397,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let [f, i] = check_arg_count(args)?; let f = this.read_scalar(f)?.to_f64()?; let i = this.read_scalar(i)?.to_i32()?; - // FIXME: Using host floats. + // Using host floats (but it's fine, this operation does not have guaranteed precision). let res = f.to_host().powi(i).to_soft(); let res = this.adjust_nan(res, &[f]); this.write_scalar(res, dest)?; @@ -425,9 +426,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { throw_machine_stop!(TerminationInfo::Abort(format!("trace/breakpoint trap"))) } - name => throw_unsup_format!("unimplemented intrinsic: `{name}`"), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(()) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/intrinsics/simd.rs b/src/tools/miri/src/intrinsics/simd.rs similarity index 98% rename from src/tools/miri/src/shims/intrinsics/simd.rs rename to src/tools/miri/src/intrinsics/simd.rs index 9a0671430d438..3be98d7f5f864 100644 --- a/src/tools/miri/src/shims/intrinsics/simd.rs +++ b/src/tools/miri/src/intrinsics/simd.rs @@ -16,13 +16,14 @@ pub(crate) enum MinMax { impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { /// Calls the simd intrinsic `intrinsic`; the `simd_` prefix has already been removed. + /// Returns `Ok(true)` if the intrinsic was handled. fn emulate_simd_intrinsic( &mut self, intrinsic_name: &str, generic_args: ty::GenericArgsRef<'tcx>, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); match intrinsic_name { #[rustfmt::skip] @@ -99,14 +100,14 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let ty::Float(float_ty) = op.layout.ty.kind() else { span_bug!(this.cur_span(), "{} operand is not a float", intrinsic_name) }; - // FIXME using host floats + // Using host floats (but it's fine, these operations do not have guaranteed precision). match float_ty { FloatTy::F16 => unimplemented!("f16_f128"), FloatTy::F32 => { let f = op.to_scalar().to_f32()?; let f_host = f.to_host(); let res = match host_op { - "fsqrt" => f_host.sqrt(), + "fsqrt" => f_host.sqrt(), // FIXME Using host floats, this should use full-precision soft-floats "fsin" => f_host.sin(), "fcos" => f_host.cos(), "fexp" => f_host.exp(), @@ -743,9 +744,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } } - name => throw_unsup_format!("unimplemented intrinsic: `simd_{name}`"), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(()) + Ok(EmulateItemResult::NeedsJumping) } fn fminmax_op( diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs index f47c84842b17f..1680b98eca33f 100644 --- a/src/tools/miri/src/lib.rs +++ b/src/tools/miri/src/lib.rs @@ -79,6 +79,7 @@ mod concurrency; mod diagnostics; mod eval; mod helpers; +mod intrinsics; mod machine; mod mono_hash_map; mod operator; @@ -95,13 +96,14 @@ pub use rustc_const_eval::interpret::*; #[doc(no_inline)] pub use rustc_const_eval::interpret::{self, AllocMap, PlaceTy, Provenance as _}; +pub use crate::intrinsics::EvalContextExt as _; pub use crate::shims::env::{EnvVars, EvalContextExt as _}; pub use crate::shims::foreign_items::{DynSym, EvalContextExt as _}; -pub use crate::shims::intrinsics::EvalContextExt as _; pub use crate::shims::os_str::EvalContextExt as _; pub use crate::shims::panic::{CatchUnwindData, EvalContextExt as _}; pub use crate::shims::time::EvalContextExt as _; pub use crate::shims::tls::TlsData; +pub use crate::shims::EmulateItemResult; pub use crate::alloc_addresses::{EvalContextExt as _, ProvenanceMode}; pub use crate::borrow_tracker::stacked_borrows::{ diff --git a/src/tools/miri/src/machine.rs b/src/tools/miri/src/machine.rs index 4dacb6db8da94..51b96bff5fefc 100644 --- a/src/tools/miri/src/machine.rs +++ b/src/tools/miri/src/machine.rs @@ -986,7 +986,7 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> { dest: &MPlaceTy<'tcx, Provenance>, ret: Option, unwind: mir::UnwindAction, - ) -> InterpResult<'tcx> { + ) -> InterpResult<'tcx, Option>> { ecx.call_intrinsic(instance, args, dest, ret, unwind) } diff --git a/src/tools/miri/src/shims/alloc.rs b/src/tools/miri/src/shims/alloc.rs index b5ae06c2a492a..79531598c003a 100644 --- a/src/tools/miri/src/shims/alloc.rs +++ b/src/tools/miri/src/shims/alloc.rs @@ -4,7 +4,6 @@ use rustc_ast::expand::allocator::AllocatorKind; use rustc_target::abi::{Align, Size}; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; /// Check some basic requirements for this allocation request: /// non-zero size, power-of-two alignment. @@ -55,12 +54,12 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { fn emulate_allocator( &mut self, default: impl FnOnce(&mut MiriInterpCx<'mir, 'tcx>) -> InterpResult<'tcx>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); let Some(allocator_kind) = this.tcx.allocator_kind(()) else { // in real code, this symbol does not exist without an allocator - return Ok(EmulateForeignItemResult::NotSupported); + return Ok(EmulateItemResult::NotSupported); }; match allocator_kind { @@ -70,11 +69,11 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { // and not execute any Miri shim. Somewhat unintuitively doing so is done // by returning `NotSupported`, which triggers the `lookup_exported_symbol` // fallback case in `emulate_foreign_item`. - return Ok(EmulateForeignItemResult::NotSupported); + return Ok(EmulateItemResult::NotSupported); } AllocatorKind::Default => { default(this)?; - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } } diff --git a/src/tools/miri/src/shims/env.rs b/src/tools/miri/src/shims/env.rs index fc0160fdf2117..695d1138756ca 100644 --- a/src/tools/miri/src/shims/env.rs +++ b/src/tools/miri/src/shims/env.rs @@ -1,4 +1,4 @@ -use std::ffi::OsString; +use std::ffi::{OsStr, OsString}; use rustc_data_structures::fx::FxHashMap; @@ -99,4 +99,15 @@ impl<'tcx> EnvVars<'tcx> { } impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} -pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {} +pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { + /// Try to get an environment variable from the interpreted program's environment. This is + /// useful for implementing shims which are documented to read from the environment. + fn get_env_var(&mut self, name: &OsStr) -> InterpResult<'tcx, Option> { + let this = self.eval_context_ref(); + match &this.machine.env_vars { + EnvVars::Uninit => return Ok(None), + EnvVars::Unix(vars) => vars.get(this, name), + EnvVars::Windows(vars) => vars.get(name), + } + } +} diff --git a/src/tools/miri/src/shims/extern_static.rs b/src/tools/miri/src/shims/extern_static.rs index 442338a6117d8..c3c7ef7c1fd8e 100644 --- a/src/tools/miri/src/shims/extern_static.rs +++ b/src/tools/miri/src/shims/extern_static.rs @@ -16,8 +16,8 @@ impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> { /// Zero-initialized pointer-sized extern statics are pretty common. /// Most of them are for weak symbols, which we all set to null (indicating that the - /// symbol is not supported, and triggering fallback code which ends up calling a - /// syscall that we do support). + /// symbol is not supported, and triggering fallback code which ends up calling + /// some other shim that we do support). fn null_ptr_extern_statics( this: &mut MiriInterpCx<'mir, 'tcx>, names: &[&str], @@ -29,6 +29,21 @@ impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> { Ok(()) } + /// Extern statics that are initialized with function pointers to the symbols of the same name. + fn weak_symbol_extern_statics( + this: &mut MiriInterpCx<'mir, 'tcx>, + names: &[&str], + ) -> InterpResult<'tcx> { + for name in names { + assert!(this.is_dyn_sym(name), "{name} is not a dynamic symbol"); + let layout = this.machine.layouts.const_raw_ptr; + let ptr = this.fn_ptr(FnVal::Other(DynSym::from_str(name))); + let val = ImmTy::from_scalar(Scalar::from_pointer(ptr, this), layout); + Self::alloc_extern_static(this, name, val)?; + } + Ok(()) + } + /// Sets up the "extern statics" for this machine. pub fn init_extern_statics(this: &mut MiriInterpCx<'mir, 'tcx>) -> InterpResult<'tcx> { // "__rust_no_alloc_shim_is_unstable" @@ -44,8 +59,9 @@ impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> { "linux" => { Self::null_ptr_extern_statics( this, - &["__cxa_thread_atexit_impl", "getrandom", "statx", "__clock_gettime64"], + &["__cxa_thread_atexit_impl", "__clock_gettime64"], )?; + Self::weak_symbol_extern_statics(this, &["getrandom", "statx"])?; // "environ" let environ = this.machine.env_vars.unix().environ(); Self::add_extern_static(this, "environ", environ); @@ -58,12 +74,7 @@ impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> { } "android" => { Self::null_ptr_extern_statics(this, &["bsd_signal"])?; - // "signal" -- just needs a non-zero pointer value (function does not even get called), - // but we arrange for this to call the `signal` function anyway. - let layout = this.machine.layouts.const_raw_ptr; - let ptr = this.fn_ptr(FnVal::Other(DynSym::from_str("signal"))); - let val = ImmTy::from_scalar(Scalar::from_pointer(ptr, this), layout); - Self::alloc_extern_static(this, "signal", val)?; + Self::weak_symbol_extern_statics(this, &["signal"])?; } "windows" => { // "_tls_used" diff --git a/src/tools/miri/src/shims/foreign_items.rs b/src/tools/miri/src/shims/foreign_items.rs index 636361148a469..c51a27b7458a8 100644 --- a/src/tools/miri/src/shims/foreign_items.rs +++ b/src/tools/miri/src/shims/foreign_items.rs @@ -28,16 +28,6 @@ impl DynSym { } } -/// Returned by `emulate_foreign_item_inner`. -pub enum EmulateForeignItemResult { - /// The caller is expected to jump to the return block. - NeedsJumping, - /// Jumping has already been taken care of. - AlreadyJumped, - /// The item is not supported. - NotSupported, -} - impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { /// Emulates calling a foreign item, failing if the item is not supported. @@ -58,89 +48,52 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let this = self.eval_context_mut(); let tcx = this.tcx.tcx; - // First: functions that diverge. - let ret = match ret { - None => - match link_name.as_str() { - "miri_start_unwind" => { - // `check_shim` happens inside `handle_miri_start_unwind`. - this.handle_miri_start_unwind(abi, link_name, args, unwind)?; - return Ok(None); - } - // This matches calls to the foreign item `panic_impl`. - // The implementation is provided by the function with the `#[panic_handler]` attribute. - "panic_impl" => { - // We don't use `check_shim` here because we are just forwarding to the lang - // item. Argument count checking will be performed when the returned `Body` is - // called. - this.check_abi_and_shim_symbol_clash(abi, Abi::Rust, link_name)?; - let panic_impl_id = tcx.lang_items().panic_impl().unwrap(); - let panic_impl_instance = ty::Instance::mono(tcx, panic_impl_id); - return Ok(Some(( - this.load_mir(panic_impl_instance.def, None)?, - panic_impl_instance, - ))); - } - "__rust_alloc_error_handler" => { - // Forward to the right symbol that implements this function. - let Some(handler_kind) = this.tcx.alloc_error_handler_kind(()) else { - // in real code, this symbol does not exist without an allocator - throw_unsup_format!( - "`__rust_alloc_error_handler` cannot be called when no alloc error handler is set" - ); - }; - let name = alloc_error_handler_name(handler_kind); - let handler = this - .lookup_exported_symbol(Symbol::intern(name))? - .expect("missing alloc error handler symbol"); - return Ok(Some(handler)); - } - #[rustfmt::skip] - | "exit" - | "ExitProcess" - => { - let exp_abi = if link_name.as_str() == "exit" { - Abi::C { unwind: false } - } else { - Abi::System { unwind: false } - }; - let [code] = this.check_shim(abi, exp_abi, link_name, args)?; - // it's really u32 for ExitProcess, but we have to put it into the `Exit` variant anyway - let code = this.read_scalar(code)?.to_i32()?; - throw_machine_stop!(TerminationInfo::Exit { code: code.into(), leak_check: false }); - } - "abort" => { - let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; - throw_machine_stop!(TerminationInfo::Abort( - "the program aborted execution".to_owned() - )) - } - _ => { - if let Some(body) = this.lookup_exported_symbol(link_name)? { - return Ok(Some(body)); - } - this.handle_unsupported(format!( - "can't call (diverging) foreign function: {link_name}" - ))?; - return Ok(None); - } - }, - Some(p) => p, - }; + // Some shims forward to other MIR bodies. + match link_name.as_str() { + // This matches calls to the foreign item `panic_impl`. + // The implementation is provided by the function with the `#[panic_handler]` attribute. + "panic_impl" => { + // We don't use `check_shim` here because we are just forwarding to the lang + // item. Argument count checking will be performed when the returned `Body` is + // called. + this.check_abi_and_shim_symbol_clash(abi, Abi::Rust, link_name)?; + let panic_impl_id = tcx.lang_items().panic_impl().unwrap(); + let panic_impl_instance = ty::Instance::mono(tcx, panic_impl_id); + return Ok(Some(( + this.load_mir(panic_impl_instance.def, None)?, + panic_impl_instance, + ))); + } + "__rust_alloc_error_handler" => { + // Forward to the right symbol that implements this function. + let Some(handler_kind) = this.tcx.alloc_error_handler_kind(()) else { + // in real code, this symbol does not exist without an allocator + throw_unsup_format!( + "`__rust_alloc_error_handler` cannot be called when no alloc error handler is set" + ); + }; + let name = alloc_error_handler_name(handler_kind); + let handler = this + .lookup_exported_symbol(Symbol::intern(name))? + .expect("missing alloc error handler symbol"); + return Ok(Some(handler)); + } + _ => {} + } - // Second: functions that return immediately. - match this.emulate_foreign_item_inner(link_name, abi, args, dest)? { - EmulateForeignItemResult::NeedsJumping => { + // The rest either implements the logic, or falls back to `lookup_exported_symbol`. + match this.emulate_foreign_item_inner(link_name, abi, args, dest, unwind)? { + EmulateItemResult::NeedsJumping => { trace!("{:?}", this.dump_place(&dest.clone().into())); - this.go_to_block(ret); + this.return_to_block(ret)?; } - EmulateForeignItemResult::AlreadyJumped => (), - EmulateForeignItemResult::NotSupported => { + EmulateItemResult::AlreadyJumped => (), + EmulateItemResult::NotSupported => { if let Some(body) = this.lookup_exported_symbol(link_name)? { return Ok(Some(body)); } - this.handle_unsupported(format!( + this.handle_unsupported_foreign_item(format!( "can't call foreign function `{link_name}` on OS `{os}`", os = this.tcx.sess.target.os, ))?; @@ -151,6 +104,15 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { Ok(None) } + fn is_dyn_sym(&self, name: &str) -> bool { + let this = self.eval_context_ref(); + match this.tcx.sess.target.os.as_ref() { + os if this.target_os_is_unix() => shims::unix::foreign_items::is_dyn_sym(name, os), + "windows" => shims::windows::foreign_items::is_dyn_sym(name), + _ => false, + } + } + /// Emulates a call to a `DynSym`. fn emulate_dyn_sym( &mut self, @@ -243,7 +205,8 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + unwind: mir::UnwindAction, + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); // First deal with any external C functions in linked .so file. @@ -254,7 +217,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { // by the specified `.so` file; we should continue and check if it corresponds to // a provided shim. if this.call_external_c_fct(link_name, dest, args)? { - return Ok(EmulateForeignItemResult::NeedsJumping); + return Ok(EmulateItemResult::NeedsJumping); } } @@ -298,6 +261,11 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { // shim, add it to the corresponding submodule. match link_name.as_str() { // Miri-specific extern functions + "miri_start_unwind" => { + // `check_shim` happens inside `handle_miri_start_unwind`. + this.handle_miri_start_unwind(abi, link_name, args, unwind)?; + return Ok(EmulateItemResult::AlreadyJumped); + } "miri_run_provenance_gc" => { let [] = this.check_shim(abi, Abi::Rust, link_name, args)?; this.run_provenance_gc(); @@ -362,29 +330,24 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { // Return value: 0 on success, otherwise the size it would have needed. this.write_int(if success { 0 } else { needed_size }, dest)?; } - // Obtains the size of a Miri backtrace. See the README for details. "miri_backtrace_size" => { this.handle_miri_backtrace_size(abi, link_name, args, dest)?; } - // Obtains a Miri backtrace. See the README for details. "miri_get_backtrace" => { // `check_shim` happens inside `handle_miri_get_backtrace`. this.handle_miri_get_backtrace(abi, link_name, args, dest)?; } - // Resolves a Miri backtrace frame. See the README for details. "miri_resolve_frame" => { // `check_shim` happens inside `handle_miri_resolve_frame`. this.handle_miri_resolve_frame(abi, link_name, args, dest)?; } - // Writes the function and file names of a Miri backtrace frame into a user provided buffer. See the README for details. "miri_resolve_frame_names" => { this.handle_miri_resolve_frame_names(abi, link_name, args)?; } - // Writes some bytes to the interpreter's stdout/stderr. See the // README for details. "miri_write_to_stdout" | "miri_write_to_stderr" => { @@ -398,7 +361,6 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { _ => unreachable!(), }; } - // Promises that a pointer has a given symbolic alignment. "miri_promise_symbolic_alignment" => { use rustc_target::abi::AlignFromBytesError; @@ -442,6 +404,19 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } } + // Aborting the process. + "exit" => { + let [code] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; + let code = this.read_scalar(code)?.to_i32()?; + throw_machine_stop!(TerminationInfo::Exit { code: code.into(), leak_check: false }); + } + "abort" => { + let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; + throw_machine_stop!(TerminationInfo::Abort( + "the program aborted execution".to_owned() + )) + } + // Standard C allocation "malloc" => { let [size] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; @@ -504,7 +479,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { "__rust_alloc" => return this.emulate_allocator(default), "miri_alloc" => { default(this)?; - return Ok(EmulateForeignItemResult::NeedsJumping); + return Ok(EmulateItemResult::NeedsJumping); } _ => unreachable!(), } @@ -564,7 +539,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } "miri_dealloc" => { default(this)?; - return Ok(EmulateForeignItemResult::NeedsJumping); + return Ok(EmulateItemResult::NeedsJumping); } _ => unreachable!(), } @@ -730,7 +705,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { => { let [f] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; let f = this.read_scalar(f)?.to_f32()?; - // FIXME: Using host floats. + // Using host floats (but it's fine, these operations do not have guaranteed precision). let f_host = f.to_host(); let res = match link_name.as_str() { "cbrtf" => f_host.cbrt(), @@ -761,7 +736,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let f2 = this.read_scalar(f2)?.to_f32()?; // underscore case for windows, here and below // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019) - // FIXME: Using host floats. + // Using host floats (but it's fine, these operations do not have guaranteed precision). let res = match link_name.as_str() { "_hypotf" | "hypotf" => f1.to_host().hypot(f2.to_host()).to_soft(), "atan2f" => f1.to_host().atan2(f2.to_host()).to_soft(), @@ -787,7 +762,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { => { let [f] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; let f = this.read_scalar(f)?.to_f64()?; - // FIXME: Using host floats. + // Using host floats (but it's fine, these operations do not have guaranteed precision). let f_host = f.to_host(); let res = match link_name.as_str() { "cbrt" => f_host.cbrt(), @@ -818,7 +793,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let f2 = this.read_scalar(f2)?.to_f64()?; // underscore case for windows, here and below // (see https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/floating-point-primitives?view=vs-2019) - // FIXME: Using host floats. + // Using host floats (but it's fine, these operations do not have guaranteed precision). let res = match link_name.as_str() { "_hypot" | "hypot" => f1.to_host().hypot(f2.to_host()).to_soft(), "atan2" => f1.to_host().atan2(f2.to_host()).to_soft(), @@ -848,7 +823,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let x = this.read_scalar(x)?.to_f32()?; let signp = this.deref_pointer(signp)?; - // FIXME: Using host floats. + // Using host floats (but it's fine, these operations do not have guaranteed precision). let (res, sign) = x.to_host().ln_gamma(); this.write_int(sign, &signp)?; let res = this.adjust_nan(res.to_soft(), &[x]); @@ -859,7 +834,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let x = this.read_scalar(x)?.to_f64()?; let signp = this.deref_pointer(signp)?; - // FIXME: Using host floats. + // Using host floats (but it's fine, these operations do not have guaranteed precision). let (res, sign) = x.to_host().ln_gamma(); this.write_int(sign, &signp)?; let res = this.adjust_nan(res.to_soft(), &[x]); @@ -893,36 +868,6 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { throw_unsup_format!("unsupported `llvm.prefetch` type argument: {}", ty); } } - // FIXME: Move these to an `arm` submodule. - "llvm.aarch64.isb" if this.tcx.sess.target.arch == "aarch64" => { - let [arg] = this.check_shim(abi, Abi::Unadjusted, link_name, args)?; - let arg = this.read_scalar(arg)?.to_i32()?; - match arg { - // SY ("full system scope") - 15 => { - this.yield_active_thread(); - } - _ => { - throw_unsup_format!("unsupported llvm.aarch64.isb argument {}", arg); - } - } - } - "llvm.arm.hint" if this.tcx.sess.target.arch == "arm" => { - let [arg] = this.check_shim(abi, Abi::Unadjusted, link_name, args)?; - let arg = this.read_scalar(arg)?.to_i32()?; - // Note that different arguments might have different target feature requirements. - match arg { - // YIELD - 1 => { - this.expect_target_feature_for_intrinsic(link_name, "v6")?; - this.yield_active_thread(); - } - _ => { - throw_unsup_format!("unsupported llvm.arm.hint argument {}", arg); - } - } - } - // Used to implement the x86 `_mm{,256,512}_popcnt_epi{8,16,32,64}` and wasm // `{i,u}8x16_popcnt` functions. name if name.starts_with("llvm.ctpop.v") => { @@ -946,6 +891,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } } + // Target-specific shims name if name.starts_with("llvm.x86.") && (this.tcx.sess.target.arch == "x86" || this.tcx.sess.target.arch == "x86_64") => @@ -954,6 +900,35 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { this, link_name, abi, args, dest, ); } + // FIXME: Move these to an `arm` submodule. + "llvm.aarch64.isb" if this.tcx.sess.target.arch == "aarch64" => { + let [arg] = this.check_shim(abi, Abi::Unadjusted, link_name, args)?; + let arg = this.read_scalar(arg)?.to_i32()?; + match arg { + // SY ("full system scope") + 15 => { + this.yield_active_thread(); + } + _ => { + throw_unsup_format!("unsupported llvm.aarch64.isb argument {}", arg); + } + } + } + "llvm.arm.hint" if this.tcx.sess.target.arch == "arm" => { + let [arg] = this.check_shim(abi, Abi::Unadjusted, link_name, args)?; + let arg = this.read_scalar(arg)?.to_i32()?; + // Note that different arguments might have different target feature requirements. + match arg { + // YIELD + 1 => { + this.expect_target_feature_for_intrinsic(link_name, "v6")?; + this.yield_active_thread(); + } + _ => { + throw_unsup_format!("unsupported llvm.arm.hint argument {}", arg); + } + } + } // Platform-specific shims _ => @@ -966,11 +941,11 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { shims::windows::foreign_items::EvalContextExt::emulate_foreign_item_inner( this, link_name, abi, args, dest, ), - _ => Ok(EmulateForeignItemResult::NotSupported), + _ => Ok(EmulateItemResult::NotSupported), }, }; // We only fall through to here if we did *not* hit the `_` arm above, // i.e., if we actually emulated the function with one of the shims. - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/mod.rs b/src/tools/miri/src/shims/mod.rs index 85c9a202f7daf..11048459206bf 100644 --- a/src/tools/miri/src/shims/mod.rs +++ b/src/tools/miri/src/shims/mod.rs @@ -5,7 +5,6 @@ mod backtrace; #[cfg(target_os = "linux")] pub mod ffi_support; pub mod foreign_items; -pub mod intrinsics; pub mod unix; pub mod windows; mod x86; @@ -16,3 +15,13 @@ pub mod os_str; pub mod panic; pub mod time; pub mod tls; + +/// What needs to be done after emulating an item (a shim or an intrinsic) is done. +pub enum EmulateItemResult { + /// The caller is expected to jump to the return block. + NeedsJumping, + /// Jumping has already been taken care of. + AlreadyJumped, + /// The item is not supported. + NotSupported, +} diff --git a/src/tools/miri/src/shims/panic.rs b/src/tools/miri/src/shims/panic.rs index bb31ef733cf94..4444d297469fb 100644 --- a/src/tools/miri/src/shims/panic.rs +++ b/src/tools/miri/src/shims/panic.rs @@ -30,7 +30,7 @@ pub struct CatchUnwindData<'tcx> { /// The return place from the original call to `try`. dest: MPlaceTy<'tcx, Provenance>, /// The return block from the original call to `try`. - ret: mir::BasicBlock, + ret: Option, } impl VisitProvenance for CatchUnwindData<'_> { @@ -73,7 +73,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { &mut self, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ret: mir::BasicBlock, + ret: Option, ) -> InterpResult<'tcx> { let this = self.eval_context_mut(); @@ -103,7 +103,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { &[data.into()], None, // Directly return to caller. - StackPopCleanup::Goto { ret: Some(ret), unwind: mir::UnwindAction::Continue }, + StackPopCleanup::Goto { ret, unwind: mir::UnwindAction::Continue }, )?; // We ourselves will return `0`, eventually (will be overwritten if we catch a panic). @@ -155,7 +155,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { None, // Directly return to caller of `try`. StackPopCleanup::Goto { - ret: Some(catch_unwind.ret), + ret: catch_unwind.ret, unwind: mir::UnwindAction::Continue, }, )?; diff --git a/src/tools/miri/src/shims/time.rs b/src/tools/miri/src/shims/time.rs index dfdf58470d63a..8d1f07f916c9b 100644 --- a/src/tools/miri/src/shims/time.rs +++ b/src/tools/miri/src/shims/time.rs @@ -1,8 +1,10 @@ -use std::ffi::OsString; +use std::ffi::{OsStr, OsString}; use std::fmt::Write; +use std::str::FromStr; use std::time::{Duration, SystemTime}; -use chrono::{DateTime, Datelike, Local, Timelike, Utc}; +use chrono::{DateTime, Datelike, Offset, Timelike, Utc}; +use chrono_tz::Tz; use crate::concurrency::thread::MachineCallback; use crate::*; @@ -136,8 +138,16 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { .unwrap(); let dt_utc: DateTime = DateTime::from_timestamp(sec_since_epoch, 0).expect("Invalid timestamp"); + + // Figure out what time zone is in use + let tz = this.get_env_var(OsStr::new("TZ"))?.unwrap_or_else(|| OsString::from("UTC")); + let tz = match tz.into_string() { + Ok(tz) => Tz::from_str(&tz).unwrap_or(Tz::UTC), + _ => Tz::UTC, + }; + // Convert that to local time, then return the broken-down time value. - let dt: DateTime = DateTime::from(dt_utc); + let dt: DateTime = dt_utc.with_timezone(&tz); // This value is always set to -1, because there is no way to know if dst is in effect with // chrono crate yet. @@ -146,17 +156,17 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { // tm_zone represents the timezone value in the form of: +0730, +08, -0730 or -08. // This may not be consistent with libc::localtime_r's result. - let offset_in_second = Local::now().offset().local_minus_utc(); - let tm_gmtoff = offset_in_second; + let offset_in_seconds = dt.offset().fix().local_minus_utc(); + let tm_gmtoff = offset_in_seconds; let mut tm_zone = String::new(); - if offset_in_second < 0 { + if offset_in_seconds < 0 { tm_zone.push('-'); } else { tm_zone.push('+'); } - let offset_hour = offset_in_second.abs() / 3600; + let offset_hour = offset_in_seconds.abs() / 3600; write!(tm_zone, "{:02}", offset_hour).unwrap(); - let offset_min = (offset_in_second.abs() % 3600) / 60; + let offset_min = (offset_in_seconds.abs() % 3600) / 60; if offset_min != 0 { write!(tm_zone, "{:02}", offset_min).unwrap(); } diff --git a/src/tools/miri/src/shims/tls.rs b/src/tools/miri/src/shims/tls.rs index d25bae1cdc03f..0dec12f0b65f1 100644 --- a/src/tools/miri/src/shims/tls.rs +++ b/src/tools/miri/src/shims/tls.rs @@ -242,21 +242,21 @@ impl<'tcx> TlsDtorsState<'tcx> { match &mut self.0 { Init => { match this.tcx.sess.target.os.as_ref() { - "linux" | "freebsd" | "android" => { - // Run the pthread dtors. - break 'new_state PthreadDtors(Default::default()); - } "macos" => { // The macOS thread wide destructor runs "before any TLS slots get // freed", so do that first. this.schedule_macos_tls_dtor()?; - // When the stack is empty again, go on with the pthread dtors. + // When that destructor is done, go on with the pthread dtors. + break 'new_state PthreadDtors(Default::default()); + } + _ if this.target_os_is_unix() => { + // All other Unixes directly jump to running the pthread dtors. break 'new_state PthreadDtors(Default::default()); } "windows" => { // Determine which destructors to run. let dtors = this.lookup_windows_tls_dtors()?; - // And move to the final state. + // And move to the next state, that runs them. break 'new_state WindowsDtors(dtors); } _ => { diff --git a/src/tools/miri/src/shims/unix/env.rs b/src/tools/miri/src/shims/unix/env.rs index 128f0dcafa942..9082d13da8404 100644 --- a/src/tools/miri/src/shims/unix/env.rs +++ b/src/tools/miri/src/shims/unix/env.rs @@ -70,6 +70,41 @@ impl<'tcx> UnixEnvVars<'tcx> { pub(crate) fn environ(&self) -> Pointer> { self.environ.ptr() } + + fn get_ptr<'mir>( + &self, + ecx: &InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>, + name: &OsStr, + ) -> InterpResult<'tcx, Option>>> { + // We don't care about the value as we have the `map` to keep track of everything, + // but we do want to do this read so it shows up as a data race. + let _vars_ptr = ecx.read_pointer(&self.environ)?; + let Some(var_ptr) = self.map.get(name) else { + return Ok(None); + }; + // The offset is used to strip the "{name}=" part of the string. + let var_ptr = var_ptr.offset( + Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()), + ecx, + )?; + Ok(Some(var_ptr)) + } + + /// Implementation detail for [`InterpCx::get_env_var`]. This basically does `getenv`, complete + /// with the reads of the environment, but returns an [`OsString`] instead of a pointer. + pub(crate) fn get<'mir>( + &self, + ecx: &InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>, + name: &OsStr, + ) -> InterpResult<'tcx, Option> { + let var_ptr = self.get_ptr(ecx, name)?; + if let Some(ptr) = var_ptr { + let var = ecx.read_os_str_from_c_str(ptr)?; + Ok(Some(var.to_owned())) + } else { + Ok(None) + } + } } fn alloc_env_var<'mir, 'tcx>( @@ -116,19 +151,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let name_ptr = this.read_pointer(name_op)?; let name = this.read_os_str_from_c_str(name_ptr)?; - // We don't care about the value as we have the `map` to keep track of everything, - // but we do want to do this read so it shows up as a data race. - let _vars_ptr = this.read_pointer(&this.machine.env_vars.unix().environ)?; - Ok(match this.machine.env_vars.unix().map.get(name) { - Some(var_ptr) => { - // The offset is used to strip the "{name}=" part of the string. - var_ptr.offset( - Size::from_bytes(u64::try_from(name.len()).unwrap().checked_add(1).unwrap()), - this, - )? - } - None => Pointer::null(), - }) + let var_ptr = this.machine.env_vars.unix().get_ptr(this, name)?; + Ok(var_ptr.unwrap_or_else(Pointer::null)) } fn setenv( diff --git a/src/tools/miri/src/shims/unix/fd.rs b/src/tools/miri/src/shims/unix/fd.rs index a5fe38b902de8..e536b78d1c0bc 100644 --- a/src/tools/miri/src/shims/unix/fd.rs +++ b/src/tools/miri/src/shims/unix/fd.rs @@ -2,8 +2,10 @@ //! standard file descriptors (stdin/stdout/stderr). use std::any::Any; +use std::cell::{Ref, RefCell, RefMut}; use std::collections::BTreeMap; use std::io::{self, ErrorKind, IsTerminal, Read, SeekFrom, Write}; +use std::rc::Rc; use rustc_middle::ty::TyCtxt; use rustc_target::abi::Size; @@ -12,9 +14,10 @@ use crate::shims::unix::*; use crate::*; /// Represents an open file descriptor. -pub trait FileDescriptor: std::fmt::Debug + Any { +pub trait FileDescription: std::fmt::Debug + Any { fn name(&self) -> &'static str; + /// Reads as much as possible into the given buffer, and returns the number of bytes read. fn read<'tcx>( &mut self, _communicate_allowed: bool, @@ -24,8 +27,9 @@ pub trait FileDescriptor: std::fmt::Debug + Any { throw_unsup_format!("cannot read from {}", self.name()); } + /// Writes as much as possible from the given buffer, and returns the number of bytes written. fn write<'tcx>( - &self, + &mut self, _communicate_allowed: bool, _bytes: &[u8], _tcx: TyCtxt<'tcx>, @@ -33,6 +37,8 @@ pub trait FileDescriptor: std::fmt::Debug + Any { throw_unsup_format!("cannot write to {}", self.name()); } + /// Seeks to the given offset (which can be relative to the beginning, end, or current position). + /// Returns the new position from the start of the stream. fn seek<'tcx>( &mut self, _communicate_allowed: bool, @@ -44,13 +50,10 @@ pub trait FileDescriptor: std::fmt::Debug + Any { fn close<'tcx>( self: Box, _communicate_allowed: bool, - ) -> InterpResult<'tcx, io::Result> { + ) -> InterpResult<'tcx, io::Result<()>> { throw_unsup_format!("cannot close {}", self.name()); } - /// Return a new file descriptor *that refers to the same underlying object*. - fn dup(&mut self) -> io::Result>; - fn is_tty(&self, _communicate_allowed: bool) -> bool { // Most FDs are not tty's and the consequence of a wrong `false` are minor, // so we use a default impl here. @@ -58,7 +61,7 @@ pub trait FileDescriptor: std::fmt::Debug + Any { } } -impl dyn FileDescriptor { +impl dyn FileDescription { #[inline(always)] pub fn downcast_ref(&self) -> Option<&T> { (self as &dyn Any).downcast_ref() @@ -70,7 +73,7 @@ impl dyn FileDescriptor { } } -impl FileDescriptor for io::Stdin { +impl FileDescription for io::Stdin { fn name(&self) -> &'static str { "stdin" } @@ -88,28 +91,24 @@ impl FileDescriptor for io::Stdin { Ok(Read::read(self, bytes)) } - fn dup(&mut self) -> io::Result> { - Ok(Box::new(io::stdin())) - } - fn is_tty(&self, communicate_allowed: bool) -> bool { communicate_allowed && self.is_terminal() } } -impl FileDescriptor for io::Stdout { +impl FileDescription for io::Stdout { fn name(&self) -> &'static str { "stdout" } fn write<'tcx>( - &self, + &mut self, _communicate_allowed: bool, bytes: &[u8], _tcx: TyCtxt<'tcx>, ) -> InterpResult<'tcx, io::Result> { // We allow writing to stderr even with isolation enabled. - let result = Write::write(&mut { self }, bytes); + let result = Write::write(self, bytes); // Stdout is buffered, flush to make sure it appears on the // screen. This is the write() syscall of the interpreted // program, we want it to correspond to a write() syscall on @@ -120,22 +119,18 @@ impl FileDescriptor for io::Stdout { Ok(result) } - fn dup(&mut self) -> io::Result> { - Ok(Box::new(io::stdout())) - } - fn is_tty(&self, communicate_allowed: bool) -> bool { communicate_allowed && self.is_terminal() } } -impl FileDescriptor for io::Stderr { +impl FileDescription for io::Stderr { fn name(&self) -> &'static str { "stderr" } fn write<'tcx>( - &self, + &mut self, _communicate_allowed: bool, bytes: &[u8], _tcx: TyCtxt<'tcx>, @@ -145,10 +140,6 @@ impl FileDescriptor for io::Stderr { Ok(Write::write(&mut { self }, bytes)) } - fn dup(&mut self) -> io::Result> { - Ok(Box::new(io::stderr())) - } - fn is_tty(&self, communicate_allowed: bool) -> bool { communicate_allowed && self.is_terminal() } @@ -158,13 +149,13 @@ impl FileDescriptor for io::Stderr { #[derive(Debug)] pub struct NullOutput; -impl FileDescriptor for NullOutput { +impl FileDescription for NullOutput { fn name(&self) -> &'static str { "stderr and stdout" } fn write<'tcx>( - &self, + &mut self, _communicate_allowed: bool, bytes: &[u8], _tcx: TyCtxt<'tcx>, @@ -172,16 +163,30 @@ impl FileDescriptor for NullOutput { // We just don't write anything, but report to the user that we did. Ok(Ok(bytes.len())) } +} + +#[derive(Clone, Debug)] +pub struct FileDescriptor(Rc>>); + +impl FileDescriptor { + pub fn new(fd: T) -> Self { + FileDescriptor(Rc::new(RefCell::new(Box::new(fd)))) + } - fn dup(&mut self) -> io::Result> { - Ok(Box::new(NullOutput)) + pub fn close<'ctx>(self, communicate_allowed: bool) -> InterpResult<'ctx, io::Result<()>> { + // Destroy this `Rc` using `into_inner` so we can call `close` instead of + // implicitly running the destructor of the file description. + match Rc::into_inner(self.0) { + Some(fd) => RefCell::into_inner(fd).close(communicate_allowed), + None => Ok(Ok(())), + } } } /// The file descriptor table #[derive(Debug)] pub struct FdTable { - pub fds: BTreeMap>, + pub fds: BTreeMap, } impl VisitProvenance for FdTable { @@ -192,28 +197,24 @@ impl VisitProvenance for FdTable { impl FdTable { pub(crate) fn new(mute_stdout_stderr: bool) -> FdTable { - let mut fds: BTreeMap<_, Box> = BTreeMap::new(); - fds.insert(0i32, Box::new(io::stdin())); + let mut fds: BTreeMap<_, FileDescriptor> = BTreeMap::new(); + fds.insert(0i32, FileDescriptor::new(io::stdin())); if mute_stdout_stderr { - fds.insert(1i32, Box::new(NullOutput)); - fds.insert(2i32, Box::new(NullOutput)); + fds.insert(1i32, FileDescriptor::new(NullOutput)); + fds.insert(2i32, FileDescriptor::new(NullOutput)); } else { - fds.insert(1i32, Box::new(io::stdout())); - fds.insert(2i32, Box::new(io::stderr())); + fds.insert(1i32, FileDescriptor::new(io::stdout())); + fds.insert(2i32, FileDescriptor::new(io::stderr())); } FdTable { fds } } - pub fn insert_fd(&mut self, file_handle: Box) -> i32 { + pub fn insert_fd(&mut self, file_handle: FileDescriptor) -> i32 { self.insert_fd_with_min_fd(file_handle, 0) } /// Insert a new FD that is at least `min_fd`. - pub fn insert_fd_with_min_fd( - &mut self, - file_handle: Box, - min_fd: i32, - ) -> i32 { + pub fn insert_fd_with_min_fd(&mut self, file_handle: FileDescriptor, min_fd: i32) -> i32 { // Find the lowest unused FD, starting from min_fd. If the first such unused FD is in // between used FDs, the find_map combinator will return it. If the first such unused FD // is after all other used FDs, the find_map combinator will return None, and we will use @@ -239,15 +240,22 @@ impl FdTable { new_fd } - pub fn get(&self, fd: i32) -> Option<&dyn FileDescriptor> { - Some(&**self.fds.get(&fd)?) + pub fn get(&self, fd: i32) -> Option> { + let fd = self.fds.get(&fd)?; + Some(Ref::map(fd.0.borrow(), |fd| fd.as_ref())) + } + + pub fn get_mut(&self, fd: i32) -> Option> { + let fd = self.fds.get(&fd)?; + Some(RefMut::map(fd.0.borrow_mut(), |fd| fd.as_mut())) } - pub fn get_mut(&mut self, fd: i32) -> Option<&mut dyn FileDescriptor> { - Some(&mut **self.fds.get_mut(&fd)?) + pub fn dup(&self, fd: i32) -> Option { + let fd = self.fds.get(&fd)?; + Some(fd.clone()) } - pub fn remove(&mut self, fd: i32) -> Option> { + pub fn remove(&mut self, fd: i32) -> Option { self.fds.remove(&fd) } @@ -296,17 +304,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } let start = this.read_scalar(&args[2])?.to_i32()?; - match this.machine.fds.get_mut(fd) { - Some(file_descriptor) => { - let dup_result = file_descriptor.dup(); - match dup_result { - Ok(dup_fd) => Ok(this.machine.fds.insert_fd_with_min_fd(dup_fd, start)), - Err(e) => { - this.set_last_error_from_io_error(e.kind())?; - Ok(-1) - } - } - } + match this.machine.fds.dup(fd) { + Some(dup_fd) => Ok(this.machine.fds.insert_fd_with_min_fd(dup_fd, start)), None => this.fd_not_found(), } } else if this.tcx.sess.target.os == "macos" && cmd == this.eval_libc_i32("F_FULLFSYNC") { @@ -330,6 +329,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { Ok(Scalar::from_i32(if let Some(file_descriptor) = this.machine.fds.remove(fd) { let result = file_descriptor.close(this.machine.communicate())?; + // return `0` if close is successful + let result = result.map(|()| 0i32); this.try_unwrap_io_result(result)? } else { this.fd_not_found()? @@ -369,32 +370,33 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { .min(u64::try_from(isize::MAX).unwrap()); let communicate = this.machine.communicate(); - if let Some(file_descriptor) = this.machine.fds.get_mut(fd) { - trace!("read: FD mapped to {:?}", file_descriptor); - // We want to read at most `count` bytes. We are sure that `count` is not negative - // because it was a target's `usize`. Also we are sure that its smaller than - // `usize::MAX` because it is bounded by the host's `isize`. - let mut bytes = vec![0; usize::try_from(count).unwrap()]; - // `File::read` never returns a value larger than `count`, - // so this cannot fail. - let result = file_descriptor - .read(communicate, &mut bytes, *this.tcx)? - .map(|c| i64::try_from(c).unwrap()); - - match result { - Ok(read_bytes) => { - // If reading to `bytes` did not fail, we write those bytes to the buffer. - this.write_bytes_ptr(buf, bytes)?; - Ok(read_bytes) - } - Err(e) => { - this.set_last_error_from_io_error(e.kind())?; - Ok(-1) - } - } - } else { + let Some(mut file_descriptor) = this.machine.fds.get_mut(fd) else { trace!("read: FD not found"); - this.fd_not_found() + return this.fd_not_found(); + }; + + trace!("read: FD mapped to {:?}", file_descriptor); + // We want to read at most `count` bytes. We are sure that `count` is not negative + // because it was a target's `usize`. Also we are sure that its smaller than + // `usize::MAX` because it is bounded by the host's `isize`. + let mut bytes = vec![0; usize::try_from(count).unwrap()]; + // `File::read` never returns a value larger than `count`, + // so this cannot fail. + let result = file_descriptor + .read(communicate, &mut bytes, *this.tcx)? + .map(|c| i64::try_from(c).unwrap()); + drop(file_descriptor); + + match result { + Ok(read_bytes) => { + // If reading to `bytes` did not fail, we write those bytes to the buffer. + this.write_bytes_ptr(buf, bytes)?; + Ok(read_bytes) + } + Err(e) => { + this.set_last_error_from_io_error(e.kind())?; + Ok(-1) + } } } @@ -418,14 +420,16 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { .min(u64::try_from(isize::MAX).unwrap()); let communicate = this.machine.communicate(); - if let Some(file_descriptor) = this.machine.fds.get(fd) { - let bytes = this.read_bytes_ptr_strip_provenance(buf, Size::from_bytes(count))?; - let result = file_descriptor - .write(communicate, bytes, *this.tcx)? - .map(|c| i64::try_from(c).unwrap()); - this.try_unwrap_io_result(result) - } else { - this.fd_not_found() - } + let bytes = this.read_bytes_ptr_strip_provenance(buf, Size::from_bytes(count))?.to_owned(); + let Some(mut file_descriptor) = this.machine.fds.get_mut(fd) else { + return this.fd_not_found(); + }; + + let result = file_descriptor + .write(communicate, &bytes, *this.tcx)? + .map(|c| i64::try_from(c).unwrap()); + drop(file_descriptor); + + this.try_unwrap_io_result(result) } } diff --git a/src/tools/miri/src/shims/unix/foreign_items.rs b/src/tools/miri/src/shims/unix/foreign_items.rs index bd299aaa1253a..595cf64a4e4b4 100644 --- a/src/tools/miri/src/shims/unix/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/foreign_items.rs @@ -9,13 +9,13 @@ use rustc_target::spec::abi::Abi; use crate::shims::alloc::EvalContextExt as _; use crate::shims::unix::*; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; use shims::unix::freebsd::foreign_items as freebsd; use shims::unix::linux::foreign_items as linux; use shims::unix::macos::foreign_items as macos; +use shims::unix::solarish::foreign_items as solarish; -fn is_dyn_sym(name: &str, target_os: &str) -> bool { +pub fn is_dyn_sym(name: &str, target_os: &str) -> bool { match name { // Used for tests. "isatty" => true, @@ -23,13 +23,14 @@ fn is_dyn_sym(name: &str, target_os: &str) -> bool { // well allow it in `dlsym`. "signal" => true, // needed at least on macOS to avoid file-based fallback in getrandom - "getentropy" => true, + "getentropy" | "getrandom" => true, // Give specific OSes a chance to allow their symbols. _ => match target_os { "freebsd" => freebsd::is_dyn_sym(name), "linux" => linux::is_dyn_sym(name), "macos" => macos::is_dyn_sym(name), + "solaris" | "illumos" => solarish::is_dyn_sym(name), _ => false, }, } @@ -43,7 +44,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); // See `fn emulate_foreign_item_inner` in `shims/foreign_items.rs` for the general pattern. @@ -489,6 +490,18 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let result = this.pthread_condattr_init(attr)?; this.write_scalar(Scalar::from_i32(result), dest)?; } + "pthread_condattr_setclock" => { + let [attr, clock_id] = + this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; + let result = this.pthread_condattr_setclock(attr, clock_id)?; + this.write_scalar(result, dest)?; + } + "pthread_condattr_getclock" => { + let [attr, clock_id] = + this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; + let result = this.pthread_condattr_getclock(attr, clock_id)?; + this.write_scalar(result, dest)?; + } "pthread_condattr_destroy" => { let [attr] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; let result = this.pthread_condattr_destroy(attr)?; @@ -592,8 +605,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } "getentropy" => { // This function is non-standard but exists with the same signature and behavior on - // Linux, macOS, and FreeBSD. - if !matches!(&*this.tcx.sess.target.os, "linux" | "macos" | "freebsd") { + // Linux, macOS, FreeBSD and Solaris/Illumos. + if !matches!(&*this.tcx.sess.target.os, "linux" | "macos" | "freebsd" | "illumos" | "solaris") { throw_unsup_format!( "`getentropy` is not supported on {}", this.tcx.sess.target.os @@ -609,6 +622,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { // FreeBSD: https://man.freebsd.org/cgi/man.cgi?query=getentropy&sektion=3&format=html // Linux: https://man7.org/linux/man-pages/man3/getentropy.3.html // macOS: https://keith.github.io/xcode-man-pages/getentropy.2.html + // Solaris/Illumos: https://illumos.org/man/3C/getentropy if bufsize > 256 { let err = this.eval_libc("EIO"); this.set_last_error(err)?; @@ -618,6 +632,24 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { this.write_scalar(Scalar::from_i32(0), dest)?; } } + "getrandom" => { + // This function is non-standard but exists with the same signature and behavior on + // Linux, FreeBSD and Solaris/Illumos. + if !matches!(&*this.tcx.sess.target.os, "linux" | "freebsd" | "illumos" | "solaris") { + throw_unsup_format!( + "`getentropy` is not supported on {}", + this.tcx.sess.target.os + ); + } + let [ptr, len, flags] = + this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; + let ptr = this.read_pointer(ptr)?; + let len = this.read_target_usize(len)?; + let _flags = this.read_scalar(flags)?.to_i32()?; + // We ignore the flags, just always use the same PRNG / host RNG. + this.gen_random(ptr, len)?; + this.write_scalar(Scalar::from_target_usize(len, this), dest)?; + } // Incomplete shims that we "stub out" just to get pre-main initialization code to work. // These shims are enabled only when the caller is in the standard library. @@ -724,25 +756,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } } - "sched_getaffinity" => { - // FreeBSD supports it as well since 13.1 (as a wrapper of cpuset_getaffinity) - if !matches!(&*this.tcx.sess.target.os, "linux" | "freebsd") { - throw_unsup_format!( - "`sched_getaffinity` is not supported on {}", - this.tcx.sess.target.os - ); - } - let [pid, cpusetsize, mask] = - this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; - this.read_scalar(pid)?.to_i32()?; - this.read_target_usize(cpusetsize)?; - this.deref_pointer_as(mask, this.libc_ty_layout("cpu_set_t"))?; - // FIXME: we just return an error; `num_cpus` then falls back to `sysconf`. - let einval = this.eval_libc("EINVAL"); - this.set_last_error(einval)?; - this.write_scalar(Scalar::from_i32(-1), dest)?; - } - // Platform-specific shims _ => { let target_os = &*this.tcx.sess.target.os; @@ -750,11 +763,12 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { "freebsd" => freebsd::EvalContextExt::emulate_foreign_item_inner(this, link_name, abi, args, dest), "linux" => linux::EvalContextExt::emulate_foreign_item_inner(this, link_name, abi, args, dest), "macos" => macos::EvalContextExt::emulate_foreign_item_inner(this, link_name, abi, args, dest), - _ => Ok(EmulateForeignItemResult::NotSupported), + "solaris" | "illumos" => solarish::EvalContextExt::emulate_foreign_item_inner(this, link_name, abi, args, dest), + _ => Ok(EmulateItemResult::NotSupported), }; } }; - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs index ffb583123d41b..e70cd35dda6d5 100644 --- a/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/freebsd/foreign_items.rs @@ -3,7 +3,6 @@ use rustc_target::spec::abi::Abi; use crate::shims::unix::*; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; pub fn is_dyn_sym(_name: &str) -> bool { false @@ -17,15 +16,10 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); match link_name.as_str() { // Threading - "pthread_attr_get_np" if this.frame_in_std() => { - let [_thread, _attr] = - this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; - this.write_null(dest)?; - } "pthread_set_name_np" => { let [thread, name] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; @@ -47,21 +41,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { this.read_scalar(len)?, )?; } - "getrandom" => { - let [ptr, len, flags] = - this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; - let ptr = this.read_pointer(ptr)?; - let len = this.read_target_usize(len)?; - let _flags = this.read_scalar(flags)?.to_i32()?; - // flags on freebsd does not really matter - // in practice, GRND_RANDOM does not particularly draw from /dev/random - // since it is the same as to /dev/urandom. - // GRND_INSECURE is only an alias of GRND_NONBLOCK, which - // does not affect the RNG. - // https://man.freebsd.org/cgi/man.cgi?query=getrandom&sektion=2&n=1 - this.gen_random(ptr, len)?; - this.write_scalar(Scalar::from_target_usize(len, this), dest)?; - } // File related shims // For those, we both intercept `func` and `call@FBSD_1.0` symbols cases @@ -90,15 +69,23 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { this.write_scalar(result, dest)?; } - // errno + // Miscellaneous "__error" => { let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; let errno_place = this.last_error_place()?; this.write_scalar(errno_place.to_ref(this).to_scalar(), dest)?; } - _ => return Ok(EmulateForeignItemResult::NotSupported), + // Incomplete shims that we "stub out" just to get pre-main initialization code to work. + // These shims are enabled only when the caller is in the standard library. + "pthread_attr_get_np" if this.frame_in_std() => { + let [_thread, _attr] = + this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; + this.write_null(dest)?; + } + + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/unix/fs.rs b/src/tools/miri/src/shims/unix/fs.rs index ebf9f43c19ef6..058747916c0ac 100644 --- a/src/tools/miri/src/shims/unix/fs.rs +++ b/src/tools/miri/src/shims/unix/fs.rs @@ -17,15 +17,17 @@ use crate::shims::unix::*; use crate::*; use shims::time::system_time_to_duration; +use self::fd::FileDescriptor; + #[derive(Debug)] struct FileHandle { file: File, writable: bool, } -impl FileDescriptor for FileHandle { +impl FileDescription for FileHandle { fn name(&self) -> &'static str { - "FILE" + "file" } fn read<'tcx>( @@ -39,13 +41,13 @@ impl FileDescriptor for FileHandle { } fn write<'tcx>( - &self, + &mut self, communicate_allowed: bool, bytes: &[u8], _tcx: TyCtxt<'tcx>, ) -> InterpResult<'tcx, io::Result> { assert!(communicate_allowed, "isolation should have prevented even opening a file"); - Ok((&mut &self.file).write(bytes)) + Ok(self.file.write(bytes)) } fn seek<'tcx>( @@ -60,16 +62,14 @@ impl FileDescriptor for FileHandle { fn close<'tcx>( self: Box, communicate_allowed: bool, - ) -> InterpResult<'tcx, io::Result> { + ) -> InterpResult<'tcx, io::Result<()>> { assert!(communicate_allowed, "isolation should have prevented even opening a file"); // We sync the file if it was opened in a mode different than read-only. if self.writable { // `File::sync_all` does the checks that are done when closing a file. We do this to // to handle possible errors correctly. - let result = self.file.sync_all().map(|_| 0i32); - // Now we actually close the file. - drop(self); - // And return the result. + let result = self.file.sync_all(); + // Now we actually close the file and return the result. Ok(result) } else { // We drop the file, this closes it but ignores any errors @@ -78,16 +78,10 @@ impl FileDescriptor for FileHandle { // `/dev/urandom` which are read-only. Check // https://github.com/rust-lang/miri/issues/999#issuecomment-568920439 // for a deeper discussion. - drop(self); - Ok(Ok(0)) + Ok(Ok(())) } } - fn dup(&mut self) -> io::Result> { - let duplicated = self.file.try_clone()?; - Ok(Box::new(FileHandle { file: duplicated, writable: self.writable })) - } - fn is_tty(&self, communicate_allowed: bool) -> bool { communicate_allowed && self.file.is_terminal() } @@ -399,7 +393,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let fd = options.open(path).map(|file| { let fh = &mut this.machine.fds; - fh.insert_fd(Box::new(FileHandle { file, writable })) + fh.insert_fd(FileDescriptor::new(FileHandle { file, writable })) }); this.try_unwrap_io_result(fd) @@ -428,14 +422,17 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { }; let communicate = this.machine.communicate(); - Ok(Scalar::from_i64(if let Some(file_descriptor) = this.machine.fds.get_mut(fd) { - let result = file_descriptor - .seek(communicate, seek_from)? - .map(|offset| i64::try_from(offset).unwrap()); - this.try_unwrap_io_result(result)? - } else { - this.fd_not_found()? - })) + + let Some(mut file_descriptor) = this.machine.fds.get_mut(fd) else { + return Ok(Scalar::from_i64(this.fd_not_found()?)); + }; + let result = file_descriptor + .seek(communicate, seek_from)? + .map(|offset| i64::try_from(offset).unwrap()); + drop(file_descriptor); + + let result = this.try_unwrap_io_result(result)?; + Ok(Scalar::from_i64(result)) } fn unlink(&mut self, path_op: &OpTy<'tcx, Provenance>) -> InterpResult<'tcx, i32> { @@ -1131,32 +1128,35 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { return Ok(Scalar::from_i32(this.fd_not_found()?)); } - Ok(Scalar::from_i32(if let Some(file_descriptor) = this.machine.fds.get_mut(fd) { - // FIXME: Support ftruncate64 for all FDs - let FileHandle { file, writable } = - file_descriptor.downcast_ref::().ok_or_else(|| { - err_unsup_format!( - "`ftruncate64` is only supported on file-backed file descriptors" - ) - })?; - if *writable { - if let Ok(length) = length.try_into() { - let result = file.set_len(length); - this.try_unwrap_io_result(result.map(|_| 0i32))? - } else { - let einval = this.eval_libc("EINVAL"); - this.set_last_error(einval)?; - -1 - } + let Some(file_descriptor) = this.machine.fds.get(fd) else { + return Ok(Scalar::from_i32(this.fd_not_found()?)); + }; + + // FIXME: Support ftruncate64 for all FDs + let FileHandle { file, writable } = + file_descriptor.downcast_ref::().ok_or_else(|| { + err_unsup_format!("`ftruncate64` is only supported on file-backed file descriptors") + })?; + + if *writable { + if let Ok(length) = length.try_into() { + let result = file.set_len(length); + drop(file_descriptor); + let result = this.try_unwrap_io_result(result.map(|_| 0i32))?; + Ok(Scalar::from_i32(result)) } else { - // The file is not writable + drop(file_descriptor); let einval = this.eval_libc("EINVAL"); this.set_last_error(einval)?; - -1 + Ok(Scalar::from_i32(-1)) } } else { - this.fd_not_found()? - })) + drop(file_descriptor); + // The file is not writable + let einval = this.eval_libc("EINVAL"); + this.set_last_error(einval)?; + Ok(Scalar::from_i32(-1)) + } } fn fsync(&mut self, fd_op: &OpTy<'tcx, Provenance>) -> InterpResult<'tcx, i32> { @@ -1190,6 +1190,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { err_unsup_format!("`fsync` is only supported on file-backed file descriptors") })?; let io_result = maybe_sync_file(file, *writable, File::sync_all); + drop(file_descriptor); this.try_unwrap_io_result(io_result) } @@ -1214,6 +1215,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { err_unsup_format!("`fdatasync` is only supported on file-backed file descriptors") })?; let io_result = maybe_sync_file(file, *writable, File::sync_data); + drop(file_descriptor); this.try_unwrap_io_result(io_result) } @@ -1263,6 +1265,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) })?; let io_result = maybe_sync_file(file, *writable, File::sync_data); + drop(file_descriptor); Ok(Scalar::from_i32(this.try_unwrap_io_result(io_result)?)) } @@ -1498,7 +1501,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { match file { Ok(f) => { let fh = &mut this.machine.fds; - let fd = fh.insert_fd(Box::new(FileHandle { file: f, writable: true })); + let fd = + fh.insert_fd(FileDescriptor::new(FileHandle { file: f, writable: true })); return Ok(fd); } Err(e) => @@ -1563,21 +1567,21 @@ impl FileMetadata { ecx: &mut MiriInterpCx<'_, 'tcx>, fd: i32, ) -> InterpResult<'tcx, Option> { - let option = ecx.machine.fds.get(fd); - let file = match option { - Some(file_descriptor) => - &file_descriptor - .downcast_ref::() - .ok_or_else(|| { - err_unsup_format!( - "obtaining metadata is only supported on file-backed file descriptors" - ) - })? - .file, - None => return ecx.fd_not_found().map(|_: i32| None), + let Some(file_descriptor) = ecx.machine.fds.get(fd) else { + return ecx.fd_not_found().map(|_: i32| None); }; - let metadata = file.metadata(); + let file = &file_descriptor + .downcast_ref::() + .ok_or_else(|| { + err_unsup_format!( + "obtaining metadata is only supported on file-backed file descriptors" + ) + })? + .file; + + let metadata = file.metadata(); + drop(file_descriptor); FileMetadata::from_meta(ecx, metadata) } diff --git a/src/tools/miri/src/shims/unix/linux/epoll.rs b/src/tools/miri/src/shims/unix/linux/epoll.rs index 5161d91ca3639..48a0ba0197608 100644 --- a/src/tools/miri/src/shims/unix/linux/epoll.rs +++ b/src/tools/miri/src/shims/unix/linux/epoll.rs @@ -5,6 +5,8 @@ use rustc_data_structures::fx::FxHashMap; use crate::shims::unix::*; use crate::*; +use self::shims::unix::fd::FileDescriptor; + /// An `Epoll` file descriptor connects file handles and epoll events #[derive(Clone, Debug, Default)] struct Epoll { @@ -29,22 +31,16 @@ struct EpollEvent { data: Scalar, } -impl FileDescriptor for Epoll { +impl FileDescription for Epoll { fn name(&self) -> &'static str { "epoll" } - fn dup(&mut self) -> io::Result> { - // FIXME: this is probably wrong -- check if the `dup`ed descriptor truly uses an - // independent event set. - Ok(Box::new(self.clone())) - } - fn close<'tcx>( self: Box, _communicate_allowed: bool, - ) -> InterpResult<'tcx, io::Result> { - Ok(Ok(0)) + ) -> InterpResult<'tcx, io::Result<()>> { + Ok(Ok(())) } } @@ -70,7 +66,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { throw_unsup_format!("epoll_create1 flags {flags} are not implemented"); } - let fd = this.machine.fds.insert_fd(Box::new(Epoll::default())); + let fd = this.machine.fds.insert_fd(FileDescriptor::new(Epoll::default())); Ok(Scalar::from_i32(fd)) } @@ -114,27 +110,25 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let data = this.read_scalar(&data)?; let event = EpollEvent { events, data }; - if let Some(epfd) = this.machine.fds.get_mut(epfd) { - let epfd = epfd - .downcast_mut::() - .ok_or_else(|| err_unsup_format!("non-epoll FD passed to `epoll_ctl`"))?; + let Some(mut epfd) = this.machine.fds.get_mut(epfd) else { + return Ok(Scalar::from_i32(this.fd_not_found()?)); + }; + let epfd = epfd + .downcast_mut::() + .ok_or_else(|| err_unsup_format!("non-epoll FD passed to `epoll_ctl`"))?; - epfd.file_descriptors.insert(fd, event); - Ok(Scalar::from_i32(0)) - } else { - Ok(Scalar::from_i32(this.fd_not_found()?)) - } + epfd.file_descriptors.insert(fd, event); + Ok(Scalar::from_i32(0)) } else if op == epoll_ctl_del { - if let Some(epfd) = this.machine.fds.get_mut(epfd) { - let epfd = epfd - .downcast_mut::() - .ok_or_else(|| err_unsup_format!("non-epoll FD passed to `epoll_ctl`"))?; - - epfd.file_descriptors.remove(&fd); - Ok(Scalar::from_i32(0)) - } else { - Ok(Scalar::from_i32(this.fd_not_found()?)) - } + let Some(mut epfd) = this.machine.fds.get_mut(epfd) else { + return Ok(Scalar::from_i32(this.fd_not_found()?)); + }; + let epfd = epfd + .downcast_mut::() + .ok_or_else(|| err_unsup_format!("non-epoll FD passed to `epoll_ctl`"))?; + + epfd.file_descriptors.remove(&fd); + Ok(Scalar::from_i32(0)) } else { let einval = this.eval_libc("EINVAL"); this.set_last_error(einval)?; @@ -185,15 +179,14 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let _maxevents = this.read_scalar(maxevents)?.to_i32()?; let _timeout = this.read_scalar(timeout)?.to_i32()?; - if let Some(epfd) = this.machine.fds.get_mut(epfd) { - let _epfd = epfd - .downcast_mut::() - .ok_or_else(|| err_unsup_format!("non-epoll FD passed to `epoll_wait`"))?; + let Some(mut epfd) = this.machine.fds.get_mut(epfd) else { + return Ok(Scalar::from_i32(this.fd_not_found()?)); + }; + let _epfd = epfd + .downcast_mut::() + .ok_or_else(|| err_unsup_format!("non-epoll FD passed to `epoll_wait`"))?; - // FIXME return number of events ready when scheme for marking events ready exists - throw_unsup_format!("returning ready events from epoll_wait is not yet implemented"); - } else { - Ok(Scalar::from_i32(this.fd_not_found()?)) - } + // FIXME return number of events ready when scheme for marking events ready exists + throw_unsup_format!("returning ready events from epoll_wait is not yet implemented"); } } diff --git a/src/tools/miri/src/shims/unix/linux/eventfd.rs b/src/tools/miri/src/shims/unix/linux/eventfd.rs index 0f28b69ac4a8e..a865f2efff957 100644 --- a/src/tools/miri/src/shims/unix/linux/eventfd.rs +++ b/src/tools/miri/src/shims/unix/linux/eventfd.rs @@ -1,6 +1,5 @@ //! Linux `eventfd` implementation. //! Currently just a stub. -use std::cell::Cell; use std::io; use rustc_middle::ty::TyCtxt; @@ -9,6 +8,8 @@ use rustc_target::abi::Endian; use crate::shims::unix::*; use crate::*; +use self::shims::unix::fd::FileDescriptor; + /// A kind of file descriptor created by `eventfd`. /// The `Event` type isn't currently written to by `eventfd`. /// The interface is meant to keep track of objects associated @@ -20,24 +21,19 @@ use crate::*; struct Event { /// The object contains an unsigned 64-bit integer (uint64_t) counter that is maintained by the /// kernel. This counter is initialized with the value specified in the argument initval. - val: Cell, + val: u64, } -impl FileDescriptor for Event { +impl FileDescription for Event { fn name(&self) -> &'static str { "event" } - fn dup(&mut self) -> io::Result> { - // FIXME: this is wrong, the new and old FD should refer to the same event object! - Ok(Box::new(Event { val: self.val.clone() })) - } - fn close<'tcx>( self: Box, _communicate_allowed: bool, - ) -> InterpResult<'tcx, io::Result> { - Ok(Ok(0)) + ) -> InterpResult<'tcx, io::Result<()>> { + Ok(Ok(())) } /// A write call adds the 8-byte integer value supplied in @@ -53,12 +49,11 @@ impl FileDescriptor for Event { /// supplied buffer is less than 8 bytes, or if an attempt is /// made to write the value 0xffffffffffffffff. fn write<'tcx>( - &self, + &mut self, _communicate_allowed: bool, bytes: &[u8], tcx: TyCtxt<'tcx>, ) -> InterpResult<'tcx, io::Result> { - let v1 = self.val.get(); let bytes: [u8; 8] = bytes.try_into().unwrap(); // FIXME fail gracefully when this has the wrong size // Convert from target endianness to host endianness. let num = match tcx.sess.target.endian { @@ -67,9 +62,7 @@ impl FileDescriptor for Event { }; // FIXME handle blocking when addition results in exceeding the max u64 value // or fail with EAGAIN if the file descriptor is nonblocking. - let v2 = v1.checked_add(num).unwrap(); - self.val.set(v2); - assert_eq!(8, bytes.len()); + self.val = self.val.checked_add(num).unwrap(); Ok(Ok(8)) } } @@ -119,7 +112,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { throw_unsup_format!("eventfd: EFD_SEMAPHORE is unsupported"); } - let fd = this.machine.fds.insert_fd(Box::new(Event { val: Cell::new(val.into()) })); + let fd = this.machine.fds.insert_fd(FileDescriptor::new(Event { val: val.into() })); Ok(Scalar::from_i32(fd)) } } diff --git a/src/tools/miri/src/shims/unix/linux/foreign_items.rs b/src/tools/miri/src/shims/unix/linux/foreign_items.rs index 497e8bee70ec9..ecf82f26a5528 100644 --- a/src/tools/miri/src/shims/unix/linux/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/linux/foreign_items.rs @@ -5,14 +5,13 @@ use crate::machine::SIGRTMAX; use crate::machine::SIGRTMIN; use crate::shims::unix::*; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; use shims::unix::linux::epoll::EvalContextExt as _; use shims::unix::linux::eventfd::EvalContextExt as _; use shims::unix::linux::mem::EvalContextExt as _; use shims::unix::linux::sync::futex; pub fn is_dyn_sym(name: &str) -> bool { - matches!(name, "getrandom") + matches!(name, "statx") } impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} @@ -23,13 +22,13 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); // See `fn emulate_foreign_item_inner` in `shims/foreign_items.rs` for the general pattern. match link_name.as_str() { - // File related shims (but also see "syscall" below for statx) + // File related shims "readdir64" => { let [dirp] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; let result = this.linux_readdir64(dirp)?; @@ -41,6 +40,12 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let result = this.sync_file_range(fd, offset, nbytes, flags)?; this.write_scalar(result, dest)?; } + "statx" => { + let [dirfd, pathname, flags, mask, statxbuf] = + this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; + let result = this.linux_statx(dirfd, pathname, flags, mask, statxbuf)?; + this.write_scalar(Scalar::from_i32(result), dest)?; + } // epoll, eventfd "epoll_create1" => { @@ -68,18 +73,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } // Threading - "pthread_condattr_setclock" => { - let [attr, clock_id] = - this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; - let result = this.pthread_condattr_setclock(attr, clock_id)?; - this.write_scalar(result, dest)?; - } - "pthread_condattr_getclock" => { - let [attr, clock_id] = - this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; - let result = this.pthread_condattr_getclock(attr, clock_id)?; - this.write_scalar(result, dest)?; - } "pthread_setname_np" => { let [thread, name] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; @@ -113,9 +106,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { // have the right type. let sys_getrandom = this.eval_libc("SYS_getrandom").to_target_usize(this)?; - - let sys_statx = this.eval_libc("SYS_statx").to_target_usize(this)?; - let sys_futex = this.eval_libc("SYS_futex").to_target_usize(this)?; if args.is_empty() { @@ -136,37 +126,20 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } getrandom(this, &args[1], &args[2], &args[3], dest)?; } - // `statx` is used by `libstd` to retrieve metadata information on `linux` - // instead of using `stat`,`lstat` or `fstat` as on `macos`. - id if id == sys_statx => { - // The first argument is the syscall id, so skip over it. - if args.len() < 6 { - throw_ub_format!( - "incorrect number of arguments for `statx` syscall: got {}, expected at least 6", - args.len() - ); - } - let result = - this.linux_statx(&args[1], &args[2], &args[3], &args[4], &args[5])?; - this.write_scalar(Scalar::from_target_isize(result.into(), this), dest)?; - } // `futex` is used by some synchronization primitives. id if id == sys_futex => { futex(this, &args[1..], dest)?; } id => { - this.handle_unsupported(format!("can't execute syscall with ID {id}"))?; - return Ok(EmulateForeignItemResult::AlreadyJumped); + this.handle_unsupported_foreign_item(format!( + "can't execute syscall with ID {id}" + ))?; + return Ok(EmulateItemResult::AlreadyJumped); } } } // Miscellaneous - "getrandom" => { - let [ptr, len, flags] = - this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; - getrandom(this, ptr, len, flags, dest)?; - } "mmap64" => { let [addr, length, prot, flags, fd, offset] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; @@ -195,6 +168,19 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { this.write_scalar(Scalar::from_i32(SIGRTMAX), dest)?; } + "sched_getaffinity" => { + // This shim isn't useful, aside from the fact that it makes `num_cpus` + // fall back to `sysconf` where it will successfully determine the number of CPUs. + let [pid, cpusetsize, mask] = + this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; + this.read_scalar(pid)?.to_i32()?; + this.read_target_usize(cpusetsize)?; + this.deref_pointer_as(mask, this.libc_ty_layout("cpu_set_t"))?; + // FIXME: we just return an error. + let einval = this.eval_libc("EINVAL"); + this.set_last_error(einval)?; + this.write_scalar(Scalar::from_i32(-1), dest)?; + } // Incomplete shims that we "stub out" just to get pre-main initialization code to work. // These shims are enabled only when the caller is in the standard library. @@ -204,10 +190,10 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { this.write_null(dest)?; } - _ => return Ok(EmulateForeignItemResult::NotSupported), + _ => return Ok(EmulateItemResult::NotSupported), }; - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/unix/macos/foreign_items.rs b/src/tools/miri/src/shims/unix/macos/foreign_items.rs index 66a8dce753fb1..912623b722570 100644 --- a/src/tools/miri/src/shims/unix/macos/foreign_items.rs +++ b/src/tools/miri/src/shims/unix/macos/foreign_items.rs @@ -3,7 +3,6 @@ use rustc_target::spec::abi::Abi; use crate::shims::unix::*; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; pub fn is_dyn_sym(_name: &str) -> bool { false @@ -17,7 +16,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); // See `fn emulate_foreign_item_inner` in `shims/foreign_items.rs` for the general pattern. @@ -175,9 +174,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { this.write_scalar(res, dest)?; } - _ => return Ok(EmulateForeignItemResult::NotSupported), + _ => return Ok(EmulateItemResult::NotSupported), }; - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/unix/mod.rs b/src/tools/miri/src/shims/unix/mod.rs index 144593aa2fc08..6dee30d895c71 100644 --- a/src/tools/miri/src/shims/unix/mod.rs +++ b/src/tools/miri/src/shims/unix/mod.rs @@ -11,9 +11,10 @@ mod thread; mod freebsd; mod linux; mod macos; +mod solarish; pub use env::UnixEnvVars; -pub use fd::{FdTable, FileDescriptor}; +pub use fd::{FdTable, FileDescription}; pub use fs::DirTable; // All the Unix-specific extension traits pub use env::EvalContextExt as _; diff --git a/src/tools/miri/src/shims/unix/socket.rs b/src/tools/miri/src/shims/unix/socket.rs index 84ddd746fb584..11fd83f57e67e 100644 --- a/src/tools/miri/src/shims/unix/socket.rs +++ b/src/tools/miri/src/shims/unix/socket.rs @@ -3,26 +3,24 @@ use std::io; use crate::shims::unix::*; use crate::*; +use self::fd::FileDescriptor; + /// Pair of connected sockets. /// /// We currently don't allow sending any data through this pair, so this can be just a dummy. #[derive(Debug)] struct SocketPair; -impl FileDescriptor for SocketPair { +impl FileDescription for SocketPair { fn name(&self) -> &'static str { "socketpair" } - fn dup(&mut self) -> io::Result> { - Ok(Box::new(SocketPair)) - } - fn close<'tcx>( self: Box, _communicate_allowed: bool, - ) -> InterpResult<'tcx, io::Result> { - Ok(Ok(0)) + ) -> InterpResult<'tcx, io::Result<()>> { + Ok(Ok(())) } } @@ -52,9 +50,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { // FIXME: fail on unsupported inputs let fds = &mut this.machine.fds; - let sv0 = fds.insert_fd(Box::new(SocketPair)); + let sv0 = fds.insert_fd(FileDescriptor::new(SocketPair)); let sv0 = Scalar::try_from_int(sv0, sv.layout.size).unwrap(); - let sv1 = fds.insert_fd(Box::new(SocketPair)); + let sv1 = fds.insert_fd(FileDescriptor::new(SocketPair)); let sv1 = Scalar::try_from_int(sv1, sv.layout.size).unwrap(); this.write_scalar(sv0, &sv)?; diff --git a/src/tools/miri/src/shims/unix/solarish/foreign_items.rs b/src/tools/miri/src/shims/unix/solarish/foreign_items.rs new file mode 100644 index 0000000000000..c01ae0ecb908b --- /dev/null +++ b/src/tools/miri/src/shims/unix/solarish/foreign_items.rs @@ -0,0 +1,33 @@ +use rustc_span::Symbol; +use rustc_target::spec::abi::Abi; + +use crate::*; +use shims::EmulateItemResult; + +pub fn is_dyn_sym(_name: &str) -> bool { + false +} + +impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} +pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { + fn emulate_foreign_item_inner( + &mut self, + link_name: Symbol, + abi: Abi, + args: &[OpTy<'tcx, Provenance>], + dest: &MPlaceTy<'tcx, Provenance>, + ) -> InterpResult<'tcx, EmulateItemResult> { + let this = self.eval_context_mut(); + match link_name.as_str() { + // Miscellaneous + "___errno" => { + let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?; + let errno_place = this.last_error_place()?; + this.write_scalar(errno_place.to_ref(this).to_scalar(), dest)?; + } + + _ => return Ok(EmulateItemResult::NotSupported), + } + Ok(EmulateItemResult::NeedsJumping) + } +} diff --git a/src/tools/miri/src/shims/unix/solarish/mod.rs b/src/tools/miri/src/shims/unix/solarish/mod.rs new file mode 100644 index 0000000000000..09c6507b24f84 --- /dev/null +++ b/src/tools/miri/src/shims/unix/solarish/mod.rs @@ -0,0 +1 @@ +pub mod foreign_items; diff --git a/src/tools/miri/src/shims/unix/sync.rs b/src/tools/miri/src/shims/unix/sync.rs index e50a8934e09d0..f24f279ab0f9d 100644 --- a/src/tools/miri/src/shims/unix/sync.rs +++ b/src/tools/miri/src/shims/unix/sync.rs @@ -1,34 +1,23 @@ +use std::sync::atomic::{AtomicBool, Ordering}; use std::time::SystemTime; +use rustc_target::abi::Size; + use crate::concurrency::thread::MachineCallback; use crate::*; // pthread_mutexattr_t is either 4 or 8 bytes, depending on the platform. +// We ignore the platform layout and store our own fields: +// - kind: i32 -// Our chosen memory layout for emulation (does not have to match the platform layout!): -// store an i32 in the first four bytes equal to the corresponding libc mutex kind constant -// (e.g. PTHREAD_MUTEX_NORMAL). - -/// A flag that allows to distinguish `PTHREAD_MUTEX_NORMAL` from -/// `PTHREAD_MUTEX_DEFAULT`. Since in `glibc` they have the same numeric values, -/// but different behaviour, we need a way to distinguish them. We do this by -/// setting this bit flag to the `PTHREAD_MUTEX_NORMAL` mutexes. See the comment -/// in `pthread_mutexattr_settype` function. -const PTHREAD_MUTEX_NORMAL_FLAG: i32 = 0x8000000; - -fn is_mutex_kind_default<'mir, 'tcx: 'mir>( +#[inline] +fn mutexattr_kind_offset<'mir, 'tcx: 'mir>( ecx: &MiriInterpCx<'mir, 'tcx>, - kind: i32, -) -> InterpResult<'tcx, bool> { - Ok(kind == ecx.eval_libc_i32("PTHREAD_MUTEX_DEFAULT")) -} - -fn is_mutex_kind_normal<'mir, 'tcx: 'mir>( - ecx: &MiriInterpCx<'mir, 'tcx>, - kind: i32, -) -> InterpResult<'tcx, bool> { - let mutex_normal_kind = ecx.eval_libc_i32("PTHREAD_MUTEX_NORMAL"); - Ok(kind == (mutex_normal_kind | PTHREAD_MUTEX_NORMAL_FLAG)) +) -> InterpResult<'tcx, u64> { + Ok(match &*ecx.tcx.sess.target.os { + "linux" | "illumos" | "solaris" | "macos" => 0, + os => throw_unsup_format!("`pthread_mutexattr` is not supported on {os}"), + }) } fn mutexattr_get_kind<'mir, 'tcx: 'mir>( @@ -37,7 +26,7 @@ fn mutexattr_get_kind<'mir, 'tcx: 'mir>( ) -> InterpResult<'tcx, i32> { ecx.deref_pointer_and_read( attr_op, - 0, + mutexattr_kind_offset(ecx)?, ecx.libc_ty_layout("pthread_mutexattr_t"), ecx.machine.layouts.i32, )? @@ -51,27 +40,99 @@ fn mutexattr_set_kind<'mir, 'tcx: 'mir>( ) -> InterpResult<'tcx, ()> { ecx.deref_pointer_and_write( attr_op, - 0, + mutexattr_kind_offset(ecx)?, Scalar::from_i32(kind), ecx.libc_ty_layout("pthread_mutexattr_t"), ecx.machine.layouts.i32, ) } +/// A flag that allows to distinguish `PTHREAD_MUTEX_NORMAL` from +/// `PTHREAD_MUTEX_DEFAULT`. Since in `glibc` they have the same numeric values, +/// but different behaviour, we need a way to distinguish them. We do this by +/// setting this bit flag to the `PTHREAD_MUTEX_NORMAL` mutexes. See the comment +/// in `pthread_mutexattr_settype` function. +const PTHREAD_MUTEX_NORMAL_FLAG: i32 = 0x8000000; + +fn is_mutex_kind_default<'mir, 'tcx: 'mir>( + ecx: &MiriInterpCx<'mir, 'tcx>, + kind: i32, +) -> InterpResult<'tcx, bool> { + Ok(kind == ecx.eval_libc_i32("PTHREAD_MUTEX_DEFAULT")) +} + +fn is_mutex_kind_normal<'mir, 'tcx: 'mir>( + ecx: &MiriInterpCx<'mir, 'tcx>, + kind: i32, +) -> InterpResult<'tcx, bool> { + let mutex_normal_kind = ecx.eval_libc_i32("PTHREAD_MUTEX_NORMAL"); + Ok(kind == (mutex_normal_kind | PTHREAD_MUTEX_NORMAL_FLAG)) +} + // pthread_mutex_t is between 24 and 48 bytes, depending on the platform. +// We ignore the platform layout and store our own fields: +// - id: u32 +// - kind: i32 + +fn mutex_id_offset<'mir, 'tcx: 'mir>(ecx: &MiriInterpCx<'mir, 'tcx>) -> InterpResult<'tcx, u64> { + let offset = match &*ecx.tcx.sess.target.os { + "linux" | "illumos" | "solaris" => 0, + // macOS stores a signature in the first bytes, so we have to move to offset 4. + "macos" => 4, + os => throw_unsup_format!("`pthread_mutex` is not supported on {os}"), + }; + + // Sanity-check this against PTHREAD_MUTEX_INITIALIZER (but only once): + // the id must start out as 0. + static SANITY: AtomicBool = AtomicBool::new(false); + if !SANITY.swap(true, Ordering::Relaxed) { + let static_initializer = ecx.eval_path(&["libc", "PTHREAD_MUTEX_INITIALIZER"]); + let id_field = static_initializer + .offset(Size::from_bytes(offset), ecx.machine.layouts.u32, ecx) + .unwrap(); + let id = ecx.read_scalar(&id_field).unwrap().to_u32().unwrap(); + assert_eq!( + id, 0, + "PTHREAD_MUTEX_INITIALIZER is incompatible with our pthread_mutex layout: id is not 0" + ); + } + + Ok(offset) +} -// Our chosen memory layout for the emulated mutex (does not have to match the platform layout!): -// bytes 0-3: reserved for signature on macOS -// (need to avoid this because it is set by static initializer macros) -// bytes 4-7: mutex id as u32 or 0 if id is not assigned yet. -// bytes 12-15 or 16-19 (depending on platform): mutex kind, as an i32 -// (the kind has to be at its offset for compatibility with static initializer macros) +fn mutex_kind_offset<'mir, 'tcx: 'mir>(ecx: &MiriInterpCx<'mir, 'tcx>) -> u64 { + // These offsets are picked for compatibility with Linux's static initializer + // macros, e.g. PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP.) + let offset = if ecx.pointer_size().bytes() == 8 { 16 } else { 12 }; + + // Sanity-check this against PTHREAD_MUTEX_INITIALIZER (but only once): + // the kind must start out as PTHREAD_MUTEX_DEFAULT. + static SANITY: AtomicBool = AtomicBool::new(false); + if !SANITY.swap(true, Ordering::Relaxed) { + let static_initializer = ecx.eval_path(&["libc", "PTHREAD_MUTEX_INITIALIZER"]); + let kind_field = static_initializer + .offset(Size::from_bytes(mutex_kind_offset(ecx)), ecx.machine.layouts.i32, ecx) + .unwrap(); + let kind = ecx.read_scalar(&kind_field).unwrap().to_i32().unwrap(); + assert_eq!( + kind, + ecx.eval_libc_i32("PTHREAD_MUTEX_DEFAULT"), + "PTHREAD_MUTEX_INITIALIZER is incompatible with our pthread_mutex layout: kind is not PTHREAD_MUTEX_DEFAULT" + ); + } + + offset +} fn mutex_get_id<'mir, 'tcx: 'mir>( ecx: &mut MiriInterpCx<'mir, 'tcx>, mutex_op: &OpTy<'tcx, Provenance>, ) -> InterpResult<'tcx, MutexId> { - ecx.mutex_get_or_create_id(mutex_op, ecx.libc_ty_layout("pthread_mutex_t"), 4) + ecx.mutex_get_or_create_id( + mutex_op, + ecx.libc_ty_layout("pthread_mutex_t"), + mutex_id_offset(ecx)?, + ) } fn mutex_reset_id<'mir, 'tcx: 'mir>( @@ -80,8 +141,8 @@ fn mutex_reset_id<'mir, 'tcx: 'mir>( ) -> InterpResult<'tcx, ()> { ecx.deref_pointer_and_write( mutex_op, - 4, - Scalar::from_i32(0), + mutex_id_offset(ecx)?, + Scalar::from_u32(0), ecx.libc_ty_layout("pthread_mutex_t"), ecx.machine.layouts.u32, ) @@ -91,10 +152,9 @@ fn mutex_get_kind<'mir, 'tcx: 'mir>( ecx: &MiriInterpCx<'mir, 'tcx>, mutex_op: &OpTy<'tcx, Provenance>, ) -> InterpResult<'tcx, i32> { - let offset = if ecx.pointer_size().bytes() == 8 { 16 } else { 12 }; ecx.deref_pointer_and_read( mutex_op, - offset, + mutex_kind_offset(ecx), ecx.libc_ty_layout("pthread_mutex_t"), ecx.machine.layouts.i32, )? @@ -106,10 +166,9 @@ fn mutex_set_kind<'mir, 'tcx: 'mir>( mutex_op: &OpTy<'tcx, Provenance>, kind: i32, ) -> InterpResult<'tcx, ()> { - let offset = if ecx.pointer_size().bytes() == 8 { 16 } else { 12 }; ecx.deref_pointer_and_write( mutex_op, - offset, + mutex_kind_offset(ecx), Scalar::from_i32(kind), ecx.libc_ty_layout("pthread_mutex_t"), ecx.machine.layouts.i32, @@ -117,24 +176,60 @@ fn mutex_set_kind<'mir, 'tcx: 'mir>( } // pthread_rwlock_t is between 32 and 56 bytes, depending on the platform. +// We ignore the platform layout and store our own fields: +// - id: u32 + +fn rwlock_id_offset<'mir, 'tcx: 'mir>(ecx: &MiriInterpCx<'mir, 'tcx>) -> InterpResult<'tcx, u64> { + let offset = match &*ecx.tcx.sess.target.os { + "linux" | "illumos" | "solaris" => 0, + // macOS stores a signature in the first bytes, so we have to move to offset 4. + "macos" => 4, + os => throw_unsup_format!("`pthread_rwlock` is not supported on {os}"), + }; + + // Sanity-check this against PTHREAD_RWLOCK_INITIALIZER (but only once): + // the id must start out as 0. + static SANITY: AtomicBool = AtomicBool::new(false); + if !SANITY.swap(true, Ordering::Relaxed) { + let static_initializer = ecx.eval_path(&["libc", "PTHREAD_RWLOCK_INITIALIZER"]); + let id_field = static_initializer + .offset(Size::from_bytes(offset), ecx.machine.layouts.u32, ecx) + .unwrap(); + let id = ecx.read_scalar(&id_field).unwrap().to_u32().unwrap(); + assert_eq!( + id, 0, + "PTHREAD_RWLOCK_INITIALIZER is incompatible with our pthread_rwlock layout: id is not 0" + ); + } -// Our chosen memory layout for the emulated rwlock (does not have to match the platform layout!): -// bytes 0-3: reserved for signature on macOS -// (need to avoid this because it is set by static initializer macros) -// bytes 4-7: rwlock id as u32 or 0 if id is not assigned yet. + Ok(offset) +} fn rwlock_get_id<'mir, 'tcx: 'mir>( ecx: &mut MiriInterpCx<'mir, 'tcx>, rwlock_op: &OpTy<'tcx, Provenance>, ) -> InterpResult<'tcx, RwLockId> { - ecx.rwlock_get_or_create_id(rwlock_op, ecx.libc_ty_layout("pthread_rwlock_t"), 4) + ecx.rwlock_get_or_create_id( + rwlock_op, + ecx.libc_ty_layout("pthread_rwlock_t"), + rwlock_id_offset(ecx)?, + ) } -// pthread_condattr_t +// pthread_condattr_t. +// We ignore the platform layout and store our own fields: +// - clock: i32 -// Our chosen memory layout for emulation (does not have to match the platform layout!): -// store an i32 in the first four bytes equal to the corresponding libc clock id constant -// (e.g. CLOCK_REALTIME). +#[inline] +fn condattr_clock_offset<'mir, 'tcx: 'mir>( + ecx: &MiriInterpCx<'mir, 'tcx>, +) -> InterpResult<'tcx, u64> { + Ok(match &*ecx.tcx.sess.target.os { + "linux" | "illumos" | "solaris" => 0, + // macOS does not have a clock attribute. + os => throw_unsup_format!("`pthread_condattr` clock field is not supported on {os}"), + }) +} fn condattr_get_clock_id<'mir, 'tcx: 'mir>( ecx: &MiriInterpCx<'mir, 'tcx>, @@ -142,7 +237,7 @@ fn condattr_get_clock_id<'mir, 'tcx: 'mir>( ) -> InterpResult<'tcx, i32> { ecx.deref_pointer_and_read( attr_op, - 0, + condattr_clock_offset(ecx)?, ecx.libc_ty_layout("pthread_condattr_t"), ecx.machine.layouts.i32, )? @@ -156,27 +251,86 @@ fn condattr_set_clock_id<'mir, 'tcx: 'mir>( ) -> InterpResult<'tcx, ()> { ecx.deref_pointer_and_write( attr_op, - 0, + condattr_clock_offset(ecx)?, Scalar::from_i32(clock_id), ecx.libc_ty_layout("pthread_condattr_t"), ecx.machine.layouts.i32, ) } -// pthread_cond_t +// pthread_cond_t. +// We ignore the platform layout and store our own fields: +// - id: u32 +// - clock: i32 + +fn cond_id_offset<'mir, 'tcx: 'mir>(ecx: &MiriInterpCx<'mir, 'tcx>) -> InterpResult<'tcx, u64> { + let offset = match &*ecx.tcx.sess.target.os { + "linux" | "illumos" | "solaris" => 0, + // macOS stores a signature in the first bytes, so we have to move to offset 4. + "macos" => 4, + os => throw_unsup_format!("`pthread_cond` is not supported on {os}"), + }; + + // Sanity-check this against PTHREAD_COND_INITIALIZER (but only once): + // the id must start out as 0. + static SANITY: AtomicBool = AtomicBool::new(false); + if !SANITY.swap(true, Ordering::Relaxed) { + let static_initializer = ecx.eval_path(&["libc", "PTHREAD_COND_INITIALIZER"]); + let id_field = static_initializer + .offset(Size::from_bytes(offset), ecx.machine.layouts.u32, ecx) + .unwrap(); + let id = ecx.read_scalar(&id_field).unwrap().to_u32().unwrap(); + assert_eq!( + id, 0, + "PTHREAD_COND_INITIALIZER is incompatible with our pthread_cond layout: id is not 0" + ); + } + + Ok(offset) +} + +/// Determines whether this clock represents the real-time clock, CLOCK_REALTIME. +fn is_cond_clock_realtime<'mir, 'tcx: 'mir>(ecx: &MiriInterpCx<'mir, 'tcx>, clock_id: i32) -> bool { + // To ensure compatibility with PTHREAD_COND_INITIALIZER on all platforms, + // we can't just compare with CLOCK_REALTIME: on Solarish, PTHREAD_COND_INITIALIZER + // makes the clock 0 but CLOCK_REALTIME is 3. + // However, we need to always be able to distinguish this from CLOCK_MONOTONIC. + clock_id == ecx.eval_libc_i32("CLOCK_REALTIME") + || (clock_id == 0 && clock_id != ecx.eval_libc_i32("CLOCK_MONOTONIC")) +} -// Our chosen memory layout for the emulated conditional variable (does not have -// to match the platform layout!): +fn cond_clock_offset<'mir, 'tcx: 'mir>(ecx: &MiriInterpCx<'mir, 'tcx>) -> u64 { + // macOS doesn't have a clock attribute, but to keep the code uniform we store + // a clock ID in the pthread_cond_t anyway. There's enough space. + let offset = 8; + + // Sanity-check this against PTHREAD_COND_INITIALIZER (but only once): + // the clock must start out as CLOCK_REALTIME. + static SANITY: AtomicBool = AtomicBool::new(false); + if !SANITY.swap(true, Ordering::Relaxed) { + let static_initializer = ecx.eval_path(&["libc", "PTHREAD_COND_INITIALIZER"]); + let id_field = static_initializer + .offset(Size::from_bytes(offset), ecx.machine.layouts.i32, ecx) + .unwrap(); + let id = ecx.read_scalar(&id_field).unwrap().to_i32().unwrap(); + assert!( + is_cond_clock_realtime(ecx, id), + "PTHREAD_COND_INITIALIZER is incompatible with our pthread_cond layout: clock is not CLOCK_REALTIME" + ); + } -// bytes 0-3: reserved for signature on macOS -// bytes 4-7: the conditional variable id as u32 or 0 if id is not assigned yet. -// bytes 8-11: the clock id constant as i32 + offset +} fn cond_get_id<'mir, 'tcx: 'mir>( ecx: &mut MiriInterpCx<'mir, 'tcx>, cond_op: &OpTy<'tcx, Provenance>, ) -> InterpResult<'tcx, CondvarId> { - ecx.condvar_get_or_create_id(cond_op, ecx.libc_ty_layout("pthread_cond_t"), 4) + ecx.condvar_get_or_create_id( + cond_op, + ecx.libc_ty_layout("pthread_cond_t"), + cond_id_offset(ecx)?, + ) } fn cond_reset_id<'mir, 'tcx: 'mir>( @@ -185,7 +339,7 @@ fn cond_reset_id<'mir, 'tcx: 'mir>( ) -> InterpResult<'tcx, ()> { ecx.deref_pointer_and_write( cond_op, - 4, + cond_id_offset(ecx)?, Scalar::from_i32(0), ecx.libc_ty_layout("pthread_cond_t"), ecx.machine.layouts.u32, @@ -198,7 +352,7 @@ fn cond_get_clock_id<'mir, 'tcx: 'mir>( ) -> InterpResult<'tcx, i32> { ecx.deref_pointer_and_read( cond_op, - 8, + cond_clock_offset(ecx), ecx.libc_ty_layout("pthread_cond_t"), ecx.machine.layouts.i32, )? @@ -212,7 +366,7 @@ fn cond_set_clock_id<'mir, 'tcx: 'mir>( ) -> InterpResult<'tcx, ()> { ecx.deref_pointer_and_write( cond_op, - 8, + cond_clock_offset(ecx), Scalar::from_i32(clock_id), ecx.libc_ty_layout("pthread_cond_t"), ecx.machine.layouts.i32, @@ -279,13 +433,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) -> InterpResult<'tcx, i32> { let this = self.eval_context_mut(); - if !matches!(&*this.tcx.sess.target.os, "linux" | "macos") { - throw_unsup_format!( - "`pthread_mutexattr_init` is not supported on {}", - this.tcx.sess.target.os - ); - } - let default_kind = this.eval_libc_i32("PTHREAD_MUTEX_DEFAULT"); mutexattr_set_kind(this, attr_op, default_kind)?; @@ -368,13 +515,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) -> InterpResult<'tcx, i32> { let this = self.eval_context_mut(); - if !matches!(&*this.tcx.sess.target.os, "linux" | "macos") { - throw_unsup_format!( - "`pthread_mutex_init` is not supported on {}", - this.tcx.sess.target.os - ); - } - let attr = this.read_pointer(attr_op)?; let kind = if this.ptr_is_null(attr)? { this.eval_libc_i32("PTHREAD_MUTEX_DEFAULT") @@ -529,13 +669,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) -> InterpResult<'tcx, i32> { let this = self.eval_context_mut(); - if !matches!(&*this.tcx.sess.target.os, "linux" | "macos") { - throw_unsup_format!( - "`pthread_rwlock_rdlock` is not supported on {}", - this.tcx.sess.target.os - ); - } - let id = rwlock_get_id(this, rwlock_op)?; let active_thread = this.get_active_thread(); @@ -554,13 +687,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) -> InterpResult<'tcx, i32> { let this = self.eval_context_mut(); - if !matches!(&*this.tcx.sess.target.os, "linux" | "macos") { - throw_unsup_format!( - "`pthread_rwlock_tryrdlock` is not supported on {}", - this.tcx.sess.target.os - ); - } - let id = rwlock_get_id(this, rwlock_op)?; let active_thread = this.get_active_thread(); @@ -578,13 +704,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) -> InterpResult<'tcx, i32> { let this = self.eval_context_mut(); - if !matches!(&*this.tcx.sess.target.os, "linux" | "macos") { - throw_unsup_format!( - "`pthread_rwlock_wrlock` is not supported on {}", - this.tcx.sess.target.os - ); - } - let id = rwlock_get_id(this, rwlock_op)?; let active_thread = this.get_active_thread(); @@ -615,13 +734,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) -> InterpResult<'tcx, i32> { let this = self.eval_context_mut(); - if !matches!(&*this.tcx.sess.target.os, "linux" | "macos") { - throw_unsup_format!( - "`pthread_rwlock_trywrlock` is not supported on {}", - this.tcx.sess.target.os - ); - } - let id = rwlock_get_id(this, rwlock_op)?; let active_thread = this.get_active_thread(); @@ -639,13 +751,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) -> InterpResult<'tcx, i32> { let this = self.eval_context_mut(); - if !matches!(&*this.tcx.sess.target.os, "linux" | "macos") { - throw_unsup_format!( - "`pthread_rwlock_unlock` is not supported on {}", - this.tcx.sess.target.os - ); - } - let id = rwlock_get_id(this, rwlock_op)?; let active_thread = this.get_active_thread(); @@ -665,13 +770,6 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) -> InterpResult<'tcx, i32> { let this = self.eval_context_mut(); - if !matches!(&*this.tcx.sess.target.os, "linux" | "macos") { - throw_unsup_format!( - "`pthread_rwlock_destroy` is not supported on {}", - this.tcx.sess.target.os - ); - } - let id = rwlock_get_id(this, rwlock_op)?; if this.rwlock_is_locked(id) { @@ -696,19 +794,15 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) -> InterpResult<'tcx, i32> { let this = self.eval_context_mut(); - if !matches!(&*this.tcx.sess.target.os, "linux" | "macos") { - throw_unsup_format!( - "`pthread_condattr_init` is not supported on {}", - this.tcx.sess.target.os - ); + // no clock attribute on macOS + if this.tcx.sess.target.os != "macos" { + // The default value of the clock attribute shall refer to the system + // clock. + // https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_condattr_setclock.html + let default_clock_id = this.eval_libc_i32("CLOCK_REALTIME"); + condattr_set_clock_id(this, attr_op, default_clock_id)?; } - // The default value of the clock attribute shall refer to the system - // clock. - // https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_condattr_setclock.html - let default_clock_id = this.eval_libc_i32("CLOCK_REALTIME"); - condattr_set_clock_id(this, attr_op, default_clock_id)?; - Ok(0) } @@ -752,8 +846,12 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let this = self.eval_context_mut(); // Destroying an uninit pthread_condattr is UB, so check to make sure it's not uninit. - condattr_get_clock_id(this, attr_op)?; + // There's no clock attribute on macOS. + if this.tcx.sess.target.os != "macos" { + condattr_get_clock_id(this, attr_op)?; + } + // De-init the entire thing. // This might lead to false positives, see comment in pthread_mutexattr_destroy this.write_uninit( &this.deref_pointer_as(attr_op, this.libc_ty_layout("pthread_condattr_t"))?, @@ -769,15 +867,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) -> InterpResult<'tcx, i32> { let this = self.eval_context_mut(); - if !matches!(&*this.tcx.sess.target.os, "linux" | "macos") { - throw_unsup_format!( - "`pthread_cond_init` is not supported on {}", - this.tcx.sess.target.os - ); - } - let attr = this.read_pointer(attr_op)?; - let clock_id = if this.ptr_is_null(attr)? { + // Default clock if `attr` is null, and on macOS where there is no clock attribute. + let clock_id = if this.ptr_is_null(attr)? || this.tcx.sess.target.os == "macos" { this.eval_libc_i32("CLOCK_REALTIME") } else { condattr_get_clock_id(this, attr_op)? @@ -858,7 +950,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } }; - let timeout_time = if clock_id == this.eval_libc_i32("CLOCK_REALTIME") { + let timeout_time = if is_cond_clock_realtime(this, clock_id) { this.check_no_isolation("`pthread_cond_timedwait` with `CLOCK_REALTIME`")?; CallbackTime::RealTime(SystemTime::UNIX_EPOCH.checked_add(duration).unwrap()) } else if clock_id == this.eval_libc_i32("CLOCK_MONOTONIC") { diff --git a/src/tools/miri/src/shims/unix/thread.rs b/src/tools/miri/src/shims/unix/thread.rs index 2a56cd35dcbf3..9e09401a81584 100644 --- a/src/tools/miri/src/shims/unix/thread.rs +++ b/src/tools/miri/src/shims/unix/thread.rs @@ -42,7 +42,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { throw_unsup_format!("Miri supports pthread_join only with retval==NULL"); } - let thread_id = this.read_target_usize(thread)?; + let thread_id = this.read_scalar(thread)?.to_int(this.libc_ty_layout("pthread_t").size)?; this.join_thread_exclusive(thread_id.try_into().expect("thread ID should fit in u32"))?; Ok(0) @@ -51,7 +51,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { fn pthread_detach(&mut self, thread: &OpTy<'tcx, Provenance>) -> InterpResult<'tcx, i32> { let this = self.eval_context_mut(); - let thread_id = this.read_target_usize(thread)?; + let thread_id = this.read_scalar(thread)?.to_int(this.libc_ty_layout("pthread_t").size)?; this.detach_thread( thread_id.try_into().expect("thread ID should fit in u32"), /*allow_terminated_joined*/ false, @@ -64,7 +64,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { let this = self.eval_context_mut(); let thread_id = this.get_active_thread(); - Ok(Scalar::from_target_usize(thread_id.into(), this)) + Ok(Scalar::from_uint(thread_id.to_u32(), this.libc_ty_layout("pthread_t").size)) } /// Set the name of the current thread. `max_name_len` is the maximal length of the name @@ -77,7 +77,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) -> InterpResult<'tcx, Scalar> { let this = self.eval_context_mut(); - let thread = ThreadId::try_from(thread.to_target_usize(this)?).unwrap(); + let thread = thread.to_int(this.libc_ty_layout("pthread_t").size)?; + let thread = ThreadId::try_from(thread).unwrap(); let name = name.to_pointer(this)?; let name = this.read_c_str(name)?.to_owned(); @@ -100,7 +101,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { ) -> InterpResult<'tcx, Scalar> { let this = self.eval_context_mut(); - let thread = ThreadId::try_from(thread.to_target_usize(this)?).unwrap(); + let thread = thread.to_int(this.libc_ty_layout("pthread_t").size)?; + let thread = ThreadId::try_from(thread).unwrap(); let name_out = name_out.to_pointer(this)?; let len = len.to_target_usize(this)?; diff --git a/src/tools/miri/src/shims/windows/env.rs b/src/tools/miri/src/shims/windows/env.rs index e91623ac87160..b3bc5d4d85235 100644 --- a/src/tools/miri/src/shims/windows/env.rs +++ b/src/tools/miri/src/shims/windows/env.rs @@ -1,5 +1,5 @@ use std::env; -use std::ffi::OsString; +use std::ffi::{OsStr, OsString}; use std::io::ErrorKind; use rustc_data_structures::fx::FxHashMap; @@ -9,7 +9,7 @@ use helpers::windows_check_buffer_size; #[derive(Default)] pub struct WindowsEnvVars { - /// Stores the environment varialbles. + /// Stores the environment variables. map: FxHashMap, } @@ -26,6 +26,11 @@ impl WindowsEnvVars { ) -> InterpResult<'tcx, Self> { Ok(Self { map: env_vars }) } + + /// Implementation detail for [`InterpCx::get_env_var`]. + pub(crate) fn get<'tcx>(&self, name: &OsStr) -> InterpResult<'tcx, Option> { + Ok(self.map.get(name).cloned()) + } } impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} diff --git a/src/tools/miri/src/shims/windows/foreign_items.rs b/src/tools/miri/src/shims/windows/foreign_items.rs index e8ae80261c662..dba5b7a906f91 100644 --- a/src/tools/miri/src/shims/windows/foreign_items.rs +++ b/src/tools/miri/src/shims/windows/foreign_items.rs @@ -12,10 +12,9 @@ use crate::shims::alloc::EvalContextExt as _; use crate::shims::os_str::bytes_to_os_str; use crate::shims::windows::*; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; use shims::windows::handle::{Handle, PseudoHandle}; -fn is_dyn_sym(name: &str) -> bool { +pub fn is_dyn_sym(name: &str) -> bool { // std does dynamic detection for these symbols matches!( name, @@ -86,7 +85,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); // See `fn emulate_foreign_item_inner` in `shims/foreign_items.rs` for the general pattern. @@ -507,6 +506,12 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { } // Miscellaneous + "ExitProcess" => { + let [code] = + this.check_shim(abi, Abi::System { unwind: false }, link_name, args)?; + let code = this.read_scalar(code)?.to_u32()?; + throw_machine_stop!(TerminationInfo::Exit { code: code.into(), leak_check: false }); + } "SystemFunction036" => { // This is really 'RtlGenRandom'. let [ptr, len] = @@ -721,9 +726,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> { this.write_null(dest)?; } - _ => return Ok(EmulateForeignItemResult::NotSupported), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/x86/aesni.rs b/src/tools/miri/src/shims/x86/aesni.rs index 6c090d877ea3e..8dc3748a12d47 100644 --- a/src/tools/miri/src/shims/x86/aesni.rs +++ b/src/tools/miri/src/shims/x86/aesni.rs @@ -4,7 +4,6 @@ use rustc_span::Symbol; use rustc_target::spec::abi::Abi; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: @@ -16,7 +15,7 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); this.expect_target_feature_for_intrinsic(link_name, "aes")?; // Prefix should have already been checked. @@ -126,9 +125,9 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: } // TODO: Implement the `llvm.x86.aesni.aeskeygenassist` when possible // with an external crate. - _ => return Ok(EmulateForeignItemResult::NotSupported), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/x86/avx.rs b/src/tools/miri/src/shims/x86/avx.rs index 41c20d768f77a..86ef180a44893 100644 --- a/src/tools/miri/src/shims/x86/avx.rs +++ b/src/tools/miri/src/shims/x86/avx.rs @@ -11,7 +11,6 @@ use super::{ FloatBinOp, FloatUnaryOp, }; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: @@ -23,7 +22,7 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); this.expect_target_feature_for_intrinsic(link_name, "avx")?; // Prefix should have already been checked. @@ -343,8 +342,8 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: this.write_scalar(Scalar::from_i32(res.into()), dest)?; } - _ => return Ok(EmulateForeignItemResult::NotSupported), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/x86/avx2.rs b/src/tools/miri/src/shims/x86/avx2.rs index bbf53f9f1e5d0..783be802bb73b 100644 --- a/src/tools/miri/src/shims/x86/avx2.rs +++ b/src/tools/miri/src/shims/x86/avx2.rs @@ -9,7 +9,6 @@ use super::{ packuswb, pmulhrsw, psign, shift_simd_by_scalar, shift_simd_by_simd, ShiftOp, }; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: @@ -21,7 +20,7 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); this.expect_target_feature_for_intrinsic(link_name, "avx2")?; // Prefix should have already been checked. @@ -71,6 +70,8 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: let (dest, dest_len) = this.mplace_to_simd(dest)?; // There are cases like dest: i32x4, offsets: i64x2 + // If dest has more elements than offset, extra dest elements are filled with zero. + // If offsets has more elements than dest, extra offsets are ignored. let actual_len = dest_len.min(offsets_len); assert_eq!(dest_len, mask_len); @@ -437,8 +438,8 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: shift_simd_by_simd(this, left, right, which, dest)?; } - _ => return Ok(EmulateForeignItemResult::NotSupported), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/x86/mod.rs b/src/tools/miri/src/shims/x86/mod.rs index cf4d6a04bec87..e519fa5508d28 100644 --- a/src/tools/miri/src/shims/x86/mod.rs +++ b/src/tools/miri/src/shims/x86/mod.rs @@ -10,7 +10,6 @@ use rustc_target::spec::abi::Abi; use crate::*; use helpers::bool_to_simd_element; -use shims::foreign_items::EmulateForeignItemResult; mod aesni; mod avx; @@ -31,7 +30,7 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); // Prefix should have already been checked. let unprefixed_name = link_name.as_str().strip_prefix("llvm.x86.").unwrap(); @@ -43,7 +42,7 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: // https://www.intel.com/content/www/us/en/docs/cpp-compiler/developer-guide-reference/2021-8/addcarry-u32-addcarry-u64.html "addcarry.32" | "addcarry.64" => { if unprefixed_name == "addcarry.64" && this.tcx.sess.target.arch != "x86_64" { - return Ok(EmulateForeignItemResult::NotSupported); + return Ok(EmulateItemResult::NotSupported); } let [c_in, a, b] = this.check_shim(abi, Abi::Unadjusted, link_name, args)?; @@ -69,7 +68,7 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: // https://www.intel.com/content/www/us/en/docs/cpp-compiler/developer-guide-reference/2021-8/subborrow-u32-subborrow-u64.html "subborrow.32" | "subborrow.64" => { if unprefixed_name == "subborrow.64" && this.tcx.sess.target.arch != "x86_64" { - return Ok(EmulateForeignItemResult::NotSupported); + return Ok(EmulateItemResult::NotSupported); } let [b_in, a, b] = this.check_shim(abi, Abi::Unadjusted, link_name, args)?; @@ -143,9 +142,9 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: ); } - _ => return Ok(EmulateForeignItemResult::NotSupported), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } @@ -739,14 +738,20 @@ fn int_abs<'tcx>( assert_eq!(op_len, dest_len); + let zero = ImmTy::from_int(0, op.layout.field(this, 0)); + for i in 0..dest_len { - let op = this.read_scalar(&this.project_index(&op, i)?)?; + let op = this.read_immediate(&this.project_index(&op, i)?)?; let dest = this.project_index(&dest, i)?; - // Converting to a host "i128" works since the input is always signed. - let res = op.to_int(dest.layout.size)?.unsigned_abs(); + let lt_zero = this.wrapping_binary_op(mir::BinOp::Lt, &op, &zero)?; + let res = if lt_zero.to_scalar().to_bool()? { + this.wrapping_unary_op(mir::UnOp::Neg, &op)? + } else { + op + }; - this.write_scalar(Scalar::from_uint(res, dest.layout.size), &dest)?; + this.write_immediate(*res, &dest)?; } Ok(()) @@ -1127,6 +1132,13 @@ fn pmulhrsw<'tcx>( Ok(()) } +/// Packs two N-bit integer vectors to a single N/2-bit integers. +/// +/// The conversion from N-bit to N/2-bit should be provided by `f`. +/// +/// Each 128-bit chunk is treated independently (i.e., the value for +/// the is i-th 128-bit chunk of `dest` is calculated with the i-th +/// 128-bit chunks of `left` and `right`). fn pack_generic<'tcx>( this: &mut crate::MiriInterpCx<'_, 'tcx>, left: &OpTy<'tcx, Provenance>, diff --git a/src/tools/miri/src/shims/x86/sse.rs b/src/tools/miri/src/shims/x86/sse.rs index 176088373196f..ea967a8cf72bb 100644 --- a/src/tools/miri/src/shims/x86/sse.rs +++ b/src/tools/miri/src/shims/x86/sse.rs @@ -8,7 +8,6 @@ use super::{ FloatUnaryOp, }; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: @@ -20,7 +19,7 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); this.expect_target_feature_for_intrinsic(link_name, "sse")?; // Prefix should have already been checked. @@ -211,8 +210,8 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: this.copy_op(&this.project_index(&left, i)?, &this.project_index(&dest, i)?)?; } } - _ => return Ok(EmulateForeignItemResult::NotSupported), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/x86/sse2.rs b/src/tools/miri/src/shims/x86/sse2.rs index c9ed751d36c43..31fa66a496f3f 100644 --- a/src/tools/miri/src/shims/x86/sse2.rs +++ b/src/tools/miri/src/shims/x86/sse2.rs @@ -7,7 +7,6 @@ use super::{ packuswb, shift_simd_by_scalar, FloatBinOp, ShiftOp, }; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: @@ -19,7 +18,7 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); this.expect_target_feature_for_intrinsic(link_name, "sse2")?; // Prefix should have already been checked. @@ -387,8 +386,8 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: this.copy_op(&this.project_index(&left, i)?, &this.project_index(&dest, i)?)?; } } - _ => return Ok(EmulateForeignItemResult::NotSupported), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/x86/sse3.rs b/src/tools/miri/src/shims/x86/sse3.rs index 5ac30dca79a2f..8de339eb9e582 100644 --- a/src/tools/miri/src/shims/x86/sse3.rs +++ b/src/tools/miri/src/shims/x86/sse3.rs @@ -4,7 +4,6 @@ use rustc_target::spec::abi::Abi; use super::horizontal_bin_op; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: @@ -16,7 +15,7 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); this.expect_target_feature_for_intrinsic(link_name, "sse3")?; // Prefix should have already been checked. @@ -50,8 +49,8 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: this.mem_copy(src_ptr, dest.ptr(), dest.layout.size, /*nonoverlapping*/ true)?; } - _ => return Ok(EmulateForeignItemResult::NotSupported), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/x86/sse41.rs b/src/tools/miri/src/shims/x86/sse41.rs index 19bc27421d348..011a7a16c68bd 100644 --- a/src/tools/miri/src/shims/x86/sse41.rs +++ b/src/tools/miri/src/shims/x86/sse41.rs @@ -3,7 +3,6 @@ use rustc_target::spec::abi::Abi; use super::{conditional_dot_product, mpsadbw, packusdw, round_all, round_first, test_bits_masked}; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: @@ -15,7 +14,7 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); this.expect_target_feature_for_intrinsic(link_name, "sse4.1")?; // Prefix should have already been checked. @@ -175,8 +174,8 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: this.write_scalar(Scalar::from_i32(res.into()), dest)?; } - _ => return Ok(EmulateForeignItemResult::NotSupported), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/src/shims/x86/ssse3.rs b/src/tools/miri/src/shims/x86/ssse3.rs index 4f8e52dbb7d5d..d30de4300886c 100644 --- a/src/tools/miri/src/shims/x86/ssse3.rs +++ b/src/tools/miri/src/shims/x86/ssse3.rs @@ -4,7 +4,6 @@ use rustc_target::spec::abi::Abi; use super::{horizontal_bin_op, int_abs, pmulhrsw, psign}; use crate::*; -use shims::foreign_items::EmulateForeignItemResult; impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {} pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: @@ -16,7 +15,7 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: abi: Abi, args: &[OpTy<'tcx, Provenance>], dest: &MPlaceTy<'tcx, Provenance>, - ) -> InterpResult<'tcx, EmulateForeignItemResult> { + ) -> InterpResult<'tcx, EmulateItemResult> { let this = self.eval_context_mut(); this.expect_target_feature_for_intrinsic(link_name, "ssse3")?; // Prefix should have already been checked. @@ -136,8 +135,8 @@ pub(super) trait EvalContextExt<'mir, 'tcx: 'mir>: psign(this, left, right, dest)?; } - _ => return Ok(EmulateForeignItemResult::NotSupported), + _ => return Ok(EmulateItemResult::NotSupported), } - Ok(EmulateForeignItemResult::NeedsJumping) + Ok(EmulateItemResult::NeedsJumping) } } diff --git a/src/tools/miri/test-cargo-miri/run-test.py b/src/tools/miri/test-cargo-miri/run-test.py index cac11dff77557..2639d29b73de6 100755 --- a/src/tools/miri/test-cargo-miri/run-test.py +++ b/src/tools/miri/test-cargo-miri/run-test.py @@ -34,10 +34,6 @@ def normalize_stdout(str): str = re.sub("finished in \\d+\\.\\d\\ds", "finished in $TIME", str) # the time keeps changing, obviously return str -def normalize_stderr(str): - str = re.sub("Preparing a sysroot for Miri \\(target: [a-z0-9_-]+\\)\\.\\.\\. done\n", "", str) # remove leading cargo-miri setup output - return str - def check_output(actual, path, name): if os.environ.get("RUSTC_BLESS", "0") != "0": # Write the output only if bless is set @@ -69,7 +65,7 @@ def test(name, cmd, stdout_ref, stderr_ref, stdin=b'', env=None): ) (stdout, stderr) = p.communicate(input=stdin) stdout = normalize_stdout(stdout.decode("UTF-8")) - stderr = normalize_stderr(stderr.decode("UTF-8")) + stderr = stderr.decode("UTF-8") stdout_matches = check_output(stdout, stdout_ref, "stdout") stderr_matches = check_output(stderr, stderr_ref, "stderr") diff --git a/src/tools/miri/test_dependencies/Cargo.lock b/src/tools/miri/test_dependencies/Cargo.lock index 11d430bad152c..3dd5eb9b91c55 100644 --- a/src/tools/miri/test_dependencies/Cargo.lock +++ b/src/tools/miri/test_dependencies/Cargo.lock @@ -19,15 +19,15 @@ checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" [[package]] name = "autocfg" -version = "1.1.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" +checksum = "0c4b4d0bd25bd0b74681c0ad21497610ce1b7c91b1022cd21c80c6fbdd9476b0" [[package]] name = "backtrace" -version = "0.3.69" +version = "0.3.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2089b7e3f35b9dd2d0ed921ead4f6d318c27680d4a5bd167b3ee120edb105837" +checksum = "26b05800d2e817c8b3b4b54abd461726265fa9789ae34330622f2db9ee696f9d" dependencies = [ "addr2line", "cc", @@ -40,36 +40,27 @@ dependencies = [ [[package]] name = "bitflags" -version = "1.3.2" +version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" - -[[package]] -name = "bitflags" -version = "2.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "327762f6e5a765692301e5bb513e0d9fef63be86bbc14528052b1cd3e6f03e07" +checksum = "cf4b9d6a944f767f8e5e0db018570623c85f3d925ac718db4e06d0187adb21c1" [[package]] name = "bumpalo" -version = "3.14.0" +version = "3.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec" +checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c" [[package]] name = "bytes" -version = "1.5.0" +version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a2bd12c1caf447e69cd4528f47f94d203fd2582878ecb9e9465484c4148a8223" +checksum = "514de17de45fdb8dc022b1a7975556c53c86f9f0aa5f534b98977b171857c2c9" [[package]] name = "cc" -version = "1.0.83" +version = "1.0.96" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1174fb0b6ec23863f8b971027804a42614e347eafb0a95bf0b12cdae21fc4d0" -dependencies = [ - "libc", -] +checksum = "065a29261d53ba54260972629f9ca6bffa69bac13cd1fed61420f7fa68b9f8bd" [[package]] name = "cfg-if" @@ -89,9 +80,9 @@ dependencies = [ [[package]] name = "fastrand" -version = "2.0.1" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25cbce373ec4653f1a01a31e8a5e5ec0c622dc27ff9c4e6606eefef5cbbed4a5" +checksum = "9fc0510504f03c51ada170672ac806f1f105a88aa97a5281117e1ddc3368e51a" [[package]] name = "getrandom" @@ -106,9 +97,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.11" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe9006bed769170c11f845cf00c7c1e9092aeb3f268e007c3e760ac68008070f" +checksum = "94b22e06ecb0110981051723910cbf0b5f5e09a2062dd7663334ee79a9d1286c" dependencies = [ "cfg-if", "js-sys", @@ -125,36 +116,36 @@ checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" [[package]] name = "hermit-abi" -version = "0.3.3" +version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d77f7ec81a6d05a3abb01ab6eb7590f6083d08449fe5a1c8b1e620283546ccb7" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" [[package]] name = "js-sys" -version = "0.3.66" +version = "0.3.69" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cee9c64da59eae3b50095c18d3e74f8b73c0b86d2792824ff01bbce68ba229ca" +checksum = "29c15563dc2726973df627357ce0c9ddddbea194836909d655df6a75d2cf296d" dependencies = [ "wasm-bindgen", ] [[package]] name = "libc" -version = "0.2.151" +version = "0.2.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "302d7ab3130588088d277783b1e2d2e10c9e9e4a16dd9050e6ec93fb3e7048f4" +checksum = "ae743338b92ff9146ce83992f766a31066a91a8c84a45e0e9f21e7cf6de6d346" [[package]] name = "linux-raw-sys" -version = "0.4.12" +version = "0.4.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4cd1a83af159aa67994778be9070f0ae1bd732942279cabb14f86f986a21456" +checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c" [[package]] name = "lock_api" -version = "0.4.11" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" +checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" dependencies = [ "autocfg", "scopeguard", @@ -162,21 +153,21 @@ dependencies = [ [[package]] name = "log" -version = "0.4.20" +version = "0.4.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" +checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" [[package]] name = "memchr" -version = "2.7.1" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "523dc4f511e55ab87b694dc30d0f820d60906ef06413f93d4d7a1385599cc149" +checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d" [[package]] name = "miniz_oxide" -version = "0.7.1" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e7810e0be55b428ada41041c41f32c9f1a42817901b4ccf45fa3d4b6561e74c7" +checksum = "9d811f3e15f28568be3407c8e7fdb6514c1cda3cb30683f15b6a1a1dc4ea14a7" dependencies = [ "adler", ] @@ -197,7 +188,7 @@ name = "miri-test-deps" version = "0.1.0" dependencies = [ "getrandom 0.1.16", - "getrandom 0.2.11", + "getrandom 0.2.14", "libc", "num_cpus", "page_size", @@ -244,9 +235,9 @@ dependencies = [ [[package]] name = "parking_lot" -version = "0.12.1" +version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +checksum = "7e4af0ca4f6caed20e900d564c242b8e5d4903fdacf31d3daf527b66fe6f42fb" dependencies = [ "lock_api", "parking_lot_core", @@ -254,22 +245,22 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.9" +version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c42a9226546d68acdd9c0a280d17ce19bfe27a46bf68784e4066115788d008e" +checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8" dependencies = [ "cfg-if", "libc", "redox_syscall", "smallvec", - "windows-targets 0.48.5", + "windows-targets 0.52.5", ] [[package]] name = "pin-project-lite" -version = "0.2.13" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" +checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" [[package]] name = "ppv-lite86" @@ -279,18 +270,18 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "proc-macro2" -version = "1.0.76" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "95fc56cda0b5c3325f5fbbd7ff9fda9e02bb00bb3dac51252d2f1bfa1cb8cc8c" +checksum = "3d1597b0c024618f09a9c3b8655b7e430397a36d23fdafec26d6965e9eec3eba" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.35" +version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] @@ -322,16 +313,16 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ - "getrandom 0.2.11", + "getrandom 0.2.14", ] [[package]] name = "redox_syscall" -version = "0.4.1" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +checksum = "469052894dcb553421e483e4209ee581a45100d31b4018de03e5a7ad86374a7e" dependencies = [ - "bitflags 1.3.2", + "bitflags", ] [[package]] @@ -342,11 +333,11 @@ checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" [[package]] name = "rustix" -version = "0.38.28" +version = "0.38.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72e572a5e8ca657d7366229cdde4bd14c4eb5499a9573d4d366fe1b599daa316" +checksum = "70dc5ec042f7a43c4a73241207cecc9873a06d45debb38b329f8541d85c2730f" dependencies = [ - "bitflags 2.4.1", + "bitflags", "errno", "libc", "linux-raw-sys", @@ -361,34 +352,34 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "signal-hook-registry" -version = "1.4.1" +version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" +checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1" dependencies = [ "libc", ] [[package]] name = "smallvec" -version = "1.11.2" +version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dccd0940a2dcdf68d092b8cbab7dc0ad8fa938bf95787e1b916b0e3d0e8e970" +checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67" [[package]] name = "socket2" -version = "0.5.5" +version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b5fac59a5cb5dd637972e5fca70daf0523c9067fcdc4842f053dae04a18f8e9" +checksum = "ce305eb0b4296696835b71df73eb912e0f1ffd2556a501fcede6e0c50349191c" dependencies = [ "libc", - "windows-sys 0.48.0", + "windows-sys 0.52.0", ] [[package]] name = "syn" -version = "2.0.48" +version = "2.0.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f" +checksum = "909518bc7b1c9b779f1bbf07f2929d35af9f0f37e47c6e9ef7f9dddc1e1821f3" dependencies = [ "proc-macro2", "quote", @@ -397,22 +388,21 @@ dependencies = [ [[package]] name = "tempfile" -version = "3.9.0" +version = "3.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01ce4141aa927a6d1bd34a041795abd0db1cccba5d5f24b009f694bdf3a1f3fa" +checksum = "85b77fafb263dd9d05cbeac119526425676db3784113aa9295c88498cbf8bff1" dependencies = [ "cfg-if", "fastrand", - "redox_syscall", "rustix", "windows-sys 0.52.0", ] [[package]] name = "tokio" -version = "1.35.1" +version = "1.37.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c89b4efa943be685f629b149f53829423f8f5531ea21249408e8e2f8671ec104" +checksum = "1adbebffeca75fcfd058afa480fb6c0b81e165a0323f9c9d39c9697e37c46787" dependencies = [ "backtrace", "bytes", @@ -458,9 +448,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.89" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ed0d4f68a3015cc185aff4db9506a015f4b96f95303897bfa23f846db54064e" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" dependencies = [ "cfg-if", "wasm-bindgen-macro", @@ -468,9 +458,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.89" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b56f625e64f3a1084ded111c4d5f477df9f8c92df113852fa5a374dbda78826" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" dependencies = [ "bumpalo", "log", @@ -483,9 +473,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.89" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0162dbf37223cd2afce98f3d0785506dcb8d266223983e4b5b525859e6e182b2" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -493,9 +483,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.89" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f0eb82fcb7930ae6219a7ecfd55b217f5f0893484b7a13022ebb2b2bf20b5283" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2", "quote", @@ -506,9 +496,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.89" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ab9b36309365056cd639da3134bf87fa8f3d86008abf99e612384a6eecd459f" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" [[package]] name = "winapi" @@ -547,7 +537,7 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" dependencies = [ - "windows-targets 0.52.0", + "windows-targets 0.52.5", ] [[package]] @@ -567,17 +557,18 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" dependencies = [ - "windows_aarch64_gnullvm 0.52.0", - "windows_aarch64_msvc 0.52.0", - "windows_i686_gnu 0.52.0", - "windows_i686_msvc 0.52.0", - "windows_x86_64_gnu 0.52.0", - "windows_x86_64_gnullvm 0.52.0", - "windows_x86_64_msvc 0.52.0", + "windows_aarch64_gnullvm 0.52.5", + "windows_aarch64_msvc 0.52.5", + "windows_i686_gnu 0.52.5", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.5", + "windows_x86_64_gnu 0.52.5", + "windows_x86_64_gnullvm 0.52.5", + "windows_x86_64_msvc 0.52.5", ] [[package]] @@ -588,9 +579,9 @@ checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" [[package]] name = "windows_aarch64_gnullvm" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" [[package]] name = "windows_aarch64_msvc" @@ -600,9 +591,9 @@ checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" [[package]] name = "windows_aarch64_msvc" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" [[package]] name = "windows_i686_gnu" @@ -612,9 +603,15 @@ checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" [[package]] name = "windows_i686_gnu" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" [[package]] name = "windows_i686_msvc" @@ -624,9 +621,9 @@ checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" [[package]] name = "windows_i686_msvc" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" [[package]] name = "windows_x86_64_gnu" @@ -636,9 +633,9 @@ checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" [[package]] name = "windows_x86_64_gnu" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" [[package]] name = "windows_x86_64_gnullvm" @@ -648,9 +645,9 @@ checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" [[package]] name = "windows_x86_64_gnullvm" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" [[package]] name = "windows_x86_64_msvc" @@ -660,6 +657,6 @@ checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" [[package]] name = "windows_x86_64_msvc" -version = "0.52.0" +version = "0.52.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" diff --git a/src/tools/miri/tests/extern-so/fail/function_not_in_so.stderr b/src/tools/miri/tests/extern-so/fail/function_not_in_so.stderr index c031cb0146ad6..e905d7d039143 100644 --- a/src/tools/miri/tests/extern-so/fail/function_not_in_so.stderr +++ b/src/tools/miri/tests/extern-so/fail/function_not_in_so.stderr @@ -4,7 +4,8 @@ error: unsupported operation: can't call foreign function `foo` on $OS LL | foo(); | ^^^^^ can't call foreign function `foo` on $OS | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: if this is a basic API commonly used on this target, please report an issue with Miri + = help: however, note that Miri does not aim to support every FFI function out there; for instance, we will not support APIs for things such as GUIs, scripting languages, or databases = note: BACKTRACE: = note: inside `main` at $DIR/function_not_in_so.rs:LL:CC diff --git a/src/tools/miri/tests/fail-dep/shims/fs/close_stdout.stderr b/src/tools/miri/tests/fail-dep/shims/fs/close_stdout.stderr index 7547ec417194c..e1b1b053bbc65 100644 --- a/src/tools/miri/tests/fail-dep/shims/fs/close_stdout.stderr +++ b/src/tools/miri/tests/fail-dep/shims/fs/close_stdout.stderr @@ -4,7 +4,7 @@ error: unsupported operation: cannot close stdout LL | libc::close(1); | ^^^^^^^^^^^^^^ cannot close stdout | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/close_stdout.rs:LL:CC diff --git a/src/tools/miri/tests/fail-dep/shims/fs/read_from_stdout.stderr b/src/tools/miri/tests/fail-dep/shims/fs/read_from_stdout.stderr index 355e16d5c3498..baa6eb5ad6a09 100644 --- a/src/tools/miri/tests/fail-dep/shims/fs/read_from_stdout.stderr +++ b/src/tools/miri/tests/fail-dep/shims/fs/read_from_stdout.stderr @@ -4,7 +4,7 @@ error: unsupported operation: cannot read from stdout LL | libc::read(1, bytes.as_mut_ptr() as *mut libc::c_void, 512); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot read from stdout | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/read_from_stdout.rs:LL:CC diff --git a/src/tools/miri/tests/fail-dep/shims/fs/write_to_stdin.stderr b/src/tools/miri/tests/fail-dep/shims/fs/write_to_stdin.stderr index e2ebe234b0bb0..37323faf560df 100644 --- a/src/tools/miri/tests/fail-dep/shims/fs/write_to_stdin.stderr +++ b/src/tools/miri/tests/fail-dep/shims/fs/write_to_stdin.stderr @@ -4,7 +4,7 @@ error: unsupported operation: cannot write to stdin LL | libc::write(0, bytes.as_ptr() as *const libc::c_void, 5); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot write to stdin | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/write_to_stdin.rs:LL:CC diff --git a/src/tools/miri/tests/fail-dep/shims/sync/libc_pthread_condattr_double_destroy.rs b/src/tools/miri/tests/fail-dep/shims/sync/libc_pthread_condattr_double_destroy.rs index 13e639a867dcc..b5427d55eb07a 100644 --- a/src/tools/miri/tests/fail-dep/shims/sync/libc_pthread_condattr_double_destroy.rs +++ b/src/tools/miri/tests/fail-dep/shims/sync/libc_pthread_condattr_double_destroy.rs @@ -1,4 +1,5 @@ //@ignore-target-windows: No libc on Windows +//@ignore-target-apple: Our macOS condattr don't have any fields so we do not notice this. /// Test that destroying a pthread_condattr twice fails, even without a check for number validity diff --git a/src/tools/miri/tests/fail-dep/tokio/sleep.stderr b/src/tools/miri/tests/fail-dep/tokio/sleep.stderr index 59179478c3025..4b12729bbff9c 100644 --- a/src/tools/miri/tests/fail-dep/tokio/sleep.stderr +++ b/src/tools/miri/tests/fail-dep/tokio/sleep.stderr @@ -9,7 +9,7 @@ LL | | timeout, LL | | )) | |__________^ returning ready events from epoll_wait is not yet implemented | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support error: aborting due to 1 previous error diff --git a/src/tools/miri/tests/fail-dep/unsupported_incomplete_function.stderr b/src/tools/miri/tests/fail-dep/unsupported_incomplete_function.stderr index fabe3bbf1216a..f62622e29bf13 100644 --- a/src/tools/miri/tests/fail-dep/unsupported_incomplete_function.stderr +++ b/src/tools/miri/tests/fail-dep/unsupported_incomplete_function.stderr @@ -4,7 +4,8 @@ error: unsupported operation: can't call foreign function `signal` on $OS LL | libc::signal(libc::SIGPIPE, libc::SIG_IGN); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can't call foreign function `signal` on $OS | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: if this is a basic API commonly used on this target, please report an issue with Miri + = help: however, note that Miri does not aim to support every FFI function out there; for instance, we will not support APIs for things such as GUIs, scripting languages, or databases = note: BACKTRACE: = note: inside `main` at $DIR/unsupported_incomplete_function.rs:LL:CC diff --git a/src/tools/miri/tests/fail/alloc/no_global_allocator.stderr b/src/tools/miri/tests/fail/alloc/no_global_allocator.stderr index bd2a6c628f9e5..82bcb48cbe6ac 100644 --- a/src/tools/miri/tests/fail/alloc/no_global_allocator.stderr +++ b/src/tools/miri/tests/fail/alloc/no_global_allocator.stderr @@ -4,7 +4,8 @@ error: unsupported operation: can't call foreign function `__rust_alloc` on $OS LL | __rust_alloc(1, 1); | ^^^^^^^^^^^^^^^^^^ can't call foreign function `__rust_alloc` on $OS | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: if this is a basic API commonly used on this target, please report an issue with Miri + = help: however, note that Miri does not aim to support every FFI function out there; for instance, we will not support APIs for things such as GUIs, scripting languages, or databases = note: BACKTRACE: = note: inside `start` at $DIR/no_global_allocator.rs:LL:CC diff --git a/src/tools/miri/tests/fail/extern-type-field-offset.stderr b/src/tools/miri/tests/fail/extern-type-field-offset.stderr index cbbf1b3836199..e0d6e9ebf1de7 100644 --- a/src/tools/miri/tests/fail/extern-type-field-offset.stderr +++ b/src/tools/miri/tests/fail/extern-type-field-offset.stderr @@ -4,7 +4,7 @@ error: unsupported operation: `extern type` does not have a known offset LL | let _field = &x.a; | ^^^^ `extern type` does not have a known offset | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/extern-type-field-offset.rs:LL:CC diff --git a/src/tools/miri/tests/fail/extern_static.stderr b/src/tools/miri/tests/fail/extern_static.stderr index 34bb273f04be0..21759f9601904 100644 --- a/src/tools/miri/tests/fail/extern_static.stderr +++ b/src/tools/miri/tests/fail/extern_static.stderr @@ -4,7 +4,7 @@ error: unsupported operation: extern static `FOO` is not supported by Miri LL | let _val = unsafe { std::ptr::addr_of!(FOO) }; | ^^^ extern static `FOO` is not supported by Miri | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/extern_static.rs:LL:CC diff --git a/src/tools/miri/tests/fail/extern_static_in_const.stderr b/src/tools/miri/tests/fail/extern_static_in_const.stderr index 45d1632cce2ee..aa524c064694e 100644 --- a/src/tools/miri/tests/fail/extern_static_in_const.stderr +++ b/src/tools/miri/tests/fail/extern_static_in_const.stderr @@ -4,7 +4,7 @@ error: unsupported operation: extern static `E` is not supported by Miri LL | let _val = X; | ^ extern static `E` is not supported by Miri | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/extern_static_in_const.rs:LL:CC diff --git a/src/tools/miri/tests/fail/extern_static_wrong_size.stderr b/src/tools/miri/tests/fail/extern_static_wrong_size.stderr index 27699d780c228..3c013a5d15d05 100644 --- a/src/tools/miri/tests/fail/extern_static_wrong_size.stderr +++ b/src/tools/miri/tests/fail/extern_static_wrong_size.stderr @@ -4,7 +4,7 @@ error: unsupported operation: extern static `environ` has been declared as `exte LL | let _val = unsafe { environ }; | ^^^^^^^ extern static `environ` has been declared as `extern_static_wrong_size::environ` with a size of 1 bytes and alignment of 1 bytes, but Miri emulates it via an extern static shim with a size of N bytes and alignment of N bytes | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/extern_static_wrong_size.rs:LL:CC diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_array_vs_struct.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_array_vs_struct.stderr index 595235088f6f2..2b2a898ce73bb 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_array_vs_struct.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_array_vs_struct.stderr @@ -7,7 +7,7 @@ LL | g(Default::default()) = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information = help: this means these two types are not *guaranteed* to be ABI-compatible across all targets - = help: if you think this code should be accepted anyway, please report an issue + = help: if you think this code should be accepted anyway, please report an issue with Miri = note: BACKTRACE: = note: inside `main` at $DIR/abi_mismatch_array_vs_struct.rs:LL:CC diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_int_vs_float.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_int_vs_float.stderr index a8b1cf40c043c..752e17116d12f 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_int_vs_float.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_int_vs_float.stderr @@ -7,7 +7,7 @@ LL | g(42) = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information = help: this means these two types are not *guaranteed* to be ABI-compatible across all targets - = help: if you think this code should be accepted anyway, please report an issue + = help: if you think this code should be accepted anyway, please report an issue with Miri = note: BACKTRACE: = note: inside `main` at $DIR/abi_mismatch_int_vs_float.rs:LL:CC diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_raw_pointer.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_raw_pointer.stderr index 60dd3814bf577..907a8e50c411d 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_raw_pointer.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_raw_pointer.stderr @@ -7,7 +7,7 @@ LL | g(&42 as *const i32) = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information = help: this means these two types are not *guaranteed* to be ABI-compatible across all targets - = help: if you think this code should be accepted anyway, please report an issue + = help: if you think this code should be accepted anyway, please report an issue with Miri = note: BACKTRACE: = note: inside `main` at $DIR/abi_mismatch_raw_pointer.rs:LL:CC diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_repr_C.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_repr_C.stderr index 6d42bea9da998..eaacc32bf6880 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_repr_C.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_repr_C.stderr @@ -7,7 +7,7 @@ LL | fnptr(S1(NonZeroI32::new(1).unwrap())); = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information = help: this means these two types are not *guaranteed* to be ABI-compatible across all targets - = help: if you think this code should be accepted anyway, please report an issue + = help: if you think this code should be accepted anyway, please report an issue with Miri = note: BACKTRACE: = note: inside `main` at $DIR/abi_mismatch_repr_C.rs:LL:CC diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.stderr index 198896b0dd765..3793590f84237 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_return_type.stderr @@ -7,7 +7,7 @@ LL | g() = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information = help: this means these two types are not *guaranteed* to be ABI-compatible across all targets - = help: if you think this code should be accepted anyway, please report an issue + = help: if you think this code should be accepted anyway, please report an issue with Miri = note: BACKTRACE: = note: inside `main` at $DIR/abi_mismatch_return_type.rs:LL:CC diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_simple.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_simple.stderr index daf216a142c9c..0c533c14173da 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_simple.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_simple.stderr @@ -7,7 +7,7 @@ LL | g(42) = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information = help: this means these two types are not *guaranteed* to be ABI-compatible across all targets - = help: if you think this code should be accepted anyway, please report an issue + = help: if you think this code should be accepted anyway, please report an issue with Miri = note: BACKTRACE: = note: inside `main` at $DIR/abi_mismatch_simple.rs:LL:CC diff --git a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_vector.stderr b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_vector.stderr index 50f4474cc0e1c..ef4b60b83b1ff 100644 --- a/src/tools/miri/tests/fail/function_pointers/abi_mismatch_vector.stderr +++ b/src/tools/miri/tests/fail/function_pointers/abi_mismatch_vector.stderr @@ -7,7 +7,7 @@ LL | g(Default::default()) = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information = help: this means these two types are not *guaranteed* to be ABI-compatible across all targets - = help: if you think this code should be accepted anyway, please report an issue + = help: if you think this code should be accepted anyway, please report an issue with Miri = note: BACKTRACE: = note: inside `main` at $DIR/abi_mismatch_vector.rs:LL:CC diff --git a/src/tools/miri/tests/fail/intrinsic_fallback_checks_ub.rs b/src/tools/miri/tests/fail/intrinsic_fallback_checks_ub.rs new file mode 100644 index 0000000000000..93c9d3d7814ca --- /dev/null +++ b/src/tools/miri/tests/fail/intrinsic_fallback_checks_ub.rs @@ -0,0 +1,14 @@ +#![feature(rustc_attrs, effects)] + +#[rustc_intrinsic] +#[rustc_nounwind] +#[rustc_do_not_const_check] +#[inline] +pub const fn ptr_guaranteed_cmp(ptr: *const T, other: *const T) -> u8 { + (ptr == other) as u8 +} + +fn main() { + ptr_guaranteed_cmp::<()>(std::ptr::null(), std::ptr::null()); + //~^ ERROR: can only use intrinsic fallback bodies that check UB. +} diff --git a/src/tools/miri/tests/fail/intrinsic_fallback_checks_ub.stderr b/src/tools/miri/tests/fail/intrinsic_fallback_checks_ub.stderr new file mode 100644 index 0000000000000..699dda52096f3 --- /dev/null +++ b/src/tools/miri/tests/fail/intrinsic_fallback_checks_ub.stderr @@ -0,0 +1,14 @@ +error: unsupported operation: miri can only use intrinsic fallback bodies that check UB. After verifying that `ptr_guaranteed_cmp` does so, add the `#[miri::intrinsic_fallback_checks_ub]` attribute to it; also ping @rust-lang/miri when you do that + --> $DIR/intrinsic_fallback_checks_ub.rs:LL:CC + | +LL | ptr_guaranteed_cmp::<()>(std::ptr::null(), std::ptr::null()); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ miri can only use intrinsic fallback bodies that check UB. After verifying that `ptr_guaranteed_cmp` does so, add the `#[miri::intrinsic_fallback_checks_ub]` attribute to it; also ping @rust-lang/miri when you do that + | + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support + = note: BACKTRACE: + = note: inside `main` at $DIR/intrinsic_fallback_checks_ub.rs:LL:CC + +note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace + +error: aborting due to 1 previous error + diff --git a/src/tools/miri/tests/fail/shims/intrinsic_target_feature.rs b/src/tools/miri/tests/fail/intrinsics/intrinsic_target_feature.rs similarity index 100% rename from src/tools/miri/tests/fail/shims/intrinsic_target_feature.rs rename to src/tools/miri/tests/fail/intrinsics/intrinsic_target_feature.rs diff --git a/src/tools/miri/tests/fail/shims/intrinsic_target_feature.stderr b/src/tools/miri/tests/fail/intrinsics/intrinsic_target_feature.stderr similarity index 100% rename from src/tools/miri/tests/fail/shims/intrinsic_target_feature.stderr rename to src/tools/miri/tests/fail/intrinsics/intrinsic_target_feature.stderr diff --git a/src/tools/miri/tests/fail/issue-miri-3288-ice-symbolic-alignment-extern-static.stderr b/src/tools/miri/tests/fail/issue-miri-3288-ice-symbolic-alignment-extern-static.stderr index e5dbe749884cc..4064d7fe4e953 100644 --- a/src/tools/miri/tests/fail/issue-miri-3288-ice-symbolic-alignment-extern-static.stderr +++ b/src/tools/miri/tests/fail/issue-miri-3288-ice-symbolic-alignment-extern-static.stderr @@ -4,7 +4,7 @@ error: unsupported operation: extern static `_dispatch_queue_attr_concurrent` is LL | let _val = *DISPATCH_QUEUE_CONCURRENT; | ^^^^^^^^^^^^^^^^^^^^^^^^^ extern static `_dispatch_queue_attr_concurrent` is not supported by Miri | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/issue-miri-3288-ice-symbolic-alignment-extern-static.rs:LL:CC diff --git a/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-flags.stderr b/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-flags.stderr index 2523e5063e1b5..504485e3b3a41 100644 --- a/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-flags.stderr +++ b/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-flags.stderr @@ -4,7 +4,7 @@ error: unsupported operation: unknown `miri_get_backtrace` flags 2 LL | miri_get_backtrace(2, std::ptr::null_mut()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unknown `miri_get_backtrace` flags 2 | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/bad-backtrace-flags.rs:LL:CC diff --git a/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-resolve-flags.stderr b/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-resolve-flags.stderr index 36446ae283bf7..c1f0ce3d1a8c1 100644 --- a/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-resolve-flags.stderr +++ b/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-resolve-flags.stderr @@ -4,7 +4,7 @@ error: unsupported operation: unknown `miri_resolve_frame` flags 2 LL | miri_resolve_frame(buf[0], 2); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unknown `miri_resolve_frame` flags 2 | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/bad-backtrace-resolve-flags.rs:LL:CC diff --git a/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-resolve-names-flags.stderr b/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-resolve-names-flags.stderr index ff60ab09172fd..fc270593e6369 100644 --- a/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-resolve-names-flags.stderr +++ b/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-resolve-names-flags.stderr @@ -4,7 +4,7 @@ error: unsupported operation: unknown `miri_resolve_frame_names` flags 2 LL | ... miri_resolve_frame_names(buf[0], 2, std::ptr::null_mut(), std::ptr::null_mut()); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unknown `miri_resolve_frame_names` flags 2 | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/bad-backtrace-resolve-names-flags.rs:LL:CC diff --git a/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-size-flags.stderr b/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-size-flags.stderr index 6d4c370050f49..2d70733334d85 100644 --- a/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-size-flags.stderr +++ b/src/tools/miri/tests/fail/shims/backtrace/bad-backtrace-size-flags.stderr @@ -4,7 +4,7 @@ error: unsupported operation: unknown `miri_backtrace_size` flags 2 LL | miri_backtrace_size(2); | ^^^^^^^^^^^^^^^^^^^^^^ unknown `miri_backtrace_size` flags 2 | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/bad-backtrace-size-flags.rs:LL:CC diff --git a/src/tools/miri/tests/fail/unaligned_pointers/promise_alignment.call_unaligned_ptr.stderr b/src/tools/miri/tests/fail/unaligned_pointers/promise_alignment.call_unaligned_ptr.stderr index e23ac5ac2fc5d..6d62db4d3d556 100644 --- a/src/tools/miri/tests/fail/unaligned_pointers/promise_alignment.call_unaligned_ptr.stderr +++ b/src/tools/miri/tests/fail/unaligned_pointers/promise_alignment.call_unaligned_ptr.stderr @@ -4,7 +4,7 @@ error: unsupported operation: `miri_promise_symbolic_alignment`: pointer is not LL | unsafe { utils::miri_promise_symbolic_alignment(align8.add(1).cast(), 8) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `miri_promise_symbolic_alignment`: pointer is not actually aligned | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/promise_alignment.rs:LL:CC diff --git a/src/tools/miri/tests/fail/unaligned_pointers/promise_alignment_zero.stderr b/src/tools/miri/tests/fail/unaligned_pointers/promise_alignment_zero.stderr index b3327e04933d5..3f7ced0b407df 100644 --- a/src/tools/miri/tests/fail/unaligned_pointers/promise_alignment_zero.stderr +++ b/src/tools/miri/tests/fail/unaligned_pointers/promise_alignment_zero.stderr @@ -4,7 +4,7 @@ error: unsupported operation: `miri_promise_symbolic_alignment`: alignment must LL | unsafe { utils::miri_promise_symbolic_alignment(buffer.as_ptr().cast(), 0) }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `miri_promise_symbolic_alignment`: alignment must be a power of 2, got 0 | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/promise_alignment_zero.rs:LL:CC diff --git a/src/tools/miri/tests/fail/unsized-local.stderr b/src/tools/miri/tests/fail/unsized-local.stderr index 0ffda9e6d6317..df54c98bb0e11 100644 --- a/src/tools/miri/tests/fail/unsized-local.stderr +++ b/src/tools/miri/tests/fail/unsized-local.stderr @@ -4,7 +4,7 @@ error: unsupported operation: unsized locals are not supported LL | let x = *(Box::new(A) as Box); | ^ unsized locals are not supported | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: this is likely not a bug in the program; it indicates that the program performed an operation that Miri does not support = note: BACKTRACE: = note: inside `main` at $DIR/unsized-local.rs:LL:CC diff --git a/src/tools/miri/tests/fail/unsupported_foreign_function.stderr b/src/tools/miri/tests/fail/unsupported_foreign_function.stderr index 5a2f415bb84b0..f392e9564c751 100644 --- a/src/tools/miri/tests/fail/unsupported_foreign_function.stderr +++ b/src/tools/miri/tests/fail/unsupported_foreign_function.stderr @@ -4,7 +4,8 @@ error: unsupported operation: can't call foreign function `foo` on $OS LL | foo(); | ^^^^^ can't call foreign function `foo` on $OS | - = help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support + = help: if this is a basic API commonly used on this target, please report an issue with Miri + = help: however, note that Miri does not aim to support every FFI function out there; for instance, we will not support APIs for things such as GUIs, scripting languages, or databases = note: BACKTRACE: = note: inside `main` at $DIR/unsupported_foreign_function.rs:LL:CC diff --git a/src/tools/miri/tests/pass-dep/shims/libc-fs.rs b/src/tools/miri/tests/pass-dep/shims/libc-fs.rs index 4cfc1843a7a2f..0dd849a045dfa 100644 --- a/src/tools/miri/tests/pass-dep/shims/libc-fs.rs +++ b/src/tools/miri/tests/pass-dep/shims/libc-fs.rs @@ -4,10 +4,11 @@ #![feature(io_error_more)] #![feature(io_error_uncategorized)] -use std::ffi::CString; +use std::ffi::{CStr, CString, OsString}; use std::fs::{canonicalize, remove_dir_all, remove_file, File}; use std::io::{Error, ErrorKind, Write}; use std::os::unix::ffi::OsStrExt; +use std::os::unix::io::AsRawFd; use std::path::PathBuf; #[path = "../../utils/mod.rs"] @@ -27,6 +28,14 @@ fn main() { #[cfg(target_os = "linux")] test_o_tmpfile_flag(); test_posix_mkstemp(); + test_posix_realpath_alloc(); + test_posix_realpath_noalloc(); + test_posix_realpath_errors(); + #[cfg(target_os = "linux")] + test_posix_fadvise(); + #[cfg(target_os = "linux")] + test_sync_file_range(); + test_isatty(); } /// Prepare: compute filename and make sure the file does not exist. @@ -256,3 +265,166 @@ fn test_posix_mkstemp() { assert_eq!(e.kind(), std::io::ErrorKind::InvalidInput); } } + +/// Test allocating variant of `realpath`. +fn test_posix_realpath_alloc() { + use std::os::unix::ffi::OsStrExt; + use std::os::unix::ffi::OsStringExt; + + let buf; + let path = utils::tmp().join("miri_test_libc_posix_realpath_alloc"); + let c_path = CString::new(path.as_os_str().as_bytes()).expect("CString::new failed"); + + // Cleanup before test. + remove_file(&path).ok(); + // Create file. + drop(File::create(&path).unwrap()); + unsafe { + let r = libc::realpath(c_path.as_ptr(), std::ptr::null_mut()); + assert!(!r.is_null()); + buf = CStr::from_ptr(r).to_bytes().to_vec(); + libc::free(r as *mut _); + } + let canonical = PathBuf::from(OsString::from_vec(buf)); + assert_eq!(path.file_name(), canonical.file_name()); + + // Cleanup after test. + remove_file(&path).unwrap(); +} + +/// Test non-allocating variant of `realpath`. +fn test_posix_realpath_noalloc() { + use std::ffi::{CStr, CString}; + use std::os::unix::ffi::OsStrExt; + + let path = utils::tmp().join("miri_test_libc_posix_realpath_noalloc"); + let c_path = CString::new(path.as_os_str().as_bytes()).expect("CString::new failed"); + + let mut v = vec![0; libc::PATH_MAX as usize]; + + // Cleanup before test. + remove_file(&path).ok(); + // Create file. + drop(File::create(&path).unwrap()); + unsafe { + let r = libc::realpath(c_path.as_ptr(), v.as_mut_ptr()); + assert!(!r.is_null()); + } + let c = unsafe { CStr::from_ptr(v.as_ptr()) }; + let canonical = PathBuf::from(c.to_str().expect("CStr to str")); + + assert_eq!(path.file_name(), canonical.file_name()); + + // Cleanup after test. + remove_file(&path).unwrap(); +} + +/// Test failure cases for `realpath`. +fn test_posix_realpath_errors() { + use std::ffi::CString; + use std::io::ErrorKind; + + // Test nonexistent path returns an error. + let c_path = CString::new("./nothing_to_see_here").expect("CString::new failed"); + let r = unsafe { libc::realpath(c_path.as_ptr(), std::ptr::null_mut()) }; + assert!(r.is_null()); + let e = std::io::Error::last_os_error(); + assert_eq!(e.raw_os_error(), Some(libc::ENOENT)); + assert_eq!(e.kind(), ErrorKind::NotFound); +} + +#[cfg(target_os = "linux")] +fn test_posix_fadvise() { + use std::io::Write; + + let path = utils::tmp().join("miri_test_libc_posix_fadvise.txt"); + // Cleanup before test + remove_file(&path).ok(); + + // Set up an open file + let mut file = File::create(&path).unwrap(); + let bytes = b"Hello, World!\n"; + file.write(bytes).unwrap(); + + // Test calling posix_fadvise on a file. + let result = unsafe { + libc::posix_fadvise( + file.as_raw_fd(), + 0, + bytes.len().try_into().unwrap(), + libc::POSIX_FADV_DONTNEED, + ) + }; + drop(file); + remove_file(&path).unwrap(); + assert_eq!(result, 0); +} + +#[cfg(target_os = "linux")] +fn test_sync_file_range() { + use std::io::Write; + + let path = utils::tmp().join("miri_test_libc_sync_file_range.txt"); + // Cleanup before test. + remove_file(&path).ok(); + + // Write to a file. + let mut file = File::create(&path).unwrap(); + let bytes = b"Hello, World!\n"; + file.write(bytes).unwrap(); + + // Test calling sync_file_range on the file. + let result_1 = unsafe { + libc::sync_file_range( + file.as_raw_fd(), + 0, + 0, + libc::SYNC_FILE_RANGE_WAIT_BEFORE + | libc::SYNC_FILE_RANGE_WRITE + | libc::SYNC_FILE_RANGE_WAIT_AFTER, + ) + }; + drop(file); + + // Test calling sync_file_range on a file opened for reading. + let file = File::open(&path).unwrap(); + let result_2 = unsafe { + libc::sync_file_range( + file.as_raw_fd(), + 0, + 0, + libc::SYNC_FILE_RANGE_WAIT_BEFORE + | libc::SYNC_FILE_RANGE_WRITE + | libc::SYNC_FILE_RANGE_WAIT_AFTER, + ) + }; + drop(file); + + remove_file(&path).unwrap(); + assert_eq!(result_1, 0); + assert_eq!(result_2, 0); +} + +fn test_isatty() { + // Testing whether our isatty shim returns the right value would require controlling whether + // these streams are actually TTYs, which is hard. + // For now, we just check that these calls are supported at all. + unsafe { + libc::isatty(libc::STDIN_FILENO); + libc::isatty(libc::STDOUT_FILENO); + libc::isatty(libc::STDERR_FILENO); + + // But when we open a file, it is definitely not a TTY. + let path = utils::tmp().join("notatty.txt"); + // Cleanup before test. + remove_file(&path).ok(); + let file = File::create(&path).unwrap(); + + assert_eq!(libc::isatty(file.as_raw_fd()), 0); + assert_eq!(std::io::Error::last_os_error().raw_os_error().unwrap(), libc::ENOTTY); + + // Cleanup after test. + drop(file); + remove_file(&path).unwrap(); + } +} diff --git a/src/tools/miri/tests/pass-dep/shims/libc-getentropy.rs b/src/tools/miri/tests/pass-dep/shims/libc-getentropy.rs deleted file mode 100644 index 4b863f6851618..0000000000000 --- a/src/tools/miri/tests/pass-dep/shims/libc-getentropy.rs +++ /dev/null @@ -1,20 +0,0 @@ -//@ignore-target-windows: no libc - -// on macOS this is not in the `libc` crate. -#[cfg(target_os = "macos")] -extern "C" { - fn getentropy(bytes: *mut libc::c_void, count: libc::size_t) -> libc::c_int; -} - -#[cfg(not(target_os = "macos"))] -use libc::getentropy; - -fn main() { - let mut buf1 = [0u8; 256]; - let mut buf2 = [0u8; 257]; - unsafe { - assert_eq!(getentropy(buf1.as_mut_ptr() as *mut libc::c_void, buf1.len()), 0); - assert_eq!(getentropy(buf2.as_mut_ptr() as *mut libc::c_void, buf2.len()), -1); - assert_eq!(std::io::Error::last_os_error().raw_os_error().unwrap(), libc::EIO); - } -} diff --git a/src/tools/miri/tests/pass-dep/shims/libc-getrandom-without-isolation.rs b/src/tools/miri/tests/pass-dep/shims/libc-getrandom-without-isolation.rs deleted file mode 100644 index 349b447569a4b..0000000000000 --- a/src/tools/miri/tests/pass-dep/shims/libc-getrandom-without-isolation.rs +++ /dev/null @@ -1,41 +0,0 @@ -//@only-target-linux -//@compile-flags: -Zmiri-disable-isolation - -use std::ptr; - -fn main() { - let mut buf = [0u8; 5]; - unsafe { - assert_eq!( - libc::syscall( - libc::SYS_getrandom, - ptr::null_mut::(), - 0 as libc::size_t, - 0 as libc::c_uint, - ), - 0, - ); - assert_eq!( - libc::syscall( - libc::SYS_getrandom, - buf.as_mut_ptr() as *mut libc::c_void, - 5 as libc::size_t, - 0 as libc::c_uint, - ), - 5, - ); - - assert_eq!( - libc::getrandom(ptr::null_mut::(), 0 as libc::size_t, 0 as libc::c_uint), - 0, - ); - assert_eq!( - libc::getrandom( - buf.as_mut_ptr() as *mut libc::c_void, - 5 as libc::size_t, - 0 as libc::c_uint, - ), - 5, - ); - } -} diff --git a/src/tools/miri/tests/pass-dep/shims/libc-misc.rs b/src/tools/miri/tests/pass-dep/shims/libc-misc.rs index f710daf527745..9644920c499c6 100644 --- a/src/tools/miri/tests/pass-dep/shims/libc-misc.rs +++ b/src/tools/miri/tests/pass-dep/shims/libc-misc.rs @@ -1,158 +1,16 @@ //@ignore-target-windows: No libc on Windows //@compile-flags: -Zmiri-disable-isolation #![feature(io_error_more)] +#![feature(pointer_is_aligned_to)] +#![feature(strict_provenance)] -use std::fs::{remove_file, File}; -use std::mem::transmute; -use std::os::unix::io::AsRawFd; -use std::path::PathBuf; - -#[path = "../../utils/mod.rs"] -mod utils; - -/// Test allocating variant of `realpath`. -fn test_posix_realpath_alloc() { - use std::ffi::OsString; - use std::ffi::{CStr, CString}; - use std::os::unix::ffi::OsStrExt; - use std::os::unix::ffi::OsStringExt; - - let buf; - let path = utils::tmp().join("miri_test_libc_posix_realpath_alloc"); - let c_path = CString::new(path.as_os_str().as_bytes()).expect("CString::new failed"); - - // Cleanup before test. - remove_file(&path).ok(); - // Create file. - drop(File::create(&path).unwrap()); - unsafe { - let r = libc::realpath(c_path.as_ptr(), std::ptr::null_mut()); - assert!(!r.is_null()); - buf = CStr::from_ptr(r).to_bytes().to_vec(); - libc::free(r as *mut _); - } - let canonical = PathBuf::from(OsString::from_vec(buf)); - assert_eq!(path.file_name(), canonical.file_name()); - - // Cleanup after test. - remove_file(&path).unwrap(); -} - -/// Test non-allocating variant of `realpath`. -fn test_posix_realpath_noalloc() { - use std::ffi::{CStr, CString}; - use std::os::unix::ffi::OsStrExt; - - let path = utils::tmp().join("miri_test_libc_posix_realpath_noalloc"); - let c_path = CString::new(path.as_os_str().as_bytes()).expect("CString::new failed"); - - let mut v = vec![0; libc::PATH_MAX as usize]; - - // Cleanup before test. - remove_file(&path).ok(); - // Create file. - drop(File::create(&path).unwrap()); - unsafe { - let r = libc::realpath(c_path.as_ptr(), v.as_mut_ptr()); - assert!(!r.is_null()); - } - let c = unsafe { CStr::from_ptr(v.as_ptr()) }; - let canonical = PathBuf::from(c.to_str().expect("CStr to str")); - - assert_eq!(path.file_name(), canonical.file_name()); - - // Cleanup after test. - remove_file(&path).unwrap(); -} - -/// Test failure cases for `realpath`. -fn test_posix_realpath_errors() { - use std::ffi::CString; - use std::io::ErrorKind; - - // Test nonexistent path returns an error. - let c_path = CString::new("./nothing_to_see_here").expect("CString::new failed"); - let r = unsafe { libc::realpath(c_path.as_ptr(), std::ptr::null_mut()) }; - assert!(r.is_null()); - let e = std::io::Error::last_os_error(); - assert_eq!(e.raw_os_error(), Some(libc::ENOENT)); - assert_eq!(e.kind(), ErrorKind::NotFound); -} - -#[cfg(target_os = "linux")] -fn test_posix_fadvise() { - use std::io::Write; - - let path = utils::tmp().join("miri_test_libc_posix_fadvise.txt"); - // Cleanup before test - remove_file(&path).ok(); - - // Set up an open file - let mut file = File::create(&path).unwrap(); - let bytes = b"Hello, World!\n"; - file.write(bytes).unwrap(); - - // Test calling posix_fadvise on a file. - let result = unsafe { - libc::posix_fadvise( - file.as_raw_fd(), - 0, - bytes.len().try_into().unwrap(), - libc::POSIX_FADV_DONTNEED, - ) - }; - drop(file); - remove_file(&path).unwrap(); - assert_eq!(result, 0); -} - -#[cfg(target_os = "linux")] -fn test_sync_file_range() { - use std::io::Write; - - let path = utils::tmp().join("miri_test_libc_sync_file_range.txt"); - // Cleanup before test. - remove_file(&path).ok(); - - // Write to a file. - let mut file = File::create(&path).unwrap(); - let bytes = b"Hello, World!\n"; - file.write(bytes).unwrap(); - - // Test calling sync_file_range on the file. - let result_1 = unsafe { - libc::sync_file_range( - file.as_raw_fd(), - 0, - 0, - libc::SYNC_FILE_RANGE_WAIT_BEFORE - | libc::SYNC_FILE_RANGE_WRITE - | libc::SYNC_FILE_RANGE_WAIT_AFTER, - ) - }; - drop(file); - - // Test calling sync_file_range on a file opened for reading. - let file = File::open(&path).unwrap(); - let result_2 = unsafe { - libc::sync_file_range( - file.as_raw_fd(), - 0, - 0, - libc::SYNC_FILE_RANGE_WAIT_BEFORE - | libc::SYNC_FILE_RANGE_WRITE - | libc::SYNC_FILE_RANGE_WAIT_AFTER, - ) - }; - drop(file); - - remove_file(&path).unwrap(); - assert_eq!(result_1, 0); - assert_eq!(result_2, 0); -} +use std::mem::{self, transmute}; +use std::ptr; /// Tests whether each thread has its own `__errno_location`. fn test_thread_local_errno() { + #[cfg(any(target_os = "illumos", target_os = "solaris"))] + use libc::___errno as __errno_location; #[cfg(target_os = "linux")] use libc::__errno_location; #[cfg(any(target_os = "macos", target_os = "freebsd"))] @@ -171,116 +29,6 @@ fn test_thread_local_errno() { } } -/// Tests whether clock support exists at all -fn test_clocks() { - let mut tp = std::mem::MaybeUninit::::uninit(); - let is_error = unsafe { libc::clock_gettime(libc::CLOCK_REALTIME, tp.as_mut_ptr()) }; - assert_eq!(is_error, 0); - let is_error = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, tp.as_mut_ptr()) }; - assert_eq!(is_error, 0); - #[cfg(any(target_os = "linux", target_os = "freebsd"))] - { - let is_error = unsafe { libc::clock_gettime(libc::CLOCK_REALTIME_COARSE, tp.as_mut_ptr()) }; - assert_eq!(is_error, 0); - let is_error = - unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_COARSE, tp.as_mut_ptr()) }; - assert_eq!(is_error, 0); - } - #[cfg(target_os = "macos")] - { - let is_error = unsafe { libc::clock_gettime(libc::CLOCK_UPTIME_RAW, tp.as_mut_ptr()) }; - assert_eq!(is_error, 0); - } -} - -fn test_posix_gettimeofday() { - let mut tp = std::mem::MaybeUninit::::uninit(); - let tz = std::ptr::null_mut::(); - #[cfg(target_os = "macos")] // `tz` has a different type on macOS - let tz = tz as *mut libc::c_void; - let is_error = unsafe { libc::gettimeofday(tp.as_mut_ptr(), tz) }; - assert_eq!(is_error, 0); - let tv = unsafe { tp.assume_init() }; - assert!(tv.tv_sec > 0); - assert!(tv.tv_usec >= 0); // Theoretically this could be 0. - - // Test that non-null tz returns an error. - let mut tz = std::mem::MaybeUninit::::uninit(); - let tz_ptr = tz.as_mut_ptr(); - #[cfg(target_os = "macos")] // `tz` has a different type on macOS - let tz_ptr = tz_ptr as *mut libc::c_void; - let is_error = unsafe { libc::gettimeofday(tp.as_mut_ptr(), tz_ptr) }; - assert_eq!(is_error, -1); -} - -fn test_localtime_r() { - use std::ffi::CStr; - use std::{env, ptr}; - - // Set timezone to GMT. - let key = "TZ"; - env::set_var(key, "GMT"); - - const TIME_SINCE_EPOCH: libc::time_t = 1712475836; - let custom_time_ptr = &TIME_SINCE_EPOCH; - let mut tm = libc::tm { - tm_sec: 0, - tm_min: 0, - tm_hour: 0, - tm_mday: 0, - tm_mon: 0, - tm_year: 0, - tm_wday: 0, - tm_yday: 0, - tm_isdst: 0, - tm_gmtoff: 0, - tm_zone: std::ptr::null_mut::(), - }; - let res = unsafe { libc::localtime_r(custom_time_ptr, &mut tm) }; - - assert_eq!(tm.tm_sec, 56); - assert_eq!(tm.tm_min, 43); - assert_eq!(tm.tm_hour, 7); - assert_eq!(tm.tm_mday, 7); - assert_eq!(tm.tm_mon, 3); - assert_eq!(tm.tm_year, 124); - assert_eq!(tm.tm_wday, 0); - assert_eq!(tm.tm_yday, 97); - assert_eq!(tm.tm_isdst, -1); - assert_eq!(tm.tm_gmtoff, 0); - unsafe { assert_eq!(CStr::from_ptr(tm.tm_zone).to_str().unwrap(), "+00") }; - - // The returned value is the pointer passed in. - assert!(ptr::eq(res, &mut tm)); - - //Remove timezone setting. - env::remove_var(key); -} - -fn test_isatty() { - // Testing whether our isatty shim returns the right value would require controlling whether - // these streams are actually TTYs, which is hard. - // For now, we just check that these calls are supported at all. - unsafe { - libc::isatty(libc::STDIN_FILENO); - libc::isatty(libc::STDOUT_FILENO); - libc::isatty(libc::STDERR_FILENO); - - // But when we open a file, it is definitely not a TTY. - let path = utils::tmp().join("notatty.txt"); - // Cleanup before test. - remove_file(&path).ok(); - let file = File::create(&path).unwrap(); - - assert_eq!(libc::isatty(file.as_raw_fd()), 0); - assert_eq!(std::io::Error::last_os_error().raw_os_error().unwrap(), libc::ENOTTY); - - // Cleanup after test. - drop(file); - remove_file(&path).unwrap(); - } -} - fn test_memcpy() { unsafe { let src = [1i8, 2, 3]; @@ -306,7 +54,7 @@ fn test_memcpy() { libc::memcpy( &mut dest as *mut i32 as *mut libc::c_void, &src as *const i32 as *const libc::c_void, - std::mem::size_of::(), + mem::size_of::(), ); assert_eq!(dest, src); } @@ -317,7 +65,7 @@ fn test_memcpy() { libc::memcpy( &mut dest as *mut Option as *mut libc::c_void, &src as *const Option as *const libc::c_void, - std::mem::size_of::>(), + mem::size_of::>(), ); assert_eq!(dest, src); } @@ -328,7 +76,7 @@ fn test_memcpy() { libc::memcpy( &mut dest as *mut &'static i32 as *mut libc::c_void, &src as *const &'static i32 as *const libc::c_void, - std::mem::size_of::<&'static i32>(), + mem::size_of::<&'static i32>(), ); assert_eq!(*dest, 123); } @@ -388,7 +136,7 @@ fn test_dlsym() { assert_eq!(errno, libc::EBADF); } -#[cfg(not(target_os = "macos"))] +#[cfg(not(any(target_os = "macos", target_os = "illumos")))] fn test_reallocarray() { unsafe { let mut p = libc::reallocarray(std::ptr::null_mut(), 4096, 2); @@ -401,33 +149,94 @@ fn test_reallocarray() { } } -fn main() { - test_posix_gettimeofday(); +fn test_memalign() { + // A normal allocation. + unsafe { + let mut ptr: *mut libc::c_void = ptr::null_mut(); + let align = 8; + let size = 64; + assert_eq!(libc::posix_memalign(&mut ptr, align, size), 0); + assert!(!ptr.is_null()); + assert!(ptr.is_aligned_to(align)); + ptr.cast::().write_bytes(1, size); + libc::free(ptr); + } - test_posix_realpath_alloc(); - test_posix_realpath_noalloc(); - test_posix_realpath_errors(); + // Align > size. + unsafe { + let mut ptr: *mut libc::c_void = ptr::null_mut(); + let align = 64; + let size = 8; + assert_eq!(libc::posix_memalign(&mut ptr, align, size), 0); + assert!(!ptr.is_null()); + assert!(ptr.is_aligned_to(align)); + ptr.cast::().write_bytes(1, size); + libc::free(ptr); + } - test_thread_local_errno(); - test_localtime_r(); + // Size not multiple of align + unsafe { + let mut ptr: *mut libc::c_void = ptr::null_mut(); + let align = 16; + let size = 31; + assert_eq!(libc::posix_memalign(&mut ptr, align, size), 0); + assert!(!ptr.is_null()); + assert!(ptr.is_aligned_to(align)); + ptr.cast::().write_bytes(1, size); + libc::free(ptr); + } - test_isatty(); + // Size == 0 + unsafe { + let mut ptr: *mut libc::c_void = ptr::null_mut(); + let align = 64; + let size = 0; + assert_eq!(libc::posix_memalign(&mut ptr, align, size), 0); + // We are not required to return null if size == 0, but we currently do. + // It's fine to remove this assert if we start returning non-null pointers. + assert!(ptr.is_null()); + assert!(ptr.is_aligned_to(align)); + // Regardless of what we return, it must be `free`able. + libc::free(ptr); + } - test_clocks(); + // Non-power of 2 align + unsafe { + let mut ptr: *mut libc::c_void = ptr::without_provenance_mut(0x1234567); + let align = 15; + let size = 8; + assert_eq!(libc::posix_memalign(&mut ptr, align, size), libc::EINVAL); + // The pointer is not modified on failure, posix_memalign(3) says: + // > On Linux (and other systems), posix_memalign() does not modify memptr on failure. + // > A requirement standardizing this behavior was added in POSIX.1-2008 TC2. + assert_eq!(ptr.addr(), 0x1234567); + } + + // Too small align (smaller than ptr) + unsafe { + let mut ptr: *mut libc::c_void = ptr::without_provenance_mut(0x1234567); + let align = std::mem::size_of::() / 2; + let size = 8; + assert_eq!(libc::posix_memalign(&mut ptr, align, size), libc::EINVAL); + // The pointer is not modified on failure, posix_memalign(3) says: + // > On Linux (and other systems), posix_memalign() does not modify memptr on failure. + // > A requirement standardizing this behavior was added in POSIX.1-2008 TC2. + assert_eq!(ptr.addr(), 0x1234567); + } +} + +fn main() { + test_thread_local_errno(); test_dlsym(); test_memcpy(); test_strcpy(); - #[cfg(not(target_os = "macos"))] // reallocarray does not exist on macOS + test_memalign(); + #[cfg(not(any(target_os = "macos", target_os = "illumos")))] test_reallocarray(); - // These are Linux-specific #[cfg(target_os = "linux")] - { - test_posix_fadvise(); - test_sync_file_range(); - test_sigrt(); - } + test_sigrt(); } diff --git a/src/tools/miri/tests/pass-dep/shims/libc-getrandom.rs b/src/tools/miri/tests/pass-dep/shims/libc-random.rs similarity index 61% rename from src/tools/miri/tests/pass-dep/shims/libc-getrandom.rs rename to src/tools/miri/tests/pass-dep/shims/libc-random.rs index 9c670cbd5070e..71e335226345e 100644 --- a/src/tools/miri/tests/pass-dep/shims/libc-getrandom.rs +++ b/src/tools/miri/tests/pass-dep/shims/libc-random.rs @@ -1,9 +1,29 @@ //@ignore-target-windows: no libc -//@ignore-target-apple: no getrandom - -use std::ptr; +//@revisions: isolation no_isolation +//@[no_isolation]compile-flags: -Zmiri-disable-isolation fn main() { + test_getentropy(); + #[cfg(not(target_os = "macos"))] + test_getrandom(); +} + +fn test_getentropy() { + use libc::getentropy; + + let mut buf1 = [0u8; 256]; + let mut buf2 = [0u8; 257]; + unsafe { + assert_eq!(getentropy(buf1.as_mut_ptr() as *mut libc::c_void, buf1.len()), 0); + assert_eq!(getentropy(buf2.as_mut_ptr() as *mut libc::c_void, buf2.len()), -1); + assert_eq!(std::io::Error::last_os_error().raw_os_error().unwrap(), libc::EIO); + } +} + +#[cfg(not(target_os = "macos"))] +fn test_getrandom() { + use std::ptr; + let mut buf = [0u8; 5]; unsafe { #[cfg(target_os = "linux")] diff --git a/src/tools/miri/tests/pass-dep/shims/libc-rsfs.stdout b/src/tools/miri/tests/pass-dep/shims/libc-rsfs.stdout deleted file mode 100644 index b6fa69e3d5d2e..0000000000000 --- a/src/tools/miri/tests/pass-dep/shims/libc-rsfs.stdout +++ /dev/null @@ -1 +0,0 @@ -hello dup fd diff --git a/src/tools/miri/tests/pass-dep/shims/libc-time.rs b/src/tools/miri/tests/pass-dep/shims/libc-time.rs new file mode 100644 index 0000000000000..69c75bd8caf3c --- /dev/null +++ b/src/tools/miri/tests/pass-dep/shims/libc-time.rs @@ -0,0 +1,93 @@ +//@ignore-target-windows: no libc on Windows +//@compile-flags: -Zmiri-disable-isolation +use std::ffi::CStr; +use std::{env, mem, ptr}; + +fn main() { + test_clocks(); + test_posix_gettimeofday(); + test_localtime_r(); +} + +/// Tests whether clock support exists at all +fn test_clocks() { + let mut tp = mem::MaybeUninit::::uninit(); + let is_error = unsafe { libc::clock_gettime(libc::CLOCK_REALTIME, tp.as_mut_ptr()) }; + assert_eq!(is_error, 0); + let is_error = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, tp.as_mut_ptr()) }; + assert_eq!(is_error, 0); + #[cfg(any(target_os = "linux", target_os = "freebsd"))] + { + let is_error = unsafe { libc::clock_gettime(libc::CLOCK_REALTIME_COARSE, tp.as_mut_ptr()) }; + assert_eq!(is_error, 0); + let is_error = + unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC_COARSE, tp.as_mut_ptr()) }; + assert_eq!(is_error, 0); + } + #[cfg(target_os = "macos")] + { + let is_error = unsafe { libc::clock_gettime(libc::CLOCK_UPTIME_RAW, tp.as_mut_ptr()) }; + assert_eq!(is_error, 0); + } +} + +fn test_posix_gettimeofday() { + let mut tp = mem::MaybeUninit::::uninit(); + let tz = ptr::null_mut::(); + let is_error = unsafe { libc::gettimeofday(tp.as_mut_ptr(), tz.cast()) }; + assert_eq!(is_error, 0); + let tv = unsafe { tp.assume_init() }; + assert!(tv.tv_sec > 0); + assert!(tv.tv_usec >= 0); // Theoretically this could be 0. + + // Test that non-null tz returns an error. + let mut tz = mem::MaybeUninit::::uninit(); + let tz_ptr = tz.as_mut_ptr(); + let is_error = unsafe { libc::gettimeofday(tp.as_mut_ptr(), tz_ptr.cast()) }; + assert_eq!(is_error, -1); +} + +fn test_localtime_r() { + // Set timezone to GMT. + let key = "TZ"; + env::set_var(key, "GMT"); + + const TIME_SINCE_EPOCH: libc::time_t = 1712475836; + let custom_time_ptr = &TIME_SINCE_EPOCH; + let mut tm = libc::tm { + tm_sec: 0, + tm_min: 0, + tm_hour: 0, + tm_mday: 0, + tm_mon: 0, + tm_year: 0, + tm_wday: 0, + tm_yday: 0, + tm_isdst: 0, + tm_gmtoff: 0, + tm_zone: std::ptr::null_mut::(), + }; + let res = unsafe { libc::localtime_r(custom_time_ptr, &mut tm) }; + + assert_eq!(tm.tm_sec, 56); + assert_eq!(tm.tm_min, 43); + assert_eq!(tm.tm_hour, 7); + assert_eq!(tm.tm_mday, 7); + assert_eq!(tm.tm_mon, 3); + assert_eq!(tm.tm_year, 124); + assert_eq!(tm.tm_wday, 0); + assert_eq!(tm.tm_yday, 97); + assert_eq!(tm.tm_isdst, -1); + #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))] + assert_eq!(tm.tm_gmtoff, 0); + #[cfg(any(target_os = "linux", target_os = "macos", target_os = "freebsd"))] + unsafe { + assert_eq!(CStr::from_ptr(tm.tm_zone).to_str().unwrap(), "+00") + }; + + // The returned value is the pointer passed in. + assert!(ptr::eq(res, &mut tm)); + + // Remove timezone setting. + env::remove_var(key); +} diff --git a/src/tools/miri/tests/pass-dep/shims/posix_memalign.rs b/src/tools/miri/tests/pass-dep/shims/posix_memalign.rs deleted file mode 100644 index db66b21341641..0000000000000 --- a/src/tools/miri/tests/pass-dep/shims/posix_memalign.rs +++ /dev/null @@ -1,82 +0,0 @@ -//@ignore-target-windows: No libc on Windows - -#![feature(pointer_is_aligned_to)] -#![feature(strict_provenance)] - -use core::ptr; - -fn main() { - // A normal allocation. - unsafe { - let mut ptr: *mut libc::c_void = ptr::null_mut(); - let align = 8; - let size = 64; - assert_eq!(libc::posix_memalign(&mut ptr, align, size), 0); - assert!(!ptr.is_null()); - assert!(ptr.is_aligned_to(align)); - ptr.cast::().write_bytes(1, size); - libc::free(ptr); - } - - // Align > size. - unsafe { - let mut ptr: *mut libc::c_void = ptr::null_mut(); - let align = 64; - let size = 8; - assert_eq!(libc::posix_memalign(&mut ptr, align, size), 0); - assert!(!ptr.is_null()); - assert!(ptr.is_aligned_to(align)); - ptr.cast::().write_bytes(1, size); - libc::free(ptr); - } - - // Size not multiple of align - unsafe { - let mut ptr: *mut libc::c_void = ptr::null_mut(); - let align = 16; - let size = 31; - assert_eq!(libc::posix_memalign(&mut ptr, align, size), 0); - assert!(!ptr.is_null()); - assert!(ptr.is_aligned_to(align)); - ptr.cast::().write_bytes(1, size); - libc::free(ptr); - } - - // Size == 0 - unsafe { - let mut ptr: *mut libc::c_void = ptr::null_mut(); - let align = 64; - let size = 0; - assert_eq!(libc::posix_memalign(&mut ptr, align, size), 0); - // We are not required to return null if size == 0, but we currently do. - // It's fine to remove this assert if we start returning non-null pointers. - assert!(ptr.is_null()); - assert!(ptr.is_aligned_to(align)); - // Regardless of what we return, it must be `free`able. - libc::free(ptr); - } - - // Non-power of 2 align - unsafe { - let mut ptr: *mut libc::c_void = ptr::without_provenance_mut(0x1234567); - let align = 15; - let size = 8; - assert_eq!(libc::posix_memalign(&mut ptr, align, size), libc::EINVAL); - // The pointer is not modified on failure, posix_memalign(3) says: - // > On Linux (and other systems), posix_memalign() does not modify memptr on failure. - // > A requirement standardizing this behavior was added in POSIX.1-2008 TC2. - assert_eq!(ptr.addr(), 0x1234567); - } - - // Too small align (smaller than ptr) - unsafe { - let mut ptr: *mut libc::c_void = ptr::without_provenance_mut(0x1234567); - let align = std::mem::size_of::() / 2; - let size = 8; - assert_eq!(libc::posix_memalign(&mut ptr, align, size), libc::EINVAL); - // The pointer is not modified on failure, posix_memalign(3) says: - // > On Linux (and other systems), posix_memalign() does not modify memptr on failure. - // > A requirement standardizing this behavior was added in POSIX.1-2008 TC2. - assert_eq!(ptr.addr(), 0x1234567); - } -} diff --git a/src/tools/miri/tests/pass-dep/shims/pthread-sync.rs b/src/tools/miri/tests/pass-dep/shims/pthread-sync.rs index c9d10cb83d4d2..12d3f2b6f142f 100644 --- a/src/tools/miri/tests/pass-dep/shims/pthread-sync.rs +++ b/src/tools/miri/tests/pass-dep/shims/pthread-sync.rs @@ -19,6 +19,7 @@ fn main() { check_rwlock_write(); check_rwlock_read_no_deadlock(); check_cond(); + check_condattr(); } fn test_mutex_libc_init_recursive() { @@ -261,6 +262,31 @@ fn check_cond() { } } +fn check_condattr() { + unsafe { + // Just smoke-testing that these functions can be called. + let mut attr: MaybeUninit = MaybeUninit::uninit(); + assert_eq!(libc::pthread_condattr_init(attr.as_mut_ptr()), 0); + + #[cfg(not(target_os = "macos"))] // setclock-getclock do not exist on macOS + { + let clock_id = libc::CLOCK_MONOTONIC; + assert_eq!(libc::pthread_condattr_setclock(attr.as_mut_ptr(), clock_id), 0); + let mut check_clock_id = MaybeUninit::::uninit(); + assert_eq!( + libc::pthread_condattr_getclock(attr.as_mut_ptr(), check_clock_id.as_mut_ptr()), + 0 + ); + assert_eq!(check_clock_id.assume_init(), clock_id); + } + + let mut cond: MaybeUninit = MaybeUninit::uninit(); + assert_eq!(libc::pthread_cond_init(cond.as_mut_ptr(), attr.as_ptr()), 0); + assert_eq!(libc::pthread_condattr_destroy(attr.as_mut_ptr()), 0); + assert_eq!(libc::pthread_cond_destroy(cond.as_mut_ptr()), 0); + } +} + // std::sync::RwLock does not even used pthread_rwlock any more. // Do some smoke testing of the API surface. fn test_rwlock_libc_static_initializer() { diff --git a/src/tools/miri/tests/pass/align_offset_symbolic.rs b/src/tools/miri/tests/pass/align_offset_symbolic.rs index c32fa2c8f9bda..dec3d779a789a 100644 --- a/src/tools/miri/tests/pass/align_offset_symbolic.rs +++ b/src/tools/miri/tests/pass/align_offset_symbolic.rs @@ -62,7 +62,10 @@ fn test_from_utf8() { const N: usize = 10; let vec = vec![0x4141414141414141u64; N]; let content = unsafe { std::slice::from_raw_parts(vec.as_ptr() as *const u8, 8 * N) }; - println!("{:?}", std::str::from_utf8(content).unwrap()); + assert_eq!( + std::str::from_utf8(content).unwrap(), + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", + ); } fn test_u64_array() { diff --git a/src/tools/miri/tests/pass/align_offset_symbolic.stdout b/src/tools/miri/tests/pass/align_offset_symbolic.stdout deleted file mode 100644 index 66d4399481596..0000000000000 --- a/src/tools/miri/tests/pass/align_offset_symbolic.stdout +++ /dev/null @@ -1 +0,0 @@ -"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" diff --git a/src/tools/miri/tests/pass/alloc-access-tracking.rs b/src/tools/miri/tests/pass/alloc-access-tracking.rs index 29c1ee2f7b765..a226783155b42 100644 --- a/src/tools/miri/tests/pass/alloc-access-tracking.rs +++ b/src/tools/miri/tests/pass/alloc-access-tracking.rs @@ -1,7 +1,8 @@ #![feature(start)] #![no_std] -//@compile-flags: -Zmiri-track-alloc-id=18 -Zmiri-track-alloc-accesses -Cpanic=abort -//@only-target-linux: alloc IDs differ between OSes for some reason +//@compile-flags: -Zmiri-track-alloc-id=20 -Zmiri-track-alloc-accesses -Cpanic=abort +//@normalize-stderr-test: "id 20" -> "id $$ALLOC" +//@only-target-linux: alloc IDs differ between OSes (due to extern static allocations) extern "Rust" { fn miri_alloc(size: usize, align: usize) -> *mut u8; diff --git a/src/tools/miri/tests/pass/alloc-access-tracking.stderr b/src/tools/miri/tests/pass/alloc-access-tracking.stderr index bef13701ea2c4..0af6cde833f7f 100644 --- a/src/tools/miri/tests/pass/alloc-access-tracking.stderr +++ b/src/tools/miri/tests/pass/alloc-access-tracking.stderr @@ -2,7 +2,7 @@ note: tracking was triggered --> $DIR/alloc-access-tracking.rs:LL:CC | LL | let ptr = miri_alloc(123, 1); - | ^^^^^^^^^^^^^^^^^^ created Miri bare-metal heap allocation of 123 bytes (alignment ALIGN bytes) with id 18 + | ^^^^^^^^^^^^^^^^^^ created Miri bare-metal heap allocation of 123 bytes (alignment ALIGN bytes) with id $ALLOC | = note: BACKTRACE: = note: inside `start` at $DIR/alloc-access-tracking.rs:LL:CC @@ -11,7 +11,7 @@ note: tracking was triggered --> $DIR/alloc-access-tracking.rs:LL:CC | LL | *ptr = 42; // Crucially, only a write is printed here, no read! - | ^^^^^^^^^ write access to allocation with id 18 + | ^^^^^^^^^ write access to allocation with id $ALLOC | = note: BACKTRACE: = note: inside `start` at $DIR/alloc-access-tracking.rs:LL:CC @@ -20,7 +20,7 @@ note: tracking was triggered --> $DIR/alloc-access-tracking.rs:LL:CC | LL | assert_eq!(*ptr, 42); - | ^^^^^^^^^^^^^^^^^^^^ read access to allocation with id 18 + | ^^^^^^^^^^^^^^^^^^^^ read access to allocation with id $ALLOC | = note: BACKTRACE: = note: inside `start` at RUSTLIB/core/src/macros/mod.rs:LL:CC @@ -30,7 +30,7 @@ note: tracking was triggered --> $DIR/alloc-access-tracking.rs:LL:CC | LL | miri_dealloc(ptr, 123, 1); - | ^^^^^^^^^^^^^^^^^^^^^^^^^ freed allocation with id 18 + | ^^^^^^^^^^^^^^^^^^^^^^^^^ freed allocation with id $ALLOC | = note: BACKTRACE: = note: inside `start` at $DIR/alloc-access-tracking.rs:LL:CC diff --git a/src/tools/miri/tests/pass/concurrency/thread_name.rs b/src/tools/miri/tests/pass/concurrency/threadname.rs similarity index 100% rename from src/tools/miri/tests/pass/concurrency/thread_name.rs rename to src/tools/miri/tests/pass/concurrency/threadname.rs diff --git a/src/tools/miri/tests/pass/hello.rs b/src/tools/miri/tests/pass/hello.rs index e7a11a969c037..2a02a7a9e207b 100644 --- a/src/tools/miri/tests/pass/hello.rs +++ b/src/tools/miri/tests/pass/hello.rs @@ -1,3 +1,4 @@ fn main() { println!("Hello, world!"); + eprintln!("Hello, error!"); } diff --git a/src/tools/miri/tests/pass/hello.stderr b/src/tools/miri/tests/pass/hello.stderr new file mode 100644 index 0000000000000..445a1bc8fa4a2 --- /dev/null +++ b/src/tools/miri/tests/pass/hello.stderr @@ -0,0 +1 @@ +Hello, error! diff --git a/src/tools/miri/tests/pass/ints.rs b/src/tools/miri/tests/pass/integers.rs similarity index 100% rename from src/tools/miri/tests/pass/ints.rs rename to src/tools/miri/tests/pass/integers.rs diff --git a/src/tools/miri/tests/pass/intrinsics-integer.rs b/src/tools/miri/tests/pass/intrinsics/integer.rs similarity index 100% rename from src/tools/miri/tests/pass/intrinsics-integer.rs rename to src/tools/miri/tests/pass/intrinsics/integer.rs diff --git a/src/tools/miri/tests/pass/intrinsics.rs b/src/tools/miri/tests/pass/intrinsics/intrinsics.rs similarity index 100% rename from src/tools/miri/tests/pass/intrinsics.rs rename to src/tools/miri/tests/pass/intrinsics/intrinsics.rs diff --git a/src/tools/miri/tests/pass/portable-simd-ptrs.rs b/src/tools/miri/tests/pass/intrinsics/portable-simd-ptrs.rs similarity index 100% rename from src/tools/miri/tests/pass/portable-simd-ptrs.rs rename to src/tools/miri/tests/pass/intrinsics/portable-simd-ptrs.rs diff --git a/src/tools/miri/tests/pass/portable-simd.rs b/src/tools/miri/tests/pass/intrinsics/portable-simd.rs similarity index 100% rename from src/tools/miri/tests/pass/portable-simd.rs rename to src/tools/miri/tests/pass/intrinsics/portable-simd.rs diff --git a/src/tools/miri/tests/pass/volatile.rs b/src/tools/miri/tests/pass/intrinsics/volatile.rs similarity index 100% rename from src/tools/miri/tests/pass/volatile.rs rename to src/tools/miri/tests/pass/intrinsics/volatile.rs diff --git a/src/tools/miri/tests/pass/available-parallelism-miri-num-cpus.rs b/src/tools/miri/tests/pass/shims/available-parallelism-miri-num-cpus.rs similarity index 100% rename from src/tools/miri/tests/pass/available-parallelism-miri-num-cpus.rs rename to src/tools/miri/tests/pass/shims/available-parallelism-miri-num-cpus.rs diff --git a/src/tools/miri/tests/pass/available-parallelism.rs b/src/tools/miri/tests/pass/shims/available-parallelism.rs similarity index 100% rename from src/tools/miri/tests/pass/available-parallelism.rs rename to src/tools/miri/tests/pass/shims/available-parallelism.rs diff --git a/src/tools/miri/tests/pass/intrinsics-x86-aes-vaes.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-aes-vaes.rs similarity index 100% rename from src/tools/miri/tests/pass/intrinsics-x86-aes-vaes.rs rename to src/tools/miri/tests/pass/shims/x86/intrinsics-x86-aes-vaes.rs diff --git a/src/tools/miri/tests/pass/intrinsics-x86-avx.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx.rs similarity index 100% rename from src/tools/miri/tests/pass/intrinsics-x86-avx.rs rename to src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx.rs diff --git a/src/tools/miri/tests/pass/intrinsics-x86-avx2.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx2.rs similarity index 100% rename from src/tools/miri/tests/pass/intrinsics-x86-avx2.rs rename to src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx2.rs diff --git a/src/tools/miri/tests/pass/intrinsics-x86-avx512.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx512.rs similarity index 100% rename from src/tools/miri/tests/pass/intrinsics-x86-avx512.rs rename to src/tools/miri/tests/pass/shims/x86/intrinsics-x86-avx512.rs diff --git a/src/tools/miri/tests/pass/intrinsics-x86-pause-without-sse2.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-pause-without-sse2.rs similarity index 100% rename from src/tools/miri/tests/pass/intrinsics-x86-pause-without-sse2.rs rename to src/tools/miri/tests/pass/shims/x86/intrinsics-x86-pause-without-sse2.rs diff --git a/src/tools/miri/tests/pass/intrinsics-x86-sse.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse.rs similarity index 100% rename from src/tools/miri/tests/pass/intrinsics-x86-sse.rs rename to src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse.rs diff --git a/src/tools/miri/tests/pass/intrinsics-x86-sse2.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse2.rs similarity index 100% rename from src/tools/miri/tests/pass/intrinsics-x86-sse2.rs rename to src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse2.rs diff --git a/src/tools/miri/tests/pass/intrinsics-x86-sse3-ssse3.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse3-ssse3.rs similarity index 100% rename from src/tools/miri/tests/pass/intrinsics-x86-sse3-ssse3.rs rename to src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse3-ssse3.rs diff --git a/src/tools/miri/tests/pass/intrinsics-x86-sse41.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse41.rs similarity index 100% rename from src/tools/miri/tests/pass/intrinsics-x86-sse41.rs rename to src/tools/miri/tests/pass/shims/x86/intrinsics-x86-sse41.rs diff --git a/src/tools/miri/tests/pass/intrinsics-x86.rs b/src/tools/miri/tests/pass/shims/x86/intrinsics-x86.rs similarity index 100% rename from src/tools/miri/tests/pass/intrinsics-x86.rs rename to src/tools/miri/tests/pass/shims/x86/intrinsics-x86.rs diff --git a/src/tools/miri/tests/pass/vecdeque.rs b/src/tools/miri/tests/pass/vecdeque.rs index ccecf3d30a414..77c4ca5a04e6a 100644 --- a/src/tools/miri/tests/pass/vecdeque.rs +++ b/src/tools/miri/tests/pass/vecdeque.rs @@ -31,8 +31,8 @@ fn main() { } // Regression test for Debug impl's - println!("{:?} {:?}", dst, dst.iter()); - println!("{:?}", VecDeque::::new().iter()); + format!("{:?} {:?}", dst, dst.iter()); + format!("{:?}", VecDeque::::new().iter()); for a in dst { assert_eq!(*a, 2); diff --git a/src/tools/miri/tests/pass/vecdeque.stack.stdout b/src/tools/miri/tests/pass/vecdeque.stack.stdout deleted file mode 100644 index 63de960ee2bdf..0000000000000 --- a/src/tools/miri/tests/pass/vecdeque.stack.stdout +++ /dev/null @@ -1,2 +0,0 @@ -[2, 2] Iter([2, 2], []) -Iter([], []) diff --git a/src/tools/miri/tests/pass/vecdeque.tree.stdout b/src/tools/miri/tests/pass/vecdeque.tree.stdout deleted file mode 100644 index 63de960ee2bdf..0000000000000 --- a/src/tools/miri/tests/pass/vecdeque.tree.stdout +++ /dev/null @@ -1,2 +0,0 @@ -[2, 2] Iter([2, 2], []) -Iter([], []) diff --git a/src/tools/miri/tests/pass/vecdeque.tree_uniq.stdout b/src/tools/miri/tests/pass/vecdeque.tree_uniq.stdout deleted file mode 100644 index 63de960ee2bdf..0000000000000 --- a/src/tools/miri/tests/pass/vecdeque.tree_uniq.stdout +++ /dev/null @@ -1,2 +0,0 @@ -[2, 2] Iter([2, 2], []) -Iter([], []) diff --git a/src/tools/miri/triagebot.toml b/src/tools/miri/triagebot.toml index 3b767b3e62f13..addb36418d4b4 100644 --- a/src/tools/miri/triagebot.toml +++ b/src/tools/miri/triagebot.toml @@ -10,5 +10,10 @@ allow-unauthenticated = [ # Gives us the commands 'ready', 'author', 'blocked' [shortcut] +# Enables assigning users to issues and PRs. +[assign] +warn_non_default_branch = true +contributing_url = "https://github.com/rust-lang/miri/blob/master/CONTRIBUTING.md" + [no-merges] exclude_titles = ["Rustup"] diff --git a/src/tools/run-make-support/src/cc.rs b/src/tools/run-make-support/src/cc.rs index a2d51902652bc..4082639f618a1 100644 --- a/src/tools/run-make-support/src/cc.rs +++ b/src/tools/run-make-support/src/cc.rs @@ -71,6 +71,11 @@ impl Cc { self } + + /// Get the [`Output`][::std::process::Output] of the finished process. + pub fn output(&mut self) -> ::std::process::Output { + self.cmd.output().expect("failed to get output of finished process") + } } /// `EXTRACFLAGS` @@ -161,8 +166,9 @@ pub fn extra_cxx_flags() -> Vec<&'static str> { if is_windows() { if is_msvc() { vec![] } else { vec!["-lstdc++"] } } else { - match uname() { - n if n.contains("Darwin") => vec!["-lc++"], + match &uname()[..] { + "Darwin" => vec!["-lc++"], + "FreeBSD" | "SunOS" | "OpenBSD" => vec![], _ => vec!["-lstdc++"], } } diff --git a/src/tools/run-make-support/src/clang.rs b/src/tools/run-make-support/src/clang.rs index ed9f8383dc3ae..c30ba29ed76d6 100644 --- a/src/tools/run-make-support/src/clang.rs +++ b/src/tools/run-make-support/src/clang.rs @@ -70,4 +70,9 @@ impl Clang { self.cmd.arg(format!("-fuse-ld={ld}")); self } + + /// Get the [`Output`][::std::process::Output] of the finished process. + pub fn output(&mut self) -> ::std::process::Output { + self.cmd.output().expect("failed to get output of finished process") + } } diff --git a/src/tools/run-make-support/src/lib.rs b/src/tools/run-make-support/src/lib.rs index a874c1313b510..d040b05f20e82 100644 --- a/src/tools/run-make-support/src/lib.rs +++ b/src/tools/run-make-support/src/lib.rs @@ -144,7 +144,7 @@ pub fn set_host_rpath(cmd: &mut Command) { } /// Implement common helpers for command wrappers. This assumes that the command wrapper is a struct -/// containing a `cmd: Command` field. The provided helpers are: +/// containing a `cmd: Command` field and a `output` function. The provided helpers are: /// /// 1. Generic argument acceptors: `arg` and `args` (delegated to [`Command`]). These are intended /// to be *fallback* argument acceptors, when specific helpers don't make sense. Prefer to add @@ -160,7 +160,12 @@ pub fn set_host_rpath(cmd: &mut Command) { /// Example usage: /// /// ```ignore (illustrative) -/// struct CommandWrapper { cmd: Command } +/// struct CommandWrapper { cmd: Command } // <- required `cmd` field +/// +/// impl CommandWrapper { +/// /// Get the [`Output`][::std::process::Output] of the finished process. +/// pub fn output(&mut self) -> Output { /* ... */ } // <- required `output()` method +/// } /// /// crate::impl_common_helpers!(CommandWrapper); /// @@ -231,18 +236,13 @@ macro_rules! impl_common_helpers { self } - /// Get the [`Output`][::std::process::Output] of the finished process. - pub fn output(&mut self) -> ::std::process::Output { - self.cmd.output().expect("failed to get output of finished process") - } - /// Run the constructed command and assert that it is successfully run. #[track_caller] pub fn run(&mut self) -> ::std::process::Output { let caller_location = ::std::panic::Location::caller(); let caller_line_number = caller_location.line(); - let output = self.cmd.output().unwrap(); + let output = self.output(); if !output.status.success() { handle_failed_output(&self.cmd, output, caller_line_number); } @@ -255,12 +255,18 @@ macro_rules! impl_common_helpers { let caller_location = ::std::panic::Location::caller(); let caller_line_number = caller_location.line(); - let output = self.cmd.output().unwrap(); + let output = self.output(); if output.status.success() { handle_failed_output(&self.cmd, output, caller_line_number); } output } + + /// Set the path where the command will be run. + pub fn current_dir>(&mut self, path: P) -> &mut Self { + self.cmd.current_dir(path); + self + } } }; } diff --git a/src/tools/run-make-support/src/llvm_readobj.rs b/src/tools/run-make-support/src/llvm_readobj.rs index 32ea07e932ed8..4e1f2b002f301 100644 --- a/src/tools/run-make-support/src/llvm_readobj.rs +++ b/src/tools/run-make-support/src/llvm_readobj.rs @@ -41,4 +41,10 @@ impl LlvmReadobj { self.cmd.arg("--file-header"); self } + + /// Get the [`Output`][::std::process::Output] of the finished process. + #[track_caller] + pub fn output(&mut self) -> ::std::process::Output { + self.cmd.output().expect("failed to get output of finished process") + } } diff --git a/src/tools/run-make-support/src/rustc.rs b/src/tools/run-make-support/src/rustc.rs index ddaae3236c2b5..37539528ab3fc 100644 --- a/src/tools/run-make-support/src/rustc.rs +++ b/src/tools/run-make-support/src/rustc.rs @@ -1,7 +1,8 @@ use std::env; use std::ffi::OsString; +use std::io::Write; use std::path::Path; -use std::process::{Command, Output}; +use std::process::{Command, Output, Stdio}; use crate::{handle_failed_output, set_host_rpath, tmp_dir}; @@ -19,6 +20,7 @@ pub fn aux_build() -> Rustc { #[derive(Debug)] pub struct Rustc { cmd: Command, + stdin: Option>, } crate::impl_common_helpers!(Rustc); @@ -37,14 +39,14 @@ impl Rustc { /// Construct a new `rustc` invocation. pub fn new() -> Self { let cmd = setup_common(); - Self { cmd } + Self { cmd, stdin: None } } /// Construct a new `rustc` invocation with `aux_build` preset (setting `--crate-type=lib`). pub fn new_aux_build() -> Self { let mut cmd = setup_common(); cmd.arg("--crate-type=lib"); - Self { cmd } + Self { cmd, stdin: None } } // Argument provider methods @@ -161,12 +163,40 @@ impl Rustc { self } + /// Specify a stdin input + pub fn stdin>(&mut self, input: I) -> &mut Self { + self.stdin = Some(input.as_ref().to_vec().into_boxed_slice()); + self + } + + /// Get the [`Output`][::std::process::Output] of the finished process. + #[track_caller] + pub fn output(&mut self) -> ::std::process::Output { + // let's make sure we piped all the input and outputs + self.cmd.stdin(Stdio::piped()); + self.cmd.stdout(Stdio::piped()); + self.cmd.stderr(Stdio::piped()); + + if let Some(input) = &self.stdin { + let mut child = self.cmd.spawn().unwrap(); + + { + let mut stdin = child.stdin.take().unwrap(); + stdin.write_all(input.as_ref()).unwrap(); + } + + child.wait_with_output().expect("failed to get output of finished process") + } else { + self.cmd.output().expect("failed to get output of finished process") + } + } + #[track_caller] pub fn run_fail_assert_exit_code(&mut self, code: i32) -> Output { let caller_location = std::panic::Location::caller(); let caller_line_number = caller_location.line(); - let output = self.cmd.output().unwrap(); + let output = self.output(); if output.status.code().unwrap() != code { handle_failed_output(&self.cmd, output, caller_line_number); } diff --git a/src/tools/run-make-support/src/rustdoc.rs b/src/tools/run-make-support/src/rustdoc.rs index 1054ac83c103c..c2c4f2e68e2f8 100644 --- a/src/tools/run-make-support/src/rustdoc.rs +++ b/src/tools/run-make-support/src/rustdoc.rs @@ -1,6 +1,7 @@ use std::env; +use std::io::Write; use std::path::Path; -use std::process::{Command, Output}; +use std::process::{Command, Output, Stdio}; use crate::{handle_failed_output, set_host_rpath}; @@ -17,6 +18,7 @@ pub fn rustdoc() -> Rustdoc { #[derive(Debug)] pub struct Rustdoc { cmd: Command, + stdin: Option>, } crate::impl_common_helpers!(Rustdoc); @@ -32,7 +34,7 @@ impl Rustdoc { /// Construct a bare `rustdoc` invocation. pub fn bare() -> Self { let cmd = setup_common(); - Self { cmd } + Self { cmd, stdin: None } } /// Construct a `rustdoc` invocation with `-L $(TARGET_RPATH_DIR)` set. @@ -40,7 +42,7 @@ impl Rustdoc { let mut cmd = setup_common(); let target_rpath_dir = env::var_os("TARGET_RPATH_DIR").unwrap(); cmd.arg(format!("-L{}", target_rpath_dir.to_string_lossy())); - Self { cmd } + Self { cmd, stdin: None } } /// Specify path to the input file. @@ -62,12 +64,41 @@ impl Rustdoc { self } + /// Specify a stdin input + pub fn stdin>(&mut self, input: I) -> &mut Self { + self.cmd.stdin(Stdio::piped()); + self.stdin = Some(input.as_ref().to_vec().into_boxed_slice()); + self + } + + /// Get the [`Output`][::std::process::Output] of the finished process. + #[track_caller] + pub fn output(&mut self) -> ::std::process::Output { + // let's make sure we piped all the input and outputs + self.cmd.stdin(Stdio::piped()); + self.cmd.stdout(Stdio::piped()); + self.cmd.stderr(Stdio::piped()); + + if let Some(input) = &self.stdin { + let mut child = self.cmd.spawn().unwrap(); + + { + let mut stdin = child.stdin.take().unwrap(); + stdin.write_all(input.as_ref()).unwrap(); + } + + child.wait_with_output().expect("failed to get output of finished process") + } else { + self.cmd.output().expect("failed to get output of finished process") + } + } + #[track_caller] pub fn run_fail_assert_exit_code(&mut self, code: i32) -> Output { let caller_location = std::panic::Location::caller(); let caller_line_number = caller_location.line(); - let output = self.cmd.output().unwrap(); + let output = self.output(); if output.status.code().unwrap() != code { handle_failed_output(&self.cmd, output, caller_line_number); } diff --git a/src/tools/rust-analyzer/crates/hir-def/src/attr/builtin.rs b/src/tools/rust-analyzer/crates/hir-def/src/attr/builtin.rs index 55b9a1dfdcb91..1fba2e2e4d348 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/attr/builtin.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/attr/builtin.rs @@ -207,7 +207,6 @@ pub const INERT_ATTRIBUTES: &[BuiltinAttribute] = &[ ), // Entry point: - gated!(unix_sigpipe, Normal, template!(Word, NameValueStr: "inherit|sig_ign|sig_dfl"), ErrorFollowing, experimental!(unix_sigpipe)), ungated!(start, Normal, template!(Word), WarnFollowing), ungated!(no_start, CrateLevel, template!(Word), WarnFollowing), ungated!(no_main, CrateLevel, template!(Word), WarnFollowing), diff --git a/src/tools/rustdoc/main.rs b/src/tools/rustdoc/main.rs index b81f46d1211ce..5b499a1fa1fa8 100644 --- a/src/tools/rustdoc/main.rs +++ b/src/tools/rustdoc/main.rs @@ -1,6 +1,3 @@ -#![feature(unix_sigpipe)] - -#[unix_sigpipe = "sig_dfl"] fn main() { rustdoc::main() } diff --git a/src/tools/tidy/src/allowed_run_make_makefiles.txt b/src/tools/tidy/src/allowed_run_make_makefiles.txt index 69c6dda4b19cf..d4d6c1460ceec 100644 --- a/src/tools/tidy/src/allowed_run_make_makefiles.txt +++ b/src/tools/tidy/src/allowed_run_make_makefiles.txt @@ -44,7 +44,6 @@ run-make/dep-graph/Makefile run-make/dep-info-doesnt-run-much/Makefile run-make/dep-info-spaces/Makefile run-make/dep-info/Makefile -run-make/doctests-keep-binaries/Makefile run-make/doctests-runtool/Makefile run-make/dump-ice-to-disk/Makefile run-make/dump-mono-stats/Makefile @@ -246,7 +245,6 @@ run-make/rlib-format-packed-bundled-libs-3/Makefile run-make/rlib-format-packed-bundled-libs/Makefile run-make/rmeta-preferred/Makefile run-make/rustc-macro-dep-files/Makefile -run-make/rustdoc-determinism/Makefile run-make/rustdoc-error-lines/Makefile run-make/rustdoc-io-error/Makefile run-make/rustdoc-map-file/Makefile @@ -288,7 +286,6 @@ run-make/static-unwinding/Makefile run-make/staticlib-blank-lib/Makefile run-make/staticlib-dylib-linkage/Makefile run-make/std-core-cycle/Makefile -run-make/stdin-non-utf8/Makefile run-make/suspicious-library/Makefile run-make/symbol-mangling-hashed/Makefile run-make/symbol-visibility/Makefile diff --git a/tests/codegen/instrument-coverage/instrument-coverage-off.rs b/tests/codegen/instrument-coverage/instrument-coverage-off.rs index fda3c541a25f2..616e3295e5b1a 100644 --- a/tests/codegen/instrument-coverage/instrument-coverage-off.rs +++ b/tests/codegen/instrument-coverage/instrument-coverage-off.rs @@ -1,22 +1,19 @@ // Test that `-Cinstrument-coverage=off` does not add coverage instrumentation to LLVM IR. -//@ needs-profiler-support -//@ revisions: n no off false zero +//@ revisions: n no off false_ zero //@ [n] compile-flags: -Cinstrument-coverage=n //@ [no] compile-flags: -Cinstrument-coverage=no //@ [off] compile-flags: -Cinstrument-coverage=off -//@ [false] compile-flags: -Cinstrument-coverage=false +//@ [false_] compile-flags: -Cinstrument-coverage=false //@ [zero] compile-flags: -Cinstrument-coverage=0 // CHECK-NOT: __llvm_profile_filename // CHECK-NOT: __llvm_coverage_mapping -#![crate_type="lib"] +#![crate_type = "lib"] #[inline(never)] -fn some_function() { - -} +fn some_function() {} pub fn some_other_function() { some_function(); diff --git a/tests/codegen/instrument-coverage/instrument-coverage.rs b/tests/codegen/instrument-coverage/instrument-coverage.rs index f7d96ea346721..d638a544d5a50 100644 --- a/tests/codegen/instrument-coverage/instrument-coverage.rs +++ b/tests/codegen/instrument-coverage/instrument-coverage.rs @@ -1,12 +1,12 @@ // Test that `-Cinstrument-coverage` creates expected __llvm_profile_filename symbol in LLVM IR. //@ needs-profiler-support -//@ revisions: default y yes on true all +//@ revisions: default y yes on true_ all //@ [default] compile-flags: -Cinstrument-coverage //@ [y] compile-flags: -Cinstrument-coverage=y //@ [yes] compile-flags: -Cinstrument-coverage=yes //@ [on] compile-flags: -Cinstrument-coverage=on -//@ [true] compile-flags: -Cinstrument-coverage=true +//@ [true_] compile-flags: -Cinstrument-coverage=true //@ [all] compile-flags: -Cinstrument-coverage=all // CHECK: @__llvm_profile_filename = {{.*}}"default_%m_%p.profraw\00"{{.*}} diff --git a/tests/coverage/issue-83601.cov-map b/tests/coverage/issue-83601.cov-map index f2447e3c92c8a..ddb4407881aad 100644 --- a/tests/coverage/issue-83601.cov-map +++ b/tests/coverage/issue-83601.cov-map @@ -1,12 +1,12 @@ Function name: issue_83601::main -Raw bytes (21): 0x[01, 01, 01, 05, 09, 03, 01, 06, 01, 02, 1c, 05, 03, 09, 01, 1c, 02, 02, 05, 03, 02] +Raw bytes (21): 0x[01, 01, 01, 05, 00, 03, 01, 06, 01, 02, 1c, 05, 03, 09, 01, 1c, 02, 02, 05, 03, 02] Number of files: 1 - file 0 => global file 1 Number of expressions: 1 -- expression 0 operands: lhs = Counter(1), rhs = Counter(2) +- expression 0 operands: lhs = Counter(1), rhs = Zero Number of file 0 mappings: 3 - Code(Counter(0)) at (prev + 6, 1) to (start + 2, 28) - Code(Counter(1)) at (prev + 3, 9) to (start + 1, 28) - Code(Expression(0, Sub)) at (prev + 2, 5) to (start + 3, 2) - = (c1 - c2) + = (c1 - Zero) diff --git a/tests/coverage/issue-84561.cov-map b/tests/coverage/issue-84561.cov-map index a81884ea942d8..ab66a2fffce1b 100644 --- a/tests/coverage/issue-84561.cov-map +++ b/tests/coverage/issue-84561.cov-map @@ -77,22 +77,22 @@ Number of file 0 mappings: 1 - Code(Counter(0)) at (prev + 167, 9) to (start + 2, 10) Function name: issue_84561::test3 -Raw bytes (436): 0x[01, 01, 41, 05, 09, 0d, 00, 15, 19, 12, 00, 15, 19, 21, 00, 1e, 00, 21, 00, 31, 00, 3d, 41, 2e, 45, 3d, 41, 42, 49, 45, 00, 3f, 51, 42, 49, 45, 00, 5d, 8a, 01, 8f, 01, 5d, 92, 01, 55, 51, 00, 92, 01, 55, 51, 00, 8f, 01, 5d, 92, 01, 55, 51, 00, 87, 01, 61, 5d, 8a, 01, 8f, 01, 5d, 92, 01, 55, 51, 00, 82, 01, 65, 87, 01, 61, 5d, 8a, 01, 8f, 01, 5d, 92, 01, 55, 51, 00, 75, f6, 01, fb, 01, 79, 00, fe, 01, 82, 02, 00, 69, 6d, 00, fe, 01, 82, 02, 00, 69, 6d, 69, 6d, 82, 02, 00, 69, 6d, fb, 01, 79, 00, fe, 01, 82, 02, 00, 69, 6d, f3, 01, 7d, 75, f6, 01, fb, 01, 79, 00, fe, 01, 82, 02, 00, 69, 6d, ee, 01, 00, f3, 01, 7d, 75, f6, 01, fb, 01, 79, 00, fe, 01, 82, 02, 00, 69, 6d, 33, 01, 08, 01, 03, 1c, 05, 04, 09, 01, 1c, 02, 02, 05, 04, 1f, 0d, 05, 05, 00, 1f, 06, 01, 05, 00, 1f, 15, 01, 09, 01, 1c, 12, 02, 05, 00, 1f, 0e, 01, 05, 00, 0f, 00, 00, 20, 00, 30, 21, 01, 05, 03, 0f, 00, 03, 20, 00, 30, 00, 00, 33, 00, 41, 00, 00, 4b, 00, 5a, 1e, 01, 05, 00, 0f, 00, 05, 09, 03, 10, 00, 05, 0d, 00, 1b, 00, 02, 0d, 00, 1c, 1a, 04, 09, 05, 06, 31, 06, 05, 03, 06, 22, 04, 05, 03, 06, 3d, 04, 09, 04, 06, 2e, 05, 08, 00, 0f, 45, 01, 09, 03, 0a, 2a, 05, 09, 03, 0a, 3f, 05, 08, 00, 0f, 51, 01, 09, 00, 13, 00, 03, 0d, 00, 1d, 3a, 03, 09, 00, 13, 00, 03, 0d, 00, 1d, 87, 01, 03, 05, 00, 0f, 8f, 01, 01, 0c, 00, 13, 5d, 01, 0d, 00, 13, 8a, 01, 02, 0d, 00, 13, 82, 01, 04, 05, 02, 13, 65, 03, 0d, 00, 13, 7e, 02, 0d, 00, 13, f3, 01, 03, 05, 00, 0f, 69, 01, 0c, 00, 13, 6d, 01, 0d, 03, 0e, 75, 04, 0d, 00, 13, fb, 01, 02, 0d, 00, 17, 82, 02, 01, 14, 00, 1b, 00, 01, 15, 00, 1b, fe, 01, 02, 15, 00, 1b, f6, 01, 04, 0d, 00, 13, 7d, 03, 09, 00, 19, ee, 01, 02, 05, 00, 0f, ea, 01, 03, 09, 00, 22, 00, 02, 05, 00, 0f, 00, 03, 09, 00, 2c, 00, 02, 01, 00, 02] +Raw bytes (436): 0x[01, 01, 41, 05, 00, 0d, 00, 15, 00, 12, 00, 15, 00, 21, 00, 1e, 00, 21, 00, 31, 00, 3d, 00, 2e, 45, 3d, 00, 42, 49, 45, 00, 3f, 51, 42, 49, 45, 00, 5d, 8a, 01, 8f, 01, 5d, 92, 01, 55, 51, 00, 92, 01, 55, 51, 00, 8f, 01, 5d, 92, 01, 55, 51, 00, 87, 01, 61, 5d, 8a, 01, 8f, 01, 5d, 92, 01, 55, 51, 00, 82, 01, 65, 87, 01, 61, 5d, 8a, 01, 8f, 01, 5d, 92, 01, 55, 51, 00, 75, f6, 01, fb, 01, 79, 00, fe, 01, 82, 02, 00, 69, 6d, 00, fe, 01, 82, 02, 00, 69, 6d, 69, 6d, 82, 02, 00, 69, 6d, fb, 01, 79, 00, fe, 01, 82, 02, 00, 69, 6d, f3, 01, 7d, 75, f6, 01, fb, 01, 79, 00, fe, 01, 82, 02, 00, 69, 6d, ee, 01, 00, f3, 01, 7d, 75, f6, 01, fb, 01, 79, 00, fe, 01, 82, 02, 00, 69, 6d, 33, 01, 08, 01, 03, 1c, 05, 04, 09, 01, 1c, 02, 02, 05, 04, 1f, 0d, 05, 05, 00, 1f, 06, 01, 05, 00, 1f, 15, 01, 09, 01, 1c, 12, 02, 05, 00, 1f, 0e, 01, 05, 00, 0f, 00, 00, 20, 00, 30, 21, 01, 05, 03, 0f, 00, 03, 20, 00, 30, 00, 00, 33, 00, 41, 00, 00, 4b, 00, 5a, 1e, 01, 05, 00, 0f, 00, 05, 09, 03, 10, 00, 05, 0d, 00, 1b, 00, 02, 0d, 00, 1c, 1a, 04, 09, 05, 06, 31, 06, 05, 03, 06, 22, 04, 05, 03, 06, 3d, 04, 09, 04, 06, 2e, 05, 08, 00, 0f, 45, 01, 09, 03, 0a, 2a, 05, 09, 03, 0a, 3f, 05, 08, 00, 0f, 51, 01, 09, 00, 13, 00, 03, 0d, 00, 1d, 3a, 03, 09, 00, 13, 00, 03, 0d, 00, 1d, 87, 01, 03, 05, 00, 0f, 8f, 01, 01, 0c, 00, 13, 5d, 01, 0d, 00, 13, 8a, 01, 02, 0d, 00, 13, 82, 01, 04, 05, 02, 13, 65, 03, 0d, 00, 13, 7e, 02, 0d, 00, 13, f3, 01, 03, 05, 00, 0f, 69, 01, 0c, 00, 13, 6d, 01, 0d, 03, 0e, 75, 04, 0d, 00, 13, fb, 01, 02, 0d, 00, 17, 82, 02, 01, 14, 00, 1b, 00, 01, 15, 00, 1b, fe, 01, 02, 15, 00, 1b, f6, 01, 04, 0d, 00, 13, 7d, 03, 09, 00, 19, ee, 01, 02, 05, 00, 0f, ea, 01, 03, 09, 00, 22, 00, 02, 05, 00, 0f, 00, 03, 09, 00, 2c, 00, 02, 01, 00, 02] Number of files: 1 - file 0 => global file 1 Number of expressions: 65 -- expression 0 operands: lhs = Counter(1), rhs = Counter(2) +- expression 0 operands: lhs = Counter(1), rhs = Zero - expression 1 operands: lhs = Counter(3), rhs = Zero -- expression 2 operands: lhs = Counter(5), rhs = Counter(6) +- expression 2 operands: lhs = Counter(5), rhs = Zero - expression 3 operands: lhs = Expression(4, Sub), rhs = Zero -- expression 4 operands: lhs = Counter(5), rhs = Counter(6) +- expression 4 operands: lhs = Counter(5), rhs = Zero - expression 5 operands: lhs = Counter(8), rhs = Zero - expression 6 operands: lhs = Expression(7, Sub), rhs = Zero - expression 7 operands: lhs = Counter(8), rhs = Zero - expression 8 operands: lhs = Counter(12), rhs = Zero -- expression 9 operands: lhs = Counter(15), rhs = Counter(16) +- expression 9 operands: lhs = Counter(15), rhs = Zero - expression 10 operands: lhs = Expression(11, Sub), rhs = Counter(17) -- expression 11 operands: lhs = Counter(15), rhs = Counter(16) +- expression 11 operands: lhs = Counter(15), rhs = Zero - expression 12 operands: lhs = Expression(16, Sub), rhs = Counter(18) - expression 13 operands: lhs = Counter(17), rhs = Zero - expression 14 operands: lhs = Expression(15, Add), rhs = Counter(20) @@ -150,15 +150,15 @@ Number of file 0 mappings: 51 - Code(Counter(0)) at (prev + 8, 1) to (start + 3, 28) - Code(Counter(1)) at (prev + 4, 9) to (start + 1, 28) - Code(Expression(0, Sub)) at (prev + 2, 5) to (start + 4, 31) - = (c1 - c2) + = (c1 - Zero) - Code(Counter(3)) at (prev + 5, 5) to (start + 0, 31) - Code(Expression(1, Sub)) at (prev + 1, 5) to (start + 0, 31) = (c3 - Zero) - Code(Counter(5)) at (prev + 1, 9) to (start + 1, 28) - Code(Expression(4, Sub)) at (prev + 2, 5) to (start + 0, 31) - = (c5 - c6) + = (c5 - Zero) - Code(Expression(3, Sub)) at (prev + 1, 5) to (start + 0, 15) - = ((c5 - c6) - Zero) + = ((c5 - Zero) - Zero) - Code(Zero) at (prev + 0, 32) to (start + 0, 48) - Code(Counter(8)) at (prev + 1, 5) to (start + 3, 15) - Code(Zero) at (prev + 3, 32) to (start + 0, 48) @@ -176,10 +176,10 @@ Number of file 0 mappings: 51 = (c12 - Zero) - Code(Counter(15)) at (prev + 4, 9) to (start + 4, 6) - Code(Expression(11, Sub)) at (prev + 5, 8) to (start + 0, 15) - = (c15 - c16) + = (c15 - Zero) - Code(Counter(17)) at (prev + 1, 9) to (start + 3, 10) - Code(Expression(10, Sub)) at (prev + 5, 9) to (start + 3, 10) - = ((c15 - c16) - c17) + = ((c15 - Zero) - c17) - Code(Expression(15, Add)) at (prev + 5, 8) to (start + 0, 15) = ((c17 - Zero) + c18) - Code(Counter(20)) at (prev + 1, 9) to (start + 0, 19) diff --git a/tests/crashes/111883.rs b/tests/crashes/111883.rs deleted file mode 100644 index fa72b28c22870..0000000000000 --- a/tests/crashes/111883.rs +++ /dev/null @@ -1,40 +0,0 @@ -//@ known-bug: #111883 -#![crate_type = "lib"] -#![feature(arbitrary_self_types, no_core, lang_items)] -#![no_core] - -#[lang = "sized"] -trait Sized {} -#[lang = "copy"] -trait Copy {} -#[lang = "receiver"] -trait Receiver {} -#[lang = "dispatch_from_dyn"] -trait DispatchFromDyn {} -impl<'a, T: ?Sized + Unsize, U: ?Sized> DispatchFromDyn<&'a U> for &'a T {} -#[lang = "unsize"] -trait Unsize {} -#[lang = "coerce_unsized"] -pub trait CoerceUnsized {} -impl<'a, 'b: 'a, T: ?Sized + Unsize, U: ?Sized> CoerceUnsized<&'a U> for &'b T {} - -#[lang = "drop_in_place"] -fn drop_in_place_fn(a: &dyn Trait2) {} - -pub trait Trait1 { - fn foo(&self); -} - -pub struct Type1; - -impl Trait1 for Type1 { - fn foo(&self) {} -} - -pub trait Trait2 {} - -pub fn bar1() { - let a = Type1; - let b = &a as &dyn Trait1; - b.foo(); -} diff --git a/tests/mir-opt/building/match/sort_candidates.rs b/tests/mir-opt/building/match/sort_candidates.rs index a2583ff828484..f207f0b323483 100644 --- a/tests/mir-opt/building/match/sort_candidates.rs +++ b/tests/mir-opt/building/match/sort_candidates.rs @@ -1,5 +1,4 @@ // Check specific cases of sorting candidates in match lowering. -#![feature(exclusive_range_pattern)] // EMIT_MIR sort_candidates.constant_eq.SimplifyCfg-initial.after.mir fn constant_eq(s: &str, b: bool) -> u32 { diff --git a/tests/mir-opt/copy-prop/borrowed_local.borrowed.CopyProp.panic-abort.diff b/tests/mir-opt/copy-prop/borrowed_local.borrowed.CopyProp.panic-abort.diff new file mode 100644 index 0000000000000..897592a0e2fdd --- /dev/null +++ b/tests/mir-opt/copy-prop/borrowed_local.borrowed.CopyProp.panic-abort.diff @@ -0,0 +1,24 @@ +- // MIR for `borrowed` before CopyProp ++ // MIR for `borrowed` after CopyProp + + fn borrowed(_1: T) -> bool { + let mut _0: bool; + let mut _2: T; + let mut _3: &T; + + bb0: { +- _2 = _1; + _3 = &_1; + _0 = opaque::<&T>(_3) -> [return: bb1, unwind unreachable]; + } + + bb1: { +- _0 = opaque::(_2) -> [return: bb2, unwind unreachable]; ++ _0 = opaque::(_1) -> [return: bb2, unwind unreachable]; + } + + bb2: { + return; + } + } + diff --git a/tests/mir-opt/copy-prop/borrowed_local.borrowed.CopyProp.panic-unwind.diff b/tests/mir-opt/copy-prop/borrowed_local.borrowed.CopyProp.panic-unwind.diff new file mode 100644 index 0000000000000..33c05af91a10e --- /dev/null +++ b/tests/mir-opt/copy-prop/borrowed_local.borrowed.CopyProp.panic-unwind.diff @@ -0,0 +1,24 @@ +- // MIR for `borrowed` before CopyProp ++ // MIR for `borrowed` after CopyProp + + fn borrowed(_1: T) -> bool { + let mut _0: bool; + let mut _2: T; + let mut _3: &T; + + bb0: { +- _2 = _1; + _3 = &_1; + _0 = opaque::<&T>(_3) -> [return: bb1, unwind continue]; + } + + bb1: { +- _0 = opaque::(_2) -> [return: bb2, unwind continue]; ++ _0 = opaque::(_1) -> [return: bb2, unwind continue]; + } + + bb2: { + return; + } + } + diff --git a/tests/mir-opt/copy-prop/borrowed_local.f.CopyProp.panic-abort.diff b/tests/mir-opt/copy-prop/borrowed_local.compare_address.CopyProp.panic-abort.diff similarity index 77% rename from tests/mir-opt/copy-prop/borrowed_local.f.CopyProp.panic-abort.diff rename to tests/mir-opt/copy-prop/borrowed_local.compare_address.CopyProp.panic-abort.diff index 46534076c293b..3d6b5dffba456 100644 --- a/tests/mir-opt/copy-prop/borrowed_local.f.CopyProp.panic-abort.diff +++ b/tests/mir-opt/copy-prop/borrowed_local.compare_address.CopyProp.panic-abort.diff @@ -1,7 +1,7 @@ -- // MIR for `f` before CopyProp -+ // MIR for `f` after CopyProp +- // MIR for `compare_address` before CopyProp ++ // MIR for `compare_address` after CopyProp - fn f() -> bool { + fn compare_address() -> bool { let mut _0: bool; let mut _1: u8; let mut _2: &u8; diff --git a/tests/mir-opt/copy-prop/borrowed_local.f.CopyProp.panic-unwind.diff b/tests/mir-opt/copy-prop/borrowed_local.compare_address.CopyProp.panic-unwind.diff similarity index 77% rename from tests/mir-opt/copy-prop/borrowed_local.f.CopyProp.panic-unwind.diff rename to tests/mir-opt/copy-prop/borrowed_local.compare_address.CopyProp.panic-unwind.diff index b702e3b7d1ed7..0f29d2681de8c 100644 --- a/tests/mir-opt/copy-prop/borrowed_local.f.CopyProp.panic-unwind.diff +++ b/tests/mir-opt/copy-prop/borrowed_local.compare_address.CopyProp.panic-unwind.diff @@ -1,7 +1,7 @@ -- // MIR for `f` before CopyProp -+ // MIR for `f` after CopyProp +- // MIR for `compare_address` before CopyProp ++ // MIR for `compare_address` after CopyProp - fn f() -> bool { + fn compare_address() -> bool { let mut _0: bool; let mut _1: u8; let mut _2: &u8; diff --git a/tests/mir-opt/copy-prop/borrowed_local.non_freeze.CopyProp.panic-abort.diff b/tests/mir-opt/copy-prop/borrowed_local.non_freeze.CopyProp.panic-abort.diff new file mode 100644 index 0000000000000..af2aeb0dcab25 --- /dev/null +++ b/tests/mir-opt/copy-prop/borrowed_local.non_freeze.CopyProp.panic-abort.diff @@ -0,0 +1,23 @@ +- // MIR for `non_freeze` before CopyProp ++ // MIR for `non_freeze` after CopyProp + + fn non_freeze(_1: T) -> bool { + let mut _0: bool; + let mut _2: T; + let mut _3: &T; + + bb0: { + _2 = _1; + _3 = &_1; + _0 = opaque::<&T>(_3) -> [return: bb1, unwind unreachable]; + } + + bb1: { + _0 = opaque::(_2) -> [return: bb2, unwind unreachable]; + } + + bb2: { + return; + } + } + diff --git a/tests/mir-opt/copy-prop/borrowed_local.non_freeze.CopyProp.panic-unwind.diff b/tests/mir-opt/copy-prop/borrowed_local.non_freeze.CopyProp.panic-unwind.diff new file mode 100644 index 0000000000000..040ed0aec1669 --- /dev/null +++ b/tests/mir-opt/copy-prop/borrowed_local.non_freeze.CopyProp.panic-unwind.diff @@ -0,0 +1,23 @@ +- // MIR for `non_freeze` before CopyProp ++ // MIR for `non_freeze` after CopyProp + + fn non_freeze(_1: T) -> bool { + let mut _0: bool; + let mut _2: T; + let mut _3: &T; + + bb0: { + _2 = _1; + _3 = &_1; + _0 = opaque::<&T>(_3) -> [return: bb1, unwind continue]; + } + + bb1: { + _0 = opaque::(_2) -> [return: bb2, unwind continue]; + } + + bb2: { + return; + } + } + diff --git a/tests/mir-opt/copy-prop/borrowed_local.rs b/tests/mir-opt/copy-prop/borrowed_local.rs index 74ac6281a8953..512287dd17672 100644 --- a/tests/mir-opt/copy-prop/borrowed_local.rs +++ b/tests/mir-opt/copy-prop/borrowed_local.rs @@ -1,10 +1,10 @@ -// skip-filecheck // EMIT_MIR_FOR_EACH_PANIC_STRATEGY //@ test-mir-pass: CopyProp -#![feature(custom_mir, core_intrinsics)] +#![feature(custom_mir, core_intrinsics, freeze)] #![allow(unused_assignments)] extern crate core; +use core::marker::Freeze; use core::intrinsics::mir::*; fn opaque(_: impl Sized) -> bool { true } @@ -14,7 +14,16 @@ fn cmp_ref(a: &u8, b: &u8) -> bool { } #[custom_mir(dialect = "analysis", phase = "post-cleanup")] -fn f() -> bool { +fn compare_address() -> bool { + // CHECK-LABEL: fn compare_address( + // CHECK: bb0: { + // CHECK-NEXT: _1 = const 5_u8; + // CHECK-NEXT: _2 = &_1; + // CHECK-NEXT: _3 = _1; + // CHECK-NEXT: _4 = &_3; + // CHECK-NEXT: _0 = cmp_ref(_2, _4) + // CHECK: bb1: { + // CHECK-NEXT: _0 = opaque::(_3) mir!( { let a = 5_u8; @@ -34,8 +43,60 @@ fn f() -> bool { ) } +/// Generic type `T` is `Freeze`, so shared borrows are immutable. +#[custom_mir(dialect = "analysis", phase = "post-cleanup")] +fn borrowed(x: T) -> bool { + // CHECK-LABEL: fn borrowed( + // CHECK: bb0: { + // CHECK-NEXT: _3 = &_1; + // CHECK-NEXT: _0 = opaque::<&T>(_3) + // CHECK: bb1: { + // CHECK-NEXT: _0 = opaque::(_1) + mir!( + { + let a = x; + let r1 = &x; + Call(RET = opaque(r1), ReturnTo(next), UnwindContinue()) + } + next = { + Call(RET = opaque(a), ReturnTo(ret), UnwindContinue()) + } + ret = { + Return() + } + ) +} + +/// Generic type `T` is not known to be `Freeze`, so shared borrows may be mutable. +#[custom_mir(dialect = "analysis", phase = "post-cleanup")] +fn non_freeze(x: T) -> bool { + // CHECK-LABEL: fn non_freeze( + // CHECK: bb0: { + // CHECK-NEXT: _2 = _1; + // CHECK-NEXT: _3 = &_1; + // CHECK-NEXT: _0 = opaque::<&T>(_3) + // CHECK: bb1: { + // CHECK-NEXT: _0 = opaque::(_2) + mir!( + { + let a = x; + let r1 = &x; + Call(RET = opaque(r1), ReturnTo(next), UnwindContinue()) + } + next = { + Call(RET = opaque(a), ReturnTo(ret), UnwindContinue()) + } + ret = { + Return() + } + ) +} + fn main() { - assert!(!f()); + assert!(!compare_address()); + non_freeze(5); } -// EMIT_MIR borrowed_local.f.CopyProp.diff +// EMIT_MIR borrowed_local.compare_address.CopyProp.diff +// EMIT_MIR borrowed_local.borrowed.CopyProp.diff +// EMIT_MIR borrowed_local.non_freeze.CopyProp.diff diff --git a/tests/mir-opt/gvn.borrowed.GVN.panic-abort.diff b/tests/mir-opt/gvn.borrowed.GVN.panic-abort.diff new file mode 100644 index 0000000000000..9520bd382eebb --- /dev/null +++ b/tests/mir-opt/gvn.borrowed.GVN.panic-abort.diff @@ -0,0 +1,29 @@ +- // MIR for `borrowed` before GVN ++ // MIR for `borrowed` after GVN + + fn borrowed(_1: T) -> () { + let mut _0: (); + let mut _2: T; + let mut _3: &T; + + bb0: { + _2 = _1; + _3 = &_1; + _0 = opaque::<&T>(_3) -> [return: bb1, unwind unreachable]; + } + + bb1: { +- _0 = opaque::(_2) -> [return: bb2, unwind unreachable]; ++ _0 = opaque::(_1) -> [return: bb2, unwind unreachable]; + } + + bb2: { +- _0 = opaque::((*_3)) -> [return: bb3, unwind unreachable]; ++ _0 = opaque::(_1) -> [return: bb3, unwind unreachable]; + } + + bb3: { + return; + } + } + diff --git a/tests/mir-opt/gvn.borrowed.GVN.panic-unwind.diff b/tests/mir-opt/gvn.borrowed.GVN.panic-unwind.diff new file mode 100644 index 0000000000000..4f5d76d564400 --- /dev/null +++ b/tests/mir-opt/gvn.borrowed.GVN.panic-unwind.diff @@ -0,0 +1,29 @@ +- // MIR for `borrowed` before GVN ++ // MIR for `borrowed` after GVN + + fn borrowed(_1: T) -> () { + let mut _0: (); + let mut _2: T; + let mut _3: &T; + + bb0: { + _2 = _1; + _3 = &_1; + _0 = opaque::<&T>(_3) -> [return: bb1, unwind continue]; + } + + bb1: { +- _0 = opaque::(_2) -> [return: bb2, unwind continue]; ++ _0 = opaque::(_1) -> [return: bb2, unwind continue]; + } + + bb2: { +- _0 = opaque::((*_3)) -> [return: bb3, unwind continue]; ++ _0 = opaque::(_1) -> [return: bb3, unwind continue]; + } + + bb3: { + return; + } + } + diff --git a/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff b/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff index 02bf95840dafb..68cb4d55e7b35 100644 --- a/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff +++ b/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff @@ -8,10 +8,10 @@ let mut _3: fn(u8) -> u8; let _5: (); let mut _6: fn(u8) -> u8; - let mut _9: {closure@$DIR/gvn.rs:610:19: 610:21}; + let mut _9: {closure@$DIR/gvn.rs:612:19: 612:21}; let _10: (); let mut _11: fn(); - let mut _13: {closure@$DIR/gvn.rs:610:19: 610:21}; + let mut _13: {closure@$DIR/gvn.rs:612:19: 612:21}; let _14: (); let mut _15: fn(); scope 1 { @@ -19,7 +19,7 @@ let _4: fn(u8) -> u8; scope 2 { debug g => _4; - let _7: {closure@$DIR/gvn.rs:610:19: 610:21}; + let _7: {closure@$DIR/gvn.rs:612:19: 612:21}; scope 3 { debug closure => _7; let _8: fn(); @@ -62,16 +62,16 @@ StorageDead(_6); StorageDead(_5); - StorageLive(_7); -- _7 = {closure@$DIR/gvn.rs:610:19: 610:21}; +- _7 = {closure@$DIR/gvn.rs:612:19: 612:21}; - StorageLive(_8); + nop; -+ _7 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21}; ++ _7 = const ZeroSized: {closure@$DIR/gvn.rs:612:19: 612:21}; + nop; StorageLive(_9); - _9 = _7; - _8 = move _9 as fn() (PointerCoercion(ClosureFnPointer(Normal))); -+ _9 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21}; -+ _8 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21} as fn() (PointerCoercion(ClosureFnPointer(Normal))); ++ _9 = const ZeroSized: {closure@$DIR/gvn.rs:612:19: 612:21}; ++ _8 = const ZeroSized: {closure@$DIR/gvn.rs:612:19: 612:21} as fn() (PointerCoercion(ClosureFnPointer(Normal))); StorageDead(_9); StorageLive(_10); StorageLive(_11); @@ -88,8 +88,8 @@ StorageLive(_13); - _13 = _7; - _12 = move _13 as fn() (PointerCoercion(ClosureFnPointer(Normal))); -+ _13 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21}; -+ _12 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21} as fn() (PointerCoercion(ClosureFnPointer(Normal))); ++ _13 = const ZeroSized: {closure@$DIR/gvn.rs:612:19: 612:21}; ++ _12 = const ZeroSized: {closure@$DIR/gvn.rs:612:19: 612:21} as fn() (PointerCoercion(ClosureFnPointer(Normal))); StorageDead(_13); StorageLive(_14); StorageLive(_15); diff --git a/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff b/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff index c5dcc8a8ec9d8..fa184348b3bc7 100644 --- a/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff +++ b/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff @@ -8,10 +8,10 @@ let mut _3: fn(u8) -> u8; let _5: (); let mut _6: fn(u8) -> u8; - let mut _9: {closure@$DIR/gvn.rs:610:19: 610:21}; + let mut _9: {closure@$DIR/gvn.rs:612:19: 612:21}; let _10: (); let mut _11: fn(); - let mut _13: {closure@$DIR/gvn.rs:610:19: 610:21}; + let mut _13: {closure@$DIR/gvn.rs:612:19: 612:21}; let _14: (); let mut _15: fn(); scope 1 { @@ -19,7 +19,7 @@ let _4: fn(u8) -> u8; scope 2 { debug g => _4; - let _7: {closure@$DIR/gvn.rs:610:19: 610:21}; + let _7: {closure@$DIR/gvn.rs:612:19: 612:21}; scope 3 { debug closure => _7; let _8: fn(); @@ -62,16 +62,16 @@ StorageDead(_6); StorageDead(_5); - StorageLive(_7); -- _7 = {closure@$DIR/gvn.rs:610:19: 610:21}; +- _7 = {closure@$DIR/gvn.rs:612:19: 612:21}; - StorageLive(_8); + nop; -+ _7 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21}; ++ _7 = const ZeroSized: {closure@$DIR/gvn.rs:612:19: 612:21}; + nop; StorageLive(_9); - _9 = _7; - _8 = move _9 as fn() (PointerCoercion(ClosureFnPointer(Normal))); -+ _9 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21}; -+ _8 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21} as fn() (PointerCoercion(ClosureFnPointer(Normal))); ++ _9 = const ZeroSized: {closure@$DIR/gvn.rs:612:19: 612:21}; ++ _8 = const ZeroSized: {closure@$DIR/gvn.rs:612:19: 612:21} as fn() (PointerCoercion(ClosureFnPointer(Normal))); StorageDead(_9); StorageLive(_10); StorageLive(_11); @@ -88,8 +88,8 @@ StorageLive(_13); - _13 = _7; - _12 = move _13 as fn() (PointerCoercion(ClosureFnPointer(Normal))); -+ _13 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21}; -+ _12 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21} as fn() (PointerCoercion(ClosureFnPointer(Normal))); ++ _13 = const ZeroSized: {closure@$DIR/gvn.rs:612:19: 612:21}; ++ _12 = const ZeroSized: {closure@$DIR/gvn.rs:612:19: 612:21} as fn() (PointerCoercion(ClosureFnPointer(Normal))); StorageDead(_13); StorageLive(_14); StorageLive(_15); diff --git a/tests/mir-opt/gvn.non_freeze.GVN.panic-abort.diff b/tests/mir-opt/gvn.non_freeze.GVN.panic-abort.diff new file mode 100644 index 0000000000000..7b6ed09611846 --- /dev/null +++ b/tests/mir-opt/gvn.non_freeze.GVN.panic-abort.diff @@ -0,0 +1,27 @@ +- // MIR for `non_freeze` before GVN ++ // MIR for `non_freeze` after GVN + + fn non_freeze(_1: T) -> () { + let mut _0: (); + let mut _2: T; + let mut _3: &T; + + bb0: { + _2 = _1; + _3 = &_1; + _0 = opaque::<&T>(_3) -> [return: bb1, unwind unreachable]; + } + + bb1: { + _0 = opaque::(_2) -> [return: bb2, unwind unreachable]; + } + + bb2: { + _0 = opaque::((*_3)) -> [return: bb3, unwind unreachable]; + } + + bb3: { + return; + } + } + diff --git a/tests/mir-opt/gvn.non_freeze.GVN.panic-unwind.diff b/tests/mir-opt/gvn.non_freeze.GVN.panic-unwind.diff new file mode 100644 index 0000000000000..641a2f4609acf --- /dev/null +++ b/tests/mir-opt/gvn.non_freeze.GVN.panic-unwind.diff @@ -0,0 +1,27 @@ +- // MIR for `non_freeze` before GVN ++ // MIR for `non_freeze` after GVN + + fn non_freeze(_1: T) -> () { + let mut _0: (); + let mut _2: T; + let mut _3: &T; + + bb0: { + _2 = _1; + _3 = &_1; + _0 = opaque::<&T>(_3) -> [return: bb1, unwind continue]; + } + + bb1: { + _0 = opaque::(_2) -> [return: bb2, unwind continue]; + } + + bb2: { + _0 = opaque::((*_3)) -> [return: bb3, unwind continue]; + } + + bb3: { + return; + } + } + diff --git a/tests/mir-opt/gvn.rs b/tests/mir-opt/gvn.rs index 0484710f00e7e..9be3051528356 100644 --- a/tests/mir-opt/gvn.rs +++ b/tests/mir-opt/gvn.rs @@ -6,9 +6,11 @@ #![feature(rustc_attrs)] #![feature(custom_mir)] #![feature(core_intrinsics)] +#![feature(freeze)] #![allow(unconditional_panic)] use std::intrinsics::mir::*; +use std::marker::Freeze; use std::mem::transmute; struct S(T); @@ -720,6 +722,65 @@ fn wide_ptr_integer() { opaque(a >= b); } +#[custom_mir(dialect = "analysis", phase = "post-cleanup")] +fn borrowed(x: T) { + // CHECK-LABEL: fn borrowed( + // CHECK: bb0: { + // CHECK-NEXT: _2 = _1; + // CHECK-NEXT: _3 = &_1; + // CHECK-NEXT: _0 = opaque::<&T>(_3) + // CHECK: bb1: { + // CHECK-NEXT: _0 = opaque::(_1) + // CHECK: bb2: { + // CHECK-NEXT: _0 = opaque::(_1) + mir!( + { + let a = x; + let r1 = &x; + Call(RET = opaque(r1), ReturnTo(next), UnwindContinue()) + } + next = { + Call(RET = opaque(a), ReturnTo(deref), UnwindContinue()) + } + deref = { + Call(RET = opaque(*r1), ReturnTo(ret), UnwindContinue()) + } + ret = { + Return() + } + ) +} + +/// Generic type `T` is not known to be `Freeze`, so shared borrows may be mutable. +#[custom_mir(dialect = "analysis", phase = "post-cleanup")] +fn non_freeze(x: T) { + // CHECK-LABEL: fn non_freeze( + // CHECK: bb0: { + // CHECK-NEXT: _2 = _1; + // CHECK-NEXT: _3 = &_1; + // CHECK-NEXT: _0 = opaque::<&T>(_3) + // CHECK: bb1: { + // CHECK-NEXT: _0 = opaque::(_2) + // CHECK: bb2: { + // CHECK-NEXT: _0 = opaque::((*_3)) + mir!( + { + let a = x; + let r1 = &x; + Call(RET = opaque(r1), ReturnTo(next), UnwindContinue()) + } + next = { + Call(RET = opaque(a), ReturnTo(deref), UnwindContinue()) + } + deref = { + Call(RET = opaque(*r1), ReturnTo(ret), UnwindContinue()) + } + ret = { + Return() + } + ) +} + fn main() { subexpression_elimination(2, 4, 5); wrap_unwrap(5); @@ -742,6 +803,8 @@ fn main() { constant_index_overflow(&[5, 3]); wide_ptr_provenance(); wide_ptr_integer(); + borrowed(5); + non_freeze(5); } #[inline(never)] @@ -773,3 +836,5 @@ fn identity(x: T) -> T { // EMIT_MIR gvn.wide_ptr_provenance.GVN.diff // EMIT_MIR gvn.wide_ptr_same_provenance.GVN.diff // EMIT_MIR gvn.wide_ptr_integer.GVN.diff +// EMIT_MIR gvn.borrowed.GVN.diff +// EMIT_MIR gvn.non_freeze.GVN.diff diff --git a/tests/mir-opt/gvn.slices.GVN.panic-abort.diff b/tests/mir-opt/gvn.slices.GVN.panic-abort.diff index 2389d98b5b3c5..fb67e3d599404 100644 --- a/tests/mir-opt/gvn.slices.GVN.panic-abort.diff +++ b/tests/mir-opt/gvn.slices.GVN.panic-abort.diff @@ -111,8 +111,9 @@ StorageLive(_7); StorageLive(_8); - StorageLive(_9); +- StorageLive(_10); ++ nop; + nop; - StorageLive(_10); StorageLive(_11); _11 = &(*_1); _10 = core::str::::as_ptr(move _11) -> [return: bb3, unwind unreachable]; @@ -122,8 +123,9 @@ StorageDead(_11); _9 = &_10; - StorageLive(_12); +- StorageLive(_13); ++ nop; + nop; - StorageLive(_13); StorageLive(_14); - _14 = &(*_4); + _14 = &(*_1); @@ -148,11 +150,12 @@ StorageLive(_17); StorageLive(_18); - _18 = (*_15); -+ _18 = (*_9); ++ _18 = _10; StorageLive(_19); - _19 = (*_16); -+ _19 = (*_12); - _17 = Eq(move _18, move _19); +- _17 = Eq(move _18, move _19); ++ _19 = _13; ++ _17 = Eq(_10, _13); switchInt(move _17) -> [0: bb6, otherwise: bb5]; } @@ -163,8 +166,10 @@ StorageDead(_17); StorageDead(_16); StorageDead(_15); - StorageDead(_13); - StorageDead(_10); +- StorageDead(_13); +- StorageDead(_10); ++ nop; ++ nop; StorageDead(_8); StorageDead(_7); - StorageLive(_29); @@ -213,8 +218,9 @@ StorageLive(_33); StorageLive(_34); - StorageLive(_35); +- StorageLive(_36); ++ nop; + nop; - StorageLive(_36); StorageLive(_37); _37 = &(*_1); _36 = core::str::::as_ptr(move _37) -> [return: bb8, unwind unreachable]; @@ -224,8 +230,9 @@ StorageDead(_37); _35 = &_36; - StorageLive(_38); +- StorageLive(_39); ++ nop; + nop; - StorageLive(_39); StorageLive(_40); _40 = &(*_29); _39 = core::slice::::as_ptr(move _40) -> [return: bb9, unwind unreachable]; @@ -249,11 +256,12 @@ StorageLive(_43); StorageLive(_44); - _44 = (*_41); -+ _44 = (*_35); ++ _44 = _36; StorageLive(_45); - _45 = (*_42); -+ _45 = (*_38); - _43 = Eq(move _44, move _45); +- _43 = Eq(move _44, move _45); ++ _45 = _39; ++ _43 = Eq(_36, _39); switchInt(move _43) -> [0: bb11, otherwise: bb10]; } @@ -264,8 +272,10 @@ StorageDead(_43); StorageDead(_42); StorageDead(_41); - StorageDead(_39); - StorageDead(_36); +- StorageDead(_39); +- StorageDead(_36); ++ nop; ++ nop; StorageDead(_34); StorageDead(_33); _0 = const (); diff --git a/tests/mir-opt/gvn.slices.GVN.panic-unwind.diff b/tests/mir-opt/gvn.slices.GVN.panic-unwind.diff index 50715d748e796..ae3013b011e9a 100644 --- a/tests/mir-opt/gvn.slices.GVN.panic-unwind.diff +++ b/tests/mir-opt/gvn.slices.GVN.panic-unwind.diff @@ -111,8 +111,9 @@ StorageLive(_7); StorageLive(_8); - StorageLive(_9); +- StorageLive(_10); ++ nop; + nop; - StorageLive(_10); StorageLive(_11); _11 = &(*_1); _10 = core::str::::as_ptr(move _11) -> [return: bb3, unwind continue]; @@ -122,8 +123,9 @@ StorageDead(_11); _9 = &_10; - StorageLive(_12); +- StorageLive(_13); ++ nop; + nop; - StorageLive(_13); StorageLive(_14); - _14 = &(*_4); + _14 = &(*_1); @@ -148,11 +150,12 @@ StorageLive(_17); StorageLive(_18); - _18 = (*_15); -+ _18 = (*_9); ++ _18 = _10; StorageLive(_19); - _19 = (*_16); -+ _19 = (*_12); - _17 = Eq(move _18, move _19); +- _17 = Eq(move _18, move _19); ++ _19 = _13; ++ _17 = Eq(_10, _13); switchInt(move _17) -> [0: bb6, otherwise: bb5]; } @@ -163,8 +166,10 @@ StorageDead(_17); StorageDead(_16); StorageDead(_15); - StorageDead(_13); - StorageDead(_10); +- StorageDead(_13); +- StorageDead(_10); ++ nop; ++ nop; StorageDead(_8); StorageDead(_7); - StorageLive(_29); @@ -213,8 +218,9 @@ StorageLive(_33); StorageLive(_34); - StorageLive(_35); +- StorageLive(_36); ++ nop; + nop; - StorageLive(_36); StorageLive(_37); _37 = &(*_1); _36 = core::str::::as_ptr(move _37) -> [return: bb8, unwind continue]; @@ -224,8 +230,9 @@ StorageDead(_37); _35 = &_36; - StorageLive(_38); +- StorageLive(_39); ++ nop; + nop; - StorageLive(_39); StorageLive(_40); _40 = &(*_29); _39 = core::slice::::as_ptr(move _40) -> [return: bb9, unwind continue]; @@ -249,11 +256,12 @@ StorageLive(_43); StorageLive(_44); - _44 = (*_41); -+ _44 = (*_35); ++ _44 = _36; StorageLive(_45); - _45 = (*_42); -+ _45 = (*_38); - _43 = Eq(move _44, move _45); +- _43 = Eq(move _44, move _45); ++ _45 = _39; ++ _43 = Eq(_36, _39); switchInt(move _43) -> [0: bb11, otherwise: bb10]; } @@ -264,8 +272,10 @@ StorageDead(_43); StorageDead(_42); StorageDead(_41); - StorageDead(_39); - StorageDead(_36); +- StorageDead(_39); +- StorageDead(_36); ++ nop; ++ nop; StorageDead(_34); StorageDead(_33); _0 = const (); diff --git a/tests/mir-opt/gvn_uninhabited.f.GVN.panic-abort.diff b/tests/mir-opt/gvn_uninhabited.f.GVN.panic-abort.diff index c5ee0d9c44d7d..626367766d76d 100644 --- a/tests/mir-opt/gvn_uninhabited.f.GVN.panic-abort.diff +++ b/tests/mir-opt/gvn_uninhabited.f.GVN.panic-abort.diff @@ -17,7 +17,8 @@ StorageLive(_3); _5 = const f::promoted[0]; _3 = &(*_5); - _2 = ((*_3).1: E); +- _2 = ((*_3).1: E); ++ _2 = ((*_5).1: E); StorageLive(_1); - _1 = ((_2 as A).1: u32); + _1 = const 0_u32; diff --git a/tests/mir-opt/gvn_uninhabited.f.GVN.panic-unwind.diff b/tests/mir-opt/gvn_uninhabited.f.GVN.panic-unwind.diff index c5ee0d9c44d7d..626367766d76d 100644 --- a/tests/mir-opt/gvn_uninhabited.f.GVN.panic-unwind.diff +++ b/tests/mir-opt/gvn_uninhabited.f.GVN.panic-unwind.diff @@ -17,7 +17,8 @@ StorageLive(_3); _5 = const f::promoted[0]; _3 = &(*_5); - _2 = ((*_3).1: E); +- _2 = ((*_3).1: E); ++ _2 = ((*_5).1: E); StorageLive(_1); - _1 = ((_2 as A).1: u32); + _1 = const 0_u32; diff --git a/tests/mir-opt/pre-codegen/slice_filter.variant_a-{closure#0}.PreCodegen.after.mir b/tests/mir-opt/pre-codegen/slice_filter.variant_a-{closure#0}.PreCodegen.after.mir index 65cac0a81ef13..dfa13230254c9 100644 --- a/tests/mir-opt/pre-codegen/slice_filter.variant_a-{closure#0}.PreCodegen.after.mir +++ b/tests/mir-opt/pre-codegen/slice_filter.variant_a-{closure#0}.PreCodegen.after.mir @@ -10,18 +10,18 @@ fn variant_a::{closure#0}(_1: &mut {closure@$DIR/slice_filter.rs:7:25: 7:39}, _2 let mut _8: &&usize; let _9: &usize; let mut _10: &&usize; - let mut _15: bool; + let mut _13: bool; + let mut _14: &&usize; + let _15: &usize; let mut _16: &&usize; - let _17: &usize; - let mut _18: &&usize; + let mut _19: bool; + let mut _20: &&usize; + let _21: &usize; + let mut _22: &&usize; let mut _23: bool; let mut _24: &&usize; let _25: &usize; let mut _26: &&usize; - let mut _31: bool; - let mut _32: &&usize; - let _33: &usize; - let mut _34: &&usize; scope 1 { debug a => _4; debug b => _5; @@ -30,208 +30,145 @@ fn variant_a::{closure#0}(_1: &mut {closure@$DIR/slice_filter.rs:7:25: 7:39}, _2 scope 2 (inlined std::cmp::impls::::le) { debug self => _8; debug other => _10; - let mut _11: &usize; - let mut _12: &usize; scope 3 (inlined std::cmp::impls::::le) { - debug self => _11; - debug other => _12; - let mut _13: usize; - let mut _14: usize; + debug self => _4; + debug other => _9; + let mut _11: usize; + let mut _12: usize; } } scope 4 (inlined std::cmp::impls::::le) { - debug self => _16; - debug other => _18; - let mut _19: &usize; - let mut _20: &usize; + debug self => _14; + debug other => _16; scope 5 (inlined std::cmp::impls::::le) { - debug self => _19; - debug other => _20; - let mut _21: usize; - let mut _22: usize; + debug self => _7; + debug other => _15; + let mut _17: usize; + let mut _18: usize; } } scope 6 (inlined std::cmp::impls::::le) { - debug self => _24; - debug other => _26; - let mut _27: &usize; - let mut _28: &usize; + debug self => _20; + debug other => _22; scope 7 (inlined std::cmp::impls::::le) { - debug self => _27; - debug other => _28; - let mut _29: usize; - let mut _30: usize; + debug self => _6; + debug other => _21; } } scope 8 (inlined std::cmp::impls::::le) { - debug self => _32; - debug other => _34; - let mut _35: &usize; - let mut _36: &usize; + debug self => _24; + debug other => _26; scope 9 (inlined std::cmp::impls::::le) { - debug self => _35; - debug other => _36; - let mut _37: usize; - let mut _38: usize; + debug self => _5; + debug other => _25; + let mut _27: usize; + let mut _28: usize; } } } bb0: { - StorageLive(_4); _3 = (*_2); _4 = &((*_3).0: usize); - StorageLive(_5); _5 = &((*_3).1: usize); - StorageLive(_6); _6 = &((*_3).2: usize); - StorageLive(_7); _7 = &((*_3).3: usize); - StorageLive(_15); + StorageLive(_13); StorageLive(_8); _8 = &_4; StorageLive(_10); - StorageLive(_9); - _9 = _6; + _9 = &((*_3).2: usize); _10 = &_9; - StorageLive(_11); - StorageLive(_12); - _11 = _4; - _12 = _9; - StorageLive(_13); - _13 = (*_11); - StorageLive(_14); - _14 = (*_12); - _15 = Le(move _13, move _14); - StorageDead(_14); - StorageDead(_13); - StorageDead(_12); - StorageDead(_11); - switchInt(move _15) -> [0: bb1, otherwise: bb2]; + _11 = ((*_3).0: usize); + _12 = ((*_3).2: usize); + _13 = Le(_11, _12); + switchInt(move _13) -> [0: bb1, otherwise: bb2]; } bb1: { - StorageDead(_9); StorageDead(_10); StorageDead(_8); goto -> bb4; } bb2: { - StorageDead(_9); StorageDead(_10); StorageDead(_8); - StorageLive(_23); + StorageLive(_19); + StorageLive(_14); + _14 = &_7; StorageLive(_16); - _16 = &_7; - StorageLive(_18); + _15 = &((*_3).1: usize); + _16 = &_15; StorageLive(_17); - _17 = _5; - _18 = &_17; - StorageLive(_19); - StorageLive(_20); - _19 = _7; - _20 = _17; - StorageLive(_21); - _21 = (*_19); - StorageLive(_22); - _22 = (*_20); - _23 = Le(move _21, move _22); - StorageDead(_22); - StorageDead(_21); - StorageDead(_20); - StorageDead(_19); - switchInt(move _23) -> [0: bb3, otherwise: bb8]; + _17 = ((*_3).3: usize); + StorageLive(_18); + _18 = ((*_3).1: usize); + _19 = Le(move _17, move _18); + StorageDead(_18); + StorageDead(_17); + switchInt(move _19) -> [0: bb3, otherwise: bb8]; } bb3: { - StorageDead(_17); - StorageDead(_18); StorageDead(_16); + StorageDead(_14); goto -> bb4; } bb4: { - StorageLive(_31); - StorageLive(_24); - _24 = &_6; - StorageLive(_26); - StorageLive(_25); - _25 = _4; - _26 = &_25; - StorageLive(_27); - StorageLive(_28); - _27 = _6; - _28 = _25; - StorageLive(_29); - _29 = (*_27); - StorageLive(_30); - _30 = (*_28); - _31 = Le(move _29, move _30); - StorageDead(_30); - StorageDead(_29); - StorageDead(_28); - StorageDead(_27); - switchInt(move _31) -> [0: bb5, otherwise: bb6]; + StorageLive(_23); + StorageLive(_20); + _20 = &_6; + StorageLive(_22); + _21 = &((*_3).0: usize); + _22 = &_21; + _23 = Le(_12, _11); + switchInt(move _23) -> [0: bb5, otherwise: bb6]; } bb5: { - StorageDead(_25); - StorageDead(_26); - StorageDead(_24); + StorageDead(_22); + StorageDead(_20); _0 = const false; goto -> bb7; } bb6: { - StorageDead(_25); + StorageDead(_22); + StorageDead(_20); + StorageLive(_24); + _24 = &_5; + StorageLive(_26); + _25 = &((*_3).3: usize); + _26 = &_25; + StorageLive(_27); + _27 = ((*_3).1: usize); + StorageLive(_28); + _28 = ((*_3).3: usize); + _0 = Le(move _27, move _28); + StorageDead(_28); + StorageDead(_27); StorageDead(_26); StorageDead(_24); - StorageLive(_32); - _32 = &_5; - StorageLive(_34); - StorageLive(_33); - _33 = _7; - _34 = &_33; - StorageLive(_35); - StorageLive(_36); - _35 = _5; - _36 = _33; - StorageLive(_37); - _37 = (*_35); - StorageLive(_38); - _38 = (*_36); - _0 = Le(move _37, move _38); - StorageDead(_38); - StorageDead(_37); - StorageDead(_36); - StorageDead(_35); - StorageDead(_33); - StorageDead(_34); - StorageDead(_32); goto -> bb7; } bb7: { - StorageDead(_31); + StorageDead(_23); goto -> bb9; } bb8: { - StorageDead(_17); - StorageDead(_18); StorageDead(_16); + StorageDead(_14); _0 = const true; goto -> bb9; } bb9: { - StorageDead(_23); - StorageDead(_15); - StorageDead(_7); - StorageDead(_6); - StorageDead(_5); - StorageDead(_4); + StorageDead(_19); + StorageDead(_13); return; } } diff --git a/tests/mir-opt/reference_prop.reference_propagation.ReferencePropagation.diff b/tests/mir-opt/reference_prop.reference_propagation.ReferencePropagation.diff index 1be2ce8d0bbd4..0dfe8781c186f 100644 --- a/tests/mir-opt/reference_prop.reference_propagation.ReferencePropagation.diff +++ b/tests/mir-opt/reference_prop.reference_propagation.ReferencePropagation.diff @@ -247,7 +247,8 @@ StorageLive(_21); _21 = &_20; StorageLive(_22); - _22 = (*_20); +- _22 = (*_20); ++ _22 = _19; StorageLive(_23); StorageLive(_24); _24 = _21; @@ -394,7 +395,8 @@ StorageLive(_62); _62 = &_61; StorageLive(_63); - _63 = (*_61); +- _63 = (*_61); ++ _63 = _60; StorageLive(_64); StorageLive(_65); _65 = (); diff --git a/tests/mir-opt/reference_prop.reference_propagation_const_ptr.ReferencePropagation.diff b/tests/mir-opt/reference_prop.reference_propagation_const_ptr.ReferencePropagation.diff index 1e6a168f7564e..21486a8616aab 100644 --- a/tests/mir-opt/reference_prop.reference_propagation_const_ptr.ReferencePropagation.diff +++ b/tests/mir-opt/reference_prop.reference_propagation_const_ptr.ReferencePropagation.diff @@ -260,7 +260,8 @@ StorageLive(_20); _20 = &_19; StorageLive(_21); - _21 = (*_19); +- _21 = (*_19); ++ _21 = _18; StorageLive(_22); StorageLive(_23); _23 = _20; @@ -429,7 +430,8 @@ StorageLive(_67); _67 = &_66; StorageLive(_68); - _68 = (*_66); +- _68 = (*_66); ++ _68 = _65; StorageLive(_69); StorageLive(_70); _70 = (); diff --git a/tests/mir-opt/reference_prop.rs b/tests/mir-opt/reference_prop.rs index 2dda771ba7d74..e0b0d6994206a 100644 --- a/tests/mir-opt/reference_prop.rs +++ b/tests/mir-opt/reference_prop.rs @@ -49,7 +49,7 @@ fn reference_propagation<'a, T: Copy>(single: &'a T, mut multiple: &'a T) { // CHECK: [[a:_.*]] = const 5_usize; // CHECK: [[b:_.*]] = &[[a]]; // CHECK: [[d:_.*]] = &[[b]]; - // CHECK: [[c:_.*]] = (*[[b]]); + // CHECK: [[c:_.*]] = [[a]]; let a = 5_usize; let b = &a; @@ -138,8 +138,7 @@ fn reference_propagation<'a, T: Copy>(single: &'a T, mut multiple: &'a T) { // CHECK: [[a:_.*]] = const 5_usize; // CHECK: [[b:_.*]] = &[[a]]; // CHECK: [[d:_.*]] = &[[b]]; - // FIXME this could be [[a]] - // CHECK: [[c:_.*]] = (*[[b]]); + // CHECK: [[c:_.*]] = [[a]]; let a = 5_usize; let b = &a; @@ -363,7 +362,7 @@ fn reference_propagation_const_ptr(single: *const T, mut multiple: *con // CHECK: [[a:_.*]] = const 5_usize; // CHECK: [[b:_.*]] = &raw const [[a]]; // CHECK: [[d:_.*]] = &[[b]]; - // CHECK: [[c:_.*]] = (*[[b]]); + // CHECK: [[c:_.*]] = [[a]]; let a = 5_usize; let b = &raw const a; @@ -467,8 +466,7 @@ fn reference_propagation_const_ptr(single: *const T, mut multiple: *con // CHECK: [[a:_.*]] = const 5_usize; // CHECK: [[b:_.*]] = &raw const [[a]]; // CHECK: [[d:_.*]] = &[[b]]; - // FIXME this could be [[a]] - // CHECK: [[c:_.*]] = (*[[b]]); + // CHECK: [[c:_.*]] = [[a]]; let a = 5_usize; let b = &raw const a; diff --git a/tests/run-make/CURRENT_RUSTC_VERSION/rmake.rs b/tests/run-make/CURRENT_RUSTC_VERSION/rmake.rs index fe0ceaf6b043d..4b7ce4e57d57c 100644 --- a/tests/run-make/CURRENT_RUSTC_VERSION/rmake.rs +++ b/tests/run-make/CURRENT_RUSTC_VERSION/rmake.rs @@ -5,7 +5,7 @@ use std::path::PathBuf; -use run_make_support::{rustc, aux_build}; +use run_make_support::{aux_build, rustc}; fn main() { aux_build().input("stable.rs").emit("metadata").run(); @@ -13,11 +13,7 @@ fn main() { let mut stable_path = PathBuf::from(env!("TMPDIR")); stable_path.push("libstable.rmeta"); - let output = rustc() - .input("main.rs") - .emit("metadata") - .extern_("stable", &stable_path) - .output(); + let output = rustc().input("main.rs").emit("metadata").extern_("stable", &stable_path).output(); let stderr = String::from_utf8_lossy(&output.stderr); let version = include_str!(concat!(env!("S"), "/src/version")); diff --git a/tests/run-make/compiler-builtins/rmake.rs b/tests/run-make/compiler-builtins/rmake.rs index 1784784845995..f5da50ebb043b 100644 --- a/tests/run-make/compiler-builtins/rmake.rs +++ b/tests/run-make/compiler-builtins/rmake.rs @@ -49,22 +49,22 @@ fn main() { let bootstrap_cargo = std::env::var("BOOTSTRAP_CARGO").unwrap(); let mut cmd = std::process::Command::new(bootstrap_cargo); cmd.args([ - "build", - "--manifest-path", - manifest_path.to_str().unwrap(), - "-Zbuild-std=core", - "--target", - &target, - ]) - .env_clear() - .env("PATH", path) - .env("RUSTC", rustc) - .env("RUSTFLAGS", "-Copt-level=0 -Cdebug-assertions=yes") - .env("CARGO_TARGET_DIR", &target_dir) - .env("RUSTC_BOOTSTRAP", "1") - // Visual Studio 2022 requires that the LIB env var be set so it can - // find the Windows SDK. - .env("LIB", std::env::var("LIB").unwrap_or_default()); + "build", + "--manifest-path", + manifest_path.to_str().unwrap(), + "-Zbuild-std=core", + "--target", + &target, + ]) + .env_clear() + .env("PATH", path) + .env("RUSTC", rustc) + .env("RUSTFLAGS", "-Copt-level=0 -Cdebug-assertions=yes") + .env("CARGO_TARGET_DIR", &target_dir) + .env("RUSTC_BOOTSTRAP", "1") + // Visual Studio 2022 requires that the LIB env var be set so it can + // find the Windows SDK. + .env("LIB", std::env::var("LIB").unwrap_or_default()); set_host_rpath(&mut cmd); let status = cmd.status().unwrap(); diff --git a/tests/run-make/doctests-keep-binaries/Makefile b/tests/run-make/doctests-keep-binaries/Makefile deleted file mode 100644 index 2c647851ad0b7..0000000000000 --- a/tests/run-make/doctests-keep-binaries/Makefile +++ /dev/null @@ -1,33 +0,0 @@ -# ignore-cross-compile -include ../tools.mk - -# Check that valid binaries are persisted by running them, regardless of whether the --run or --no-run option is used. - -MY_SRC_DIR := ${CURDIR} - -all: run no_run test_run_directory - -run: - mkdir -p $(TMPDIR)/doctests - $(RUSTC) --crate-type rlib t.rs - $(RUSTDOC) -Zunstable-options --test --persist-doctests $(TMPDIR)/doctests --extern t=$(TMPDIR)/libt.rlib t.rs - $(TMPDIR)/doctests/t_rs_2_0/rust_out - $(TMPDIR)/doctests/t_rs_8_0/rust_out - rm -rf $(TMPDIR)/doctests - -no_run: - mkdir -p $(TMPDIR)/doctests - $(RUSTC) --crate-type rlib t.rs - $(RUSTDOC) -Zunstable-options --test --persist-doctests $(TMPDIR)/doctests --extern t=$(TMPDIR)/libt.rlib t.rs --no-run - $(TMPDIR)/doctests/t_rs_2_0/rust_out - $(TMPDIR)/doctests/t_rs_8_0/rust_out - rm -rf $(TMPDIR)/doctests - -# Behavior with --test-run-directory with relative paths. -test_run_directory: - mkdir -p $(TMPDIR)/doctests - mkdir -p $(TMPDIR)/rundir - $(RUSTC) --crate-type rlib t.rs - ( cd $(TMPDIR); \ - $(RUSTDOC) -Zunstable-options --test --persist-doctests doctests --test-run-directory rundir --extern t=libt.rlib $(MY_SRC_DIR)/t.rs ) - rm -rf $(TMPDIR)/doctests $(TMPDIR)/rundir diff --git a/tests/run-make/doctests-keep-binaries/rmake.rs b/tests/run-make/doctests-keep-binaries/rmake.rs new file mode 100644 index 0000000000000..ad0c2764df7aa --- /dev/null +++ b/tests/run-make/doctests-keep-binaries/rmake.rs @@ -0,0 +1,68 @@ +// Check that valid binaries are persisted by running them, regardless of whether the +// --run or --no-run option is used. + +use run_make_support::{run, rustc, rustdoc, tmp_dir}; +use std::fs::{create_dir, remove_dir_all}; +use std::path::Path; + +fn setup_test_env(callback: F) { + let out_dir = tmp_dir().join("doctests"); + create_dir(&out_dir).expect("failed to create doctests folder"); + rustc().input("t.rs").crate_type("rlib").run(); + callback(&out_dir, &tmp_dir().join("libt.rlib")); + remove_dir_all(out_dir); +} + +fn check_generated_binaries() { + run("doctests/t_rs_2_0/rust_out"); + run("doctests/t_rs_8_0/rust_out"); +} + +fn main() { + setup_test_env(|out_dir, extern_path| { + rustdoc() + .input("t.rs") + .arg("-Zunstable-options") + .arg("--test") + .arg("--persist-doctests") + .arg(out_dir) + .arg("--extern") + .arg(format!("t={}", extern_path.display())) + .run(); + check_generated_binaries(); + }); + setup_test_env(|out_dir, extern_path| { + rustdoc() + .input("t.rs") + .arg("-Zunstable-options") + .arg("--test") + .arg("--persist-doctests") + .arg(out_dir) + .arg("--extern") + .arg(format!("t={}", extern_path.display())) + .arg("--no-run") + .run(); + check_generated_binaries(); + }); + // Behavior with --test-run-directory with relative paths. + setup_test_env(|_out_dir, extern_path| { + let run_dir = "rundir"; + let run_dir_path = tmp_dir().join("rundir"); + create_dir(&run_dir_path).expect("failed to create rundir folder"); + + rustdoc() + .current_dir(tmp_dir()) + .input(std::env::current_dir().unwrap().join("t.rs")) + .arg("-Zunstable-options") + .arg("--test") + .arg("--persist-doctests") + .arg("doctests") + .arg("--test-run-directory") + .arg(run_dir) + .arg("--extern") + .arg("t=libt.rlib") + .run(); + + remove_dir_all(run_dir_path); + }); +} diff --git a/tests/run-make/exit-code/rmake.rs b/tests/run-make/exit-code/rmake.rs index f4ceabe126cbf..b1143153d0af0 100644 --- a/tests/run-make/exit-code/rmake.rs +++ b/tests/run-make/exit-code/rmake.rs @@ -3,17 +3,11 @@ use run_make_support::{rustc, rustdoc, tmp_dir}; fn main() { - rustc() - .arg("success.rs") - .run(); + rustc().arg("success.rs").run(); - rustc() - .arg("--invalid-arg-foo") - .run_fail_assert_exit_code(1); + rustc().arg("--invalid-arg-foo").run_fail_assert_exit_code(1); - rustc() - .arg("compile-error.rs") - .run_fail_assert_exit_code(1); + rustc().arg("compile-error.rs").run_fail_assert_exit_code(1); rustc() .env("RUSTC_ICE", "0") @@ -21,21 +15,11 @@ fn main() { .arg("compile-error.rs") .run_fail_assert_exit_code(101); - rustdoc() - .arg("success.rs") - .arg("-o") - .arg(tmp_dir().join("exit-code")) - .run(); + rustdoc().arg("success.rs").arg("-o").arg(tmp_dir().join("exit-code")).run(); - rustdoc() - .arg("--invalid-arg-foo") - .run_fail_assert_exit_code(1); + rustdoc().arg("--invalid-arg-foo").run_fail_assert_exit_code(1); - rustdoc() - .arg("compile-error.rs") - .run_fail_assert_exit_code(1); + rustdoc().arg("compile-error.rs").run_fail_assert_exit_code(1); - rustdoc() - .arg("lint-failure.rs") - .run_fail_assert_exit_code(1); + rustdoc().arg("lint-failure.rs").run_fail_assert_exit_code(1); } diff --git a/tests/run-make/print-native-static-libs/rmake.rs b/tests/run-make/print-native-static-libs/rmake.rs index 5249920cc60e5..edb85d568c678 100644 --- a/tests/run-make/print-native-static-libs/rmake.rs +++ b/tests/run-make/print-native-static-libs/rmake.rs @@ -14,15 +14,11 @@ use std::io::BufRead; -use run_make_support::{rustc, is_msvc}; +use run_make_support::{is_msvc, rustc}; fn main() { // build supporting crate - rustc() - .input("bar.rs") - .crate_type("rlib") - .arg("-lbar_cli") - .run(); + rustc().input("bar.rs").crate_type("rlib").arg("-lbar_cli").run(); // build main crate as staticlib let output = rustc() @@ -37,7 +33,9 @@ fn main() { for l in output.stderr.lines() { let l = l.expect("utf-8 string"); - let Some(args) = l.strip_prefix("note: native-static-libs:") else { continue; }; + let Some(args) = l.strip_prefix("note: native-static-libs:") else { + continue; + }; assert!(!found_note); found_note = true; @@ -53,11 +51,11 @@ fn main() { ); let found = $args.contains(&&*lib); assert!(found, "unable to find lib `{}` in those linker args: {:?}", lib, $args); - }} + }}; } assert_contains_lib!("glib-2.0" in args); // in bar.rs - assert_contains_lib!("systemd" in args); // in foo.rs + assert_contains_lib!("systemd" in args); // in foo.rs assert_contains_lib!("bar_cli" in args); assert_contains_lib!("foo_cli" in args); diff --git a/tests/run-make/print-to-output/rmake.rs b/tests/run-make/print-to-output/rmake.rs index f710d0dc3c9b5..1763cd378d2d9 100644 --- a/tests/run-make/print-to-output/rmake.rs +++ b/tests/run-make/print-to-output/rmake.rs @@ -13,11 +13,7 @@ struct Option<'a> { fn main() { // Printed from CodegenBackend trait impl in rustc_codegen_llvm/src/lib.rs - check(Option { - target: &target(), - option: "relocation-models", - includes: &["dynamic-no-pic"], - }); + check(Option { target: &target(), option: "relocation-models", includes: &["dynamic-no-pic"] }); // Printed by compiler/rustc_codegen_llvm/src/llvm_util.rs check(Option { diff --git a/tests/run-make/rustdoc-determinism/Makefile b/tests/run-make/rustdoc-determinism/Makefile deleted file mode 100644 index a3ef169067184..0000000000000 --- a/tests/run-make/rustdoc-determinism/Makefile +++ /dev/null @@ -1,16 +0,0 @@ -include ../tools.mk - -# Assert that the search index is generated deterministically, regardless of the -# order that crates are documented in. - -# ignore-windows -# Uses `diff`. - -all: - $(RUSTDOC) foo.rs -o $(TMPDIR)/foo_first - $(RUSTDOC) bar.rs -o $(TMPDIR)/foo_first - - $(RUSTDOC) bar.rs -o $(TMPDIR)/bar_first - $(RUSTDOC) foo.rs -o $(TMPDIR)/bar_first - - diff $(TMPDIR)/foo_first/search-index.js $(TMPDIR)/bar_first/search-index.js diff --git a/tests/run-make/rustdoc-determinism/rmake.rs b/tests/run-make/rustdoc-determinism/rmake.rs new file mode 100644 index 0000000000000..38ae75199fd83 --- /dev/null +++ b/tests/run-make/rustdoc-determinism/rmake.rs @@ -0,0 +1,18 @@ +use run_make_support::{diff, rustc, rustdoc, tmp_dir}; + +/// Assert that the search index is generated deterministically, regardless of the +/// order that crates are documented in. +fn main() { + let dir_first = tmp_dir().join("first"); + rustdoc().out_dir(&dir_first).input("foo.rs").run(); + rustdoc().out_dir(&dir_first).input("bar.rs").run(); + + let dir_second = tmp_dir().join("second"); + rustdoc().out_dir(&dir_second).input("bar.rs").run(); + rustdoc().out_dir(&dir_second).input("foo.rs").run(); + + diff() + .expected_file(dir_first.join("search-index.js")) + .actual_file(dir_second.join("search-index.js")) + .run(); +} diff --git a/tests/run-make/stdin-non-utf8/Makefile b/tests/run-make/stdin-non-utf8/Makefile deleted file mode 100644 index 709d4cf140895..0000000000000 --- a/tests/run-make/stdin-non-utf8/Makefile +++ /dev/null @@ -1,6 +0,0 @@ -include ../tools.mk - -all: - cp non-utf8 $(TMPDIR)/non-utf.rs - cat $(TMPDIR)/non-utf.rs | $(RUSTC) - 2>&1 \ - | $(CGREP) "error: couldn't read from stdin, as it did not contain valid UTF-8" diff --git a/tests/run-make/stdin-non-utf8/non-utf8 b/tests/run-make/stdin-non-utf8/non-utf8 deleted file mode 100644 index bc87051a85299..0000000000000 --- a/tests/run-make/stdin-non-utf8/non-utf8 +++ /dev/null @@ -1 +0,0 @@ -Ò diff --git a/tests/run-make/stdin-rustc/rmake.rs b/tests/run-make/stdin-rustc/rmake.rs new file mode 100644 index 0000000000000..c07a6df4d84a2 --- /dev/null +++ b/tests/run-make/stdin-rustc/rmake.rs @@ -0,0 +1,26 @@ +//! This test checks rustc `-` (stdin) support + +use run_make_support::{is_windows, rustc, tmp_dir}; + +const HELLO_WORLD: &str = r#" +fn main() { + println!("Hello world!"); +} +"#; + +const NOT_UTF8: &[u8] = &[0xff, 0xff, 0xff]; + +fn main() { + let out_dir = tmp_dir(); + + // echo $HELLO_WORLD | rustc - + rustc().arg("-").stdin(HELLO_WORLD).run(); + assert!( + out_dir.join(if !is_windows() { "rust_out" } else { "rust_out.exe" }).try_exists().unwrap() + ); + + // echo $NOT_UTF8 | rustc - + let output = rustc().arg("-").stdin(NOT_UTF8).run_fail(); + let stderr = String::from_utf8(output.stderr).unwrap(); + assert!(stderr.contains("error: couldn't read from stdin, as it did not contain valid UTF-8")); +} diff --git a/tests/run-make/wasm-custom-sections-opt/rmake.rs b/tests/run-make/wasm-custom-sections-opt/rmake.rs index 24570d8baf5a6..50916b1bf815a 100644 --- a/tests/run-make/wasm-custom-sections-opt/rmake.rs +++ b/tests/run-make/wasm-custom-sections-opt/rmake.rs @@ -1,6 +1,6 @@ //@ only-wasm32-wasip1 -use run_make_support::{tmp_dir, wasmparser, rustc}; +use run_make_support::{rustc, tmp_dir, wasmparser}; use std::collections::HashMap; use std::path::Path; diff --git a/tests/run-make/wasm-export-all-symbols/rmake.rs b/tests/run-make/wasm-export-all-symbols/rmake.rs index 50c99d027d5ac..f4c51bc4ab418 100644 --- a/tests/run-make/wasm-export-all-symbols/rmake.rs +++ b/tests/run-make/wasm-export-all-symbols/rmake.rs @@ -1,6 +1,6 @@ //@ only-wasm32-wasip1 -use run_make_support::{tmp_dir, wasmparser, rustc}; +use run_make_support::{rustc, tmp_dir, wasmparser}; use std::collections::HashMap; use std::path::Path; use wasmparser::ExternalKind::*; diff --git a/tests/run-make/wasm-import-module/rmake.rs b/tests/run-make/wasm-import-module/rmake.rs index 333d0df4653fa..6eed229e90789 100644 --- a/tests/run-make/wasm-import-module/rmake.rs +++ b/tests/run-make/wasm-import-module/rmake.rs @@ -1,17 +1,12 @@ //@ only-wasm32-wasip1 -use run_make_support::{tmp_dir, wasmparser, rustc}; +use run_make_support::{rustc, tmp_dir, wasmparser}; use std::collections::HashMap; use wasmparser::TypeRef::Func; fn main() { rustc().input("foo.rs").target("wasm32-wasip1").run(); - rustc() - .input("bar.rs") - .target("wasm32-wasip1") - .arg("-Clto") - .opt() - .run(); + rustc().input("bar.rs").target("wasm32-wasip1").arg("-Clto").opt().run(); let file = std::fs::read(&tmp_dir().join("bar.wasm")).unwrap(); diff --git a/tests/rustdoc-gui/settings-button.goml b/tests/rustdoc-gui/settings-button.goml new file mode 100644 index 0000000000000..c38a537e04782 --- /dev/null +++ b/tests/rustdoc-gui/settings-button.goml @@ -0,0 +1,31 @@ +// This test ensures that the icon of the settings button looks as expected on +// all themes. +include: "utils.goml" +go-to: "file://" + |DOC_PATH| + "/test_docs/index.html" +show-text: true + +define-function: ( + "check-image", + [theme, filter], + block { + call-function: ("switch-theme", {"theme": |theme|}) + assert-css: ("#settings-menu > a::before", { + "filter": |filter|, + "width": "22px", + "height": "22px", + }) + } +) + +call-function: ("check-image", { + "theme": "ayu", + "filter": "invert(1)", +}) +call-function: ("check-image", { + "theme": "dark", + "filter": "none", +}) +call-function: ("check-image", { + "theme": "light", + "filter": "none", +}) diff --git a/tests/rustdoc-gui/settings.goml b/tests/rustdoc-gui/settings.goml index 0011e44ca59ea..3f4f2946bf5af 100644 --- a/tests/rustdoc-gui/settings.goml +++ b/tests/rustdoc-gui/settings.goml @@ -1,6 +1,5 @@ // This test ensures that the settings menu display is working as expected and that // the settings page is also rendered as expected. -include: "utils.goml" go-to: "file://" + |DOC_PATH| + "/test_docs/index.html" show-text: true // needed when we check for colors below. // First, we check that the settings page doesn't exist. diff --git a/tests/rustdoc-gui/src/theme_css/custom-theme.css b/tests/rustdoc-gui/src/theme_css/custom-theme.css index b7f89d4cf15d3..a56c31ab9d26f 100644 --- a/tests/rustdoc-gui/src/theme_css/custom-theme.css +++ b/tests/rustdoc-gui/src/theme_css/custom-theme.css @@ -49,6 +49,7 @@ --search-tab-button-not-selected-background: #e6e6e6; --search-tab-button-selected-border-top-color: #0089ff; --search-tab-button-selected-background: #fff; + --settings-menu-filter: none; --stab-background-color: #fff5d6; --stab-code-color: #000; --code-highlight-kw-color: #8959a8; diff --git a/tests/rustdoc-js-std/parser-reference.js b/tests/rustdoc-js-std/parser-reference.js new file mode 100644 index 0000000000000..6b1250146bef8 --- /dev/null +++ b/tests/rustdoc-js-std/parser-reference.js @@ -0,0 +1,527 @@ +const PARSED = [ + { + query: '&[', + elems: [], + foundElems: 0, + original: '&[', + returned: [], + userQuery: '&[', + error: 'Unclosed `[`', + }, + { + query: '[&', + elems: [], + foundElems: 0, + original: '[&', + returned: [], + userQuery: '[&', + error: 'Unclosed `[`', + }, + { + query: '&&&D, []', + elems: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "d", + fullPath: ["d"], + pathWithoutLast: [], + pathLast: "d", + generics: [], + typeFilter: -1, + }, + ], + typeFilter: 1, + }, + ], + typeFilter: 1, + }, + ], + typeFilter: 1, + }, + { + name: "[]", + fullPath: ["[]"], + pathWithoutLast: [], + pathLast: "[]", + generics: [], + typeFilter: 1, + }, + ], + foundElems: 2, + original: '&&&D, []', + returned: [], + userQuery: '&&&d, []', + error: null, + }, + { + query: '&&&[D]', + elems: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "[]", + fullPath: ["[]"], + pathWithoutLast: [], + pathLast: "[]", + generics: [ + { + name: "d", + fullPath: ["d"], + pathWithoutLast: [], + pathLast: "d", + generics: [], + typeFilter: -1, + }, + ], + typeFilter: 1, + }, + ], + typeFilter: 1, + }, + ], + typeFilter: 1, + }, + ], + typeFilter: 1, + }, + ], + foundElems: 1, + original: '&&&[D]', + returned: [], + userQuery: '&&&[d]', + error: null, + }, + { + query: '&', + elems: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [], + typeFilter: 1, + }, + ], + foundElems: 1, + original: '&', + returned: [], + userQuery: '&', + error: null, + }, + { + query: '&mut', + elems: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "mut", + fullPath: ["mut"], + pathWithoutLast: [], + pathLast: "mut", + generics: [], + typeFilter: 0, + }, + ], + typeFilter: 1, + }, + ], + foundElems: 1, + original: '&mut', + returned: [], + userQuery: '&mut', + error: null, + }, + { + query: '&,u8', + elems: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [], + typeFilter: 1, + }, + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [], + typeFilter: -1, + }, + ], + foundElems: 2, + original: "&,u8", + returned: [], + userQuery: "&,u8", + error: null, + }, + { + query: '&mut,u8', + elems: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "mut", + fullPath: ["mut"], + pathWithoutLast: [], + pathLast: "mut", + generics: [], + typeFilter: 0, + }, + ], + typeFilter: 1, + }, + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [], + typeFilter: -1, + }, + ], + foundElems: 2, + original: "&mut,u8", + returned: [], + userQuery: "&mut,u8", + error: null, + }, + { + query: '&u8', + elems: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [], + typeFilter: -1, + }, + ], + typeFilter: 1, + }, + ], + foundElems: 1, + original: "&u8", + returned: [], + userQuery: "&u8", + error: null, + }, + { + query: '&u8', + elems: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [ + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [], + typeFilter: -1, + }, + ], + typeFilter: -1, + }, + ], + typeFilter: 1, + }, + ], + foundElems: 1, + original: "&u8", + returned: [], + userQuery: "&u8", + error: null, + }, + { + query: 'u8<&u8>', + elems: [ + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [], + typeFilter: -1, + }, + ], + typeFilter: 1, + }, + ], + typeFilter: -1, + }, + ], + foundElems: 1, + original: "u8<&u8>", + returned: [], + userQuery: "u8<&u8>", + error: null, + }, + { + query: 'u8<&u8, u8>', + elems: [ + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [], + typeFilter: -1, + }, + ], + typeFilter: 1, + }, + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [], + typeFilter: -1, + }, + ], + typeFilter: -1, + }, + ], + foundElems: 1, + original: "u8<&u8, u8>", + returned: [], + userQuery: "u8<&u8, u8>", + error: null, + }, + { + query: 'u8<&u8>', + elems: [ + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [], + typeFilter: -1, + }, + ], + typeFilter: 1, + }, + ], + typeFilter: -1, + }, + ], + foundElems: 1, + original: "u8<&u8>", + returned: [], + userQuery: "u8<&u8>", + error: null, + }, + { + query: 'u8<&mut u8, u8>', + elems: [ + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "mut", + fullPath: ["mut"], + pathWithoutLast: [], + pathLast: "mut", + generics: [], + typeFilter: 0, + }, + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [], + typeFilter: -1, + }, + ], + typeFilter: 1, + }, + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [], + typeFilter: -1, + }, + ], + typeFilter: -1, + }, + ], + foundElems: 1, + original: "u8<&mut u8, u8>", + returned: [], + userQuery: "u8<&mut u8, u8>", + error: null, + }, + { + query: 'primitive:&u8', + elems: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [], + typeFilter: -1, + }, + ], + typeFilter: 1, + }, + ], + foundElems: 1, + original: "primitive:&u8", + returned: [], + userQuery: "primitive:&u8", + error: null, + }, + { + query: 'macro:&u8', + elems: [], + foundElems: 0, + original: "macro:&u8", + returned: [], + userQuery: "macro:&u8", + error: "Invalid search type: primitive `&` and `macro` both specified", + }, + { + query: '¯o:u8', + elems: [ + { + name: "reference", + fullPath: ["reference"], + pathWithoutLast: [], + pathLast: "reference", + generics: [ + { + name: "u8", + fullPath: ["u8"], + pathWithoutLast: [], + pathLast: "u8", + generics: [], + typeFilter: 16, + }, + ], + typeFilter: 1, + }, + ], + foundElems: 1, + original: "¯o:u8", + returned: [], + userQuery: "¯o:u8", + error: null, + }, +]; diff --git a/tests/rustdoc-js/reference.js b/tests/rustdoc-js/reference.js new file mode 100644 index 0000000000000..b4a1fb15d369a --- /dev/null +++ b/tests/rustdoc-js/reference.js @@ -0,0 +1,236 @@ +// exact-check + +const EXPECTED = [ + // pinkie with explicit names + { + 'query': 'usize, usize -> ()', + 'others': [ + { 'path': 'reference', 'name': 'pinky' }, + ], + }, + { + 'query': 'reference, usize -> ()', + 'others': [ + { 'path': 'reference', 'name': 'pinky' }, + ], + }, + { + 'query': 'reference, reference -> ()', + 'others': [], + }, + { + 'query': 'reference, usize -> ()', + 'others': [], + }, + // thumb with explicit names + { + 'query': 'thumb, thumb -> ()', + 'others': [ + { 'path': 'reference::Thumb', 'name': 'up' }, + ], + }, + { + 'query': 'reference, thumb -> ()', + 'others': [ + { 'path': 'reference::Thumb', 'name': 'up' }, + ], + }, + { + 'query': 'reference, reference -> ()', + 'others': [], + }, + { + 'query': 'reference, thumb -> ()', + 'others': [], + }, + // index with explicit names + { + 'query': 'index, index -> ()', + 'others': [ + { 'path': 'reference::Index', 'name': 'point' }, + ], + }, + { + 'query': 'reference, index -> ()', + 'others': [ + { 'path': 'reference::Index', 'name': 'point' }, + ], + }, + { + 'query': 'reference, reference -> ()', + 'others': [], + }, + { + 'query': 'reference, index -> ()', + 'others': [], + }, + // ring with explicit names + { + 'query': 'ring, ring -> ()', + 'others': [ + { 'path': 'reference::Ring', 'name': 'wear' }, + ], + }, + { + 'query': 'reference, ring -> ()', + 'others': [ + { 'path': 'reference::Ring', 'name': 'wear' }, + ], + }, + { + 'query': 'reference, reference -> ()', + 'others': [ + { 'path': 'reference::Ring', 'name': 'wear' }, + ], + }, + { + 'query': 'reference, reference -> ()', + 'others': [ + { 'path': 'reference::Ring', 'name': 'wear' }, + ], + }, + { + 'query': 'reference, reference -> ()', + 'others': [], + }, + // middle with explicit names + { + 'query': 'middle, middle -> ()', + 'others': [ + { 'path': 'reference', 'name': 'show' }, + ], + }, + { + 'query': 'reference, reference -> ()', + 'others': [ + { 'path': 'reference', 'name': 'show' }, + ], + }, + { + 'query': 'reference, reference -> ()', + 'others': [ + { 'path': 'reference', 'name': 'show' }, + ], + }, + { + 'query': 'reference>, reference> -> ()', + 'others': [ + { 'path': 'reference', 'name': 'show' }, + ], + }, + { + 'query': 'reference>, reference> -> ()', + 'others': [ + { 'path': 'reference', 'name': 'show' }, + ], + }, + { + 'query': 'reference>, reference> -> ()', + 'others': [], + }, + { + 'query': 'reference>, reference> -> ()', + 'others': [], + }, + // pinkie with shorthand + { + 'query': '&usize, usize -> ()', + 'others': [ + { 'path': 'reference', 'name': 'pinky' }, + ], + }, + { + 'query': '&usize, &usize -> ()', + 'others': [], + }, + { + 'query': '&mut usize, usize -> ()', + 'others': [], + }, + // thumb with shorthand + { + 'query': '&thumb, thumb -> ()', + 'others': [ + { 'path': 'reference::Thumb', 'name': 'up' }, + ], + }, + { + 'query': '&thumb, &thumb -> ()', + 'others': [], + }, + { + 'query': '&mut thumb, thumb -> ()', + 'others': [], + }, + // index with explicit names + { + 'query': '&index, index -> ()', + 'others': [ + { 'path': 'reference::Index', 'name': 'point' }, + ], + }, + { + 'query': '&index, &index -> ()', + 'others': [], + }, + { + 'query': '&mut index, index -> ()', + 'others': [], + }, + // ring with shorthand + { + 'query': '&ring, ring -> ()', + 'others': [ + { 'path': 'reference::Ring', 'name': 'wear' }, + ], + }, + { + 'query': '&ring, ring -> ()', + 'others': [ + { 'path': 'reference::Ring', 'name': 'wear' }, + ], + }, + { + 'query': '&mut ring, &ring -> ()', + 'others': [ + { 'path': 'reference::Ring', 'name': 'wear' }, + ], + }, + { + 'query': '&mut ring, &mut ring -> ()', + 'others': [], + }, + // middle with shorthand + { + 'query': '&middle, &middle -> ()', + 'others': [ + { 'path': 'reference', 'name': 'show' }, + ], + }, + { + 'query': '&mut middle, &mut middle -> ()', + 'others': [ + { 'path': 'reference', 'name': 'show' }, + ], + }, + { + 'query': '&&mut middle, &mut &middle -> ()', + 'others': [ + { 'path': 'reference', 'name': 'show' }, + ], + }, + { + 'query': '&mut &middle, &&mut middle -> ()', + 'others': [ + { 'path': 'reference', 'name': 'show' }, + ], + }, + { + 'query': '&&mut middle, &&mut middle -> ()', + 'others': [], + }, + { + 'query': '&mut &middle, &mut &middle -> ()', + 'others': [], + }, +]; diff --git a/tests/rustdoc-js/reference.rs b/tests/rustdoc-js/reference.rs new file mode 100644 index 0000000000000..3a0a23c65d5b9 --- /dev/null +++ b/tests/rustdoc-js/reference.rs @@ -0,0 +1,32 @@ +#![feature(extern_types)] + +pub fn pinky(input: &usize, manage: usize) { + unimplemented!() +} + +pub struct Thumb; + +impl Thumb { + pub fn up(&self, finger: Thumb) { unimplemented!() } +} + +pub enum Index {} + +impl Index { + pub fn point(self, data: &Index) { unimplemented!() } +} + +pub union Ring { + magic: u32, + marriage: f32, +} + +impl Ring { + pub fn wear(&mut self, extra: &Ring) { unimplemented!() } +} + +extern "C" { + pub type Middle; +} + +pub fn show(left: &&mut Middle, right: &mut &Middle) { unimplemented!() } diff --git a/tests/rustdoc-ui/argfile/commandline-argfile.rs b/tests/rustdoc-ui/argfile/commandline-argfile.rs index b0b314f53ceb7..d5a1cd0a5ed7a 100644 --- a/tests/rustdoc-ui/argfile/commandline-argfile.rs +++ b/tests/rustdoc-ui/argfile/commandline-argfile.rs @@ -1,7 +1,8 @@ // Check to see if we can get parameters from an @argsfile file // //@ check-pass -//@ compile-flags: --cfg cmdline_set @{{src-base}}/argfile/commandline-argfile.args +//@ compile-flags: --cfg cmdline_set --check-cfg=cfg(cmdline_set,unbroken) +//@ compile-flags: @{{src-base}}/argfile/commandline-argfile.args #[cfg(not(cmdline_set))] compile_error!("cmdline_set not set"); @@ -9,5 +10,4 @@ compile_error!("cmdline_set not set"); #[cfg(not(unbroken))] compile_error!("unbroken not set"); -fn main() { -} +fn main() {} diff --git a/tests/ui/argfile/commandline-argfile.rs b/tests/ui/argfile/commandline-argfile.rs index 387a8d033b3cd..b7f1e8ed6aaa9 100644 --- a/tests/ui/argfile/commandline-argfile.rs +++ b/tests/ui/argfile/commandline-argfile.rs @@ -1,7 +1,8 @@ // Check to see if we can get parameters from an @argsfile file // //@ build-pass -//@ compile-flags: --cfg cmdline_set @{{src-base}}/argfile/commandline-argfile.args +//@ compile-flags: --cfg cmdline_set --check-cfg=cfg(cmdline_set,unbroken) +//@ compile-flags: @{{src-base}}/argfile/commandline-argfile.args #[cfg(not(cmdline_set))] compile_error!("cmdline_set not set"); @@ -9,5 +10,4 @@ compile_error!("cmdline_set not set"); #[cfg(not(unbroken))] compile_error!("unbroken not set"); -fn main() { -} +fn main() {} diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-bare.rs b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-bare.rs deleted file mode 100644 index 5d95fc70e78e9..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-bare.rs +++ /dev/null @@ -1,4 +0,0 @@ -#![feature(unix_sigpipe)] - -#[unix_sigpipe] //~ error: malformed `unix_sigpipe` attribute input -fn main() {} diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-bare.stderr b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-bare.stderr deleted file mode 100644 index c1b4470d54a4a..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-bare.stderr +++ /dev/null @@ -1,8 +0,0 @@ -error: malformed `unix_sigpipe` attribute input - --> $DIR/unix_sigpipe-bare.rs:3:1 - | -LL | #[unix_sigpipe] - | ^^^^^^^^^^^^^^^ help: must be of the form: `#[unix_sigpipe = "inherit|sig_ign|sig_dfl"]` - -error: aborting due to 1 previous error - diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-crate.rs b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-crate.rs deleted file mode 100644 index f5fa177f29c18..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-crate.rs +++ /dev/null @@ -1,4 +0,0 @@ -#![feature(unix_sigpipe)] -#![unix_sigpipe = "sig_dfl"] //~ error: `unix_sigpipe` attribute cannot be used at crate level - -fn main() {} diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-crate.stderr b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-crate.stderr deleted file mode 100644 index fdfa30180863b..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-crate.stderr +++ /dev/null @@ -1,17 +0,0 @@ -error: `unix_sigpipe` attribute cannot be used at crate level - --> $DIR/unix_sigpipe-crate.rs:2:1 - | -LL | #![unix_sigpipe = "sig_dfl"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -LL | -LL | fn main() {} - | ---- the inner attribute doesn't annotate this function - | -help: perhaps you meant to use an outer attribute - | -LL - #![unix_sigpipe = "sig_dfl"] -LL + #[unix_sigpipe = "sig_dfl"] - | - -error: aborting due to 1 previous error - diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-different-duplicates.rs b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-different-duplicates.rs deleted file mode 100644 index 294cb38526bd0..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-different-duplicates.rs +++ /dev/null @@ -1,5 +0,0 @@ -#![feature(unix_sigpipe)] - -#[unix_sigpipe = "sig_ign"] -#[unix_sigpipe = "inherit"] //~ error: multiple `unix_sigpipe` attributes -fn main() {} diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-different-duplicates.stderr b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-different-duplicates.stderr deleted file mode 100644 index c2a3b9f45f9ac..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-different-duplicates.stderr +++ /dev/null @@ -1,14 +0,0 @@ -error: multiple `unix_sigpipe` attributes - --> $DIR/unix_sigpipe-different-duplicates.rs:4:1 - | -LL | #[unix_sigpipe = "inherit"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove this attribute - | -note: attribute also specified here - --> $DIR/unix_sigpipe-different-duplicates.rs:3:1 - | -LL | #[unix_sigpipe = "sig_ign"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to 1 previous error - diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-duplicates.rs b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-duplicates.rs deleted file mode 100644 index eccb23021b6b8..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-duplicates.rs +++ /dev/null @@ -1,5 +0,0 @@ -#![feature(unix_sigpipe)] - -#[unix_sigpipe = "inherit"] -#[unix_sigpipe = "inherit"] //~ error: multiple `unix_sigpipe` attributes -fn main() {} diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-duplicates.stderr b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-duplicates.stderr deleted file mode 100644 index c86e54a1e532f..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-duplicates.stderr +++ /dev/null @@ -1,14 +0,0 @@ -error: multiple `unix_sigpipe` attributes - --> $DIR/unix_sigpipe-duplicates.rs:4:1 - | -LL | #[unix_sigpipe = "inherit"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove this attribute - | -note: attribute also specified here - --> $DIR/unix_sigpipe-duplicates.rs:3:1 - | -LL | #[unix_sigpipe = "inherit"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to 1 previous error - diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-ident-list.rs b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-ident-list.rs deleted file mode 100644 index 462ae24a88425..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-ident-list.rs +++ /dev/null @@ -1,4 +0,0 @@ -#![feature(unix_sigpipe)] - -#[unix_sigpipe(sig_dfl)] //~ error: malformed `unix_sigpipe` attribute input -fn main() {} diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-ident-list.stderr b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-ident-list.stderr deleted file mode 100644 index a020f21e6ca77..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-ident-list.stderr +++ /dev/null @@ -1,8 +0,0 @@ -error: malformed `unix_sigpipe` attribute input - --> $DIR/unix_sigpipe-ident-list.rs:3:1 - | -LL | #[unix_sigpipe(sig_dfl)] - | ^^^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[unix_sigpipe = "inherit|sig_ign|sig_dfl"]` - -error: aborting due to 1 previous error - diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-non-main-fn.rs b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-non-main-fn.rs deleted file mode 100644 index 16731a4ba2c6e..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-non-main-fn.rs +++ /dev/null @@ -1,6 +0,0 @@ -#![feature(unix_sigpipe)] - -#[unix_sigpipe = "sig_dfl"] //~ error: `unix_sigpipe` attribute can only be used on `fn main()` -fn f() {} - -fn main() {} diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-non-main-fn.stderr b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-non-main-fn.stderr deleted file mode 100644 index fcdd5db8f294b..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-non-main-fn.stderr +++ /dev/null @@ -1,8 +0,0 @@ -error: `unix_sigpipe` attribute can only be used on `fn main()` - --> $DIR/unix_sigpipe-non-main-fn.rs:3:1 - | -LL | #[unix_sigpipe = "sig_dfl"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to 1 previous error - diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-non-root-main.rs b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-non-root-main.rs deleted file mode 100644 index a2435258620a0..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-non-root-main.rs +++ /dev/null @@ -1,8 +0,0 @@ -#![feature(unix_sigpipe)] - -mod m { - #[unix_sigpipe = "sig_dfl"] //~ error: `unix_sigpipe` attribute can only be used on root `fn main()` - fn main() {} -} - -fn main() {} diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-non-root-main.stderr b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-non-root-main.stderr deleted file mode 100644 index 98afb62fdb43b..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-non-root-main.stderr +++ /dev/null @@ -1,8 +0,0 @@ -error: `unix_sigpipe` attribute can only be used on root `fn main()` - --> $DIR/unix_sigpipe-non-root-main.rs:4:5 - | -LL | #[unix_sigpipe = "sig_dfl"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to 1 previous error - diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-start.rs b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-start.rs deleted file mode 100644 index 945b820f9e00a..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-start.rs +++ /dev/null @@ -1,6 +0,0 @@ -#![feature(start)] -#![feature(unix_sigpipe)] - -#[start] -#[unix_sigpipe = "sig_dfl"] //~ error: `unix_sigpipe` attribute can only be used on `fn main()` -fn custom_start(argc: isize, argv: *const *const u8) -> isize { 0 } diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-start.stderr b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-start.stderr deleted file mode 100644 index 3d56b3655c957..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-start.stderr +++ /dev/null @@ -1,8 +0,0 @@ -error: `unix_sigpipe` attribute can only be used on `fn main()` - --> $DIR/unix_sigpipe-start.rs:5:1 - | -LL | #[unix_sigpipe = "sig_dfl"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to 1 previous error - diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-str-list.rs b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-str-list.rs deleted file mode 100644 index 22326835623bc..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-str-list.rs +++ /dev/null @@ -1,4 +0,0 @@ -#![feature(unix_sigpipe)] - -#[unix_sigpipe("sig_dfl")] //~ error: malformed `unix_sigpipe` attribute input -fn main() {} diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-str-list.stderr b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-str-list.stderr deleted file mode 100644 index b62c086e36059..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-str-list.stderr +++ /dev/null @@ -1,8 +0,0 @@ -error: malformed `unix_sigpipe` attribute input - --> $DIR/unix_sigpipe-str-list.rs:3:1 - | -LL | #[unix_sigpipe("sig_dfl")] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ help: must be of the form: `#[unix_sigpipe = "inherit|sig_ign|sig_dfl"]` - -error: aborting due to 1 previous error - diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-struct.rs b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-struct.rs deleted file mode 100644 index 662779c082177..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-struct.rs +++ /dev/null @@ -1,6 +0,0 @@ -#![feature(unix_sigpipe)] - -#[unix_sigpipe = "sig_dfl"] //~ error: `unix_sigpipe` attribute can only be used on `fn main()` -struct S; - -fn main() {} diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-struct.stderr b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-struct.stderr deleted file mode 100644 index a8fc51bdbc430..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-struct.stderr +++ /dev/null @@ -1,8 +0,0 @@ -error: `unix_sigpipe` attribute can only be used on `fn main()` - --> $DIR/unix_sigpipe-struct.rs:3:1 - | -LL | #[unix_sigpipe = "sig_dfl"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to 1 previous error - diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-wrong.rs b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-wrong.rs deleted file mode 100644 index 4ec25de00ec3b..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-wrong.rs +++ /dev/null @@ -1,4 +0,0 @@ -#![feature(unix_sigpipe)] - -#[unix_sigpipe = "wrong"] //~ error: valid values for `#[unix_sigpipe = "..."]` are `inherit`, `sig_ign`, or `sig_dfl` -fn main() {} diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-wrong.stderr b/tests/ui/attributes/unix_sigpipe/unix_sigpipe-wrong.stderr deleted file mode 100644 index d750443e4a984..0000000000000 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-wrong.stderr +++ /dev/null @@ -1,8 +0,0 @@ -error: valid values for `#[unix_sigpipe = "..."]` are `inherit`, `sig_ign`, or `sig_dfl` - --> $DIR/unix_sigpipe-wrong.rs:3:1 - | -LL | #[unix_sigpipe = "wrong"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^ - -error: aborting due to 1 previous error - diff --git a/tests/ui/binding/match-range.rs b/tests/ui/binding/match-range.rs index a024e5e585ae7..097ccb34f87c3 100644 --- a/tests/ui/binding/match-range.rs +++ b/tests/ui/binding/match-range.rs @@ -1,5 +1,4 @@ //@ run-pass -#![feature(exclusive_range_pattern)] pub fn main() { match 5_usize { diff --git a/tests/ui/cfg/cfg-in-crate-1.rs b/tests/ui/cfg/cfg-in-crate-1.rs index 07e1c3727f988..4339ce004778b 100644 --- a/tests/ui/cfg/cfg-in-crate-1.rs +++ b/tests/ui/cfg/cfg-in-crate-1.rs @@ -1,5 +1,6 @@ //@ run-pass -//@ compile-flags: --cfg bar -D warnings +//@ compile-flags: --cfg bar --check-cfg=cfg(bar) -D warnings + #![cfg(bar)] fn main() {} diff --git a/tests/ui/cfg/cfg-macros-foo.rs b/tests/ui/cfg/cfg-macros-foo.rs index 7cdf2df5c8f61..4f6ec583db219 100644 --- a/tests/ui/cfg/cfg-macros-foo.rs +++ b/tests/ui/cfg/cfg-macros-foo.rs @@ -1,5 +1,5 @@ //@ run-pass -//@ compile-flags: --cfg foo +//@ compile-flags: --cfg foo --check-cfg=cfg(foo) // check that cfg correctly chooses between the macro impls (see also // cfg-macros-notfoo.rs) diff --git a/tests/ui/cfg/cfg-path-error.rs b/tests/ui/cfg/cfg-path-error.rs index 1e52922d0793f..9db1f190bdc06 100644 --- a/tests/ui/cfg/cfg-path-error.rs +++ b/tests/ui/cfg/cfg-path-error.rs @@ -1,5 +1,7 @@ //@ check-fail +#![allow(unexpected_cfgs)] // invalid cfgs + #[cfg(any(foo, foo::bar))] //~^ERROR `cfg` predicate key must be an identifier fn foo1() {} diff --git a/tests/ui/cfg/cfg-path-error.stderr b/tests/ui/cfg/cfg-path-error.stderr index 84b44b2b0c24a..4f68fa32a9ac2 100644 --- a/tests/ui/cfg/cfg-path-error.stderr +++ b/tests/ui/cfg/cfg-path-error.stderr @@ -1,23 +1,23 @@ error: `cfg` predicate key must be an identifier - --> $DIR/cfg-path-error.rs:3:16 + --> $DIR/cfg-path-error.rs:5:16 | LL | #[cfg(any(foo, foo::bar))] | ^^^^^^^^ error: `cfg` predicate key must be an identifier - --> $DIR/cfg-path-error.rs:7:11 + --> $DIR/cfg-path-error.rs:9:11 | LL | #[cfg(any(foo::bar, foo))] | ^^^^^^^^ error: `cfg` predicate key must be an identifier - --> $DIR/cfg-path-error.rs:11:16 + --> $DIR/cfg-path-error.rs:13:16 | LL | #[cfg(all(foo, foo::bar))] | ^^^^^^^^ error: `cfg` predicate key must be an identifier - --> $DIR/cfg-path-error.rs:15:11 + --> $DIR/cfg-path-error.rs:17:11 | LL | #[cfg(all(foo::bar, foo))] | ^^^^^^^^ diff --git a/tests/ui/cfg/cfg_attr.rs b/tests/ui/cfg/cfg_attr.rs index 4bd024ef5f40c..ba4adafd3a568 100644 --- a/tests/ui/cfg/cfg_attr.rs +++ b/tests/ui/cfg/cfg_attr.rs @@ -1,6 +1,8 @@ //@ run-pass //@ compile-flags:--cfg set1 --cfg set2 -#![allow(dead_code)] + +#![allow(dead_code, unexpected_cfgs)] + use std::fmt::Debug; struct NotDebugable; diff --git a/tests/ui/cfg/cfgs-on-items.rs b/tests/ui/cfg/cfgs-on-items.rs index b3b38cfadb553..8992a8fca9c38 100644 --- a/tests/ui/cfg/cfgs-on-items.rs +++ b/tests/ui/cfg/cfgs-on-items.rs @@ -1,8 +1,7 @@ //@ run-pass -//@ compile-flags: --cfg fooA --cfg fooB +//@ compile-flags: --cfg fooA --cfg fooB --check-cfg=cfg(fooA,fooB,fooC,bar) // fooA AND !bar - #[cfg(all(fooA, not(bar)))] fn foo1() -> isize { 1 } diff --git a/tests/ui/cfg/diagnostics-not-a-def.rs b/tests/ui/cfg/diagnostics-not-a-def.rs index 7293947122675..1912cf9f61665 100644 --- a/tests/ui/cfg/diagnostics-not-a-def.rs +++ b/tests/ui/cfg/diagnostics-not-a-def.rs @@ -1,4 +1,7 @@ +#![feature(lint_reasons)] + pub mod inner { + #[expect(unexpected_cfgs)] pub fn i_am_here() { #[cfg(feature = "another one that doesn't exist")] loop {} diff --git a/tests/ui/cfg/diagnostics-not-a-def.stderr b/tests/ui/cfg/diagnostics-not-a-def.stderr index 6941f850e5f70..89bbf574871b8 100644 --- a/tests/ui/cfg/diagnostics-not-a-def.stderr +++ b/tests/ui/cfg/diagnostics-not-a-def.stderr @@ -1,5 +1,5 @@ error[E0425]: cannot find function `i_am_not` in module `inner` - --> $DIR/diagnostics-not-a-def.rs:11:12 + --> $DIR/diagnostics-not-a-def.rs:14:12 | LL | inner::i_am_not(); | ^^^^^^^^ not found in `inner` diff --git a/tests/ui/cfg/diagnostics-same-crate.rs b/tests/ui/cfg/diagnostics-same-crate.rs index d9ff8d61e9243..b2a0fb58dd6b5 100644 --- a/tests/ui/cfg/diagnostics-same-crate.rs +++ b/tests/ui/cfg/diagnostics-same-crate.rs @@ -1,3 +1,5 @@ +#![allow(unexpected_cfgs)] // since we want to recognize them as unexpected + pub mod inner { #[cfg(FALSE)] pub fn uwu() {} diff --git a/tests/ui/cfg/diagnostics-same-crate.stderr b/tests/ui/cfg/diagnostics-same-crate.stderr index 83a44587238a5..86421736b8c60 100644 --- a/tests/ui/cfg/diagnostics-same-crate.stderr +++ b/tests/ui/cfg/diagnostics-same-crate.stderr @@ -1,72 +1,72 @@ error[E0432]: unresolved import `super::inner::doesnt_exist` - --> $DIR/diagnostics-same-crate.rs:28:9 + --> $DIR/diagnostics-same-crate.rs:30:9 | LL | use super::inner::doesnt_exist; | ^^^^^^^^^^^^^^^^^^^^^^^^^^ no `doesnt_exist` in `inner` | note: found an item that was configured out - --> $DIR/diagnostics-same-crate.rs:7:13 + --> $DIR/diagnostics-same-crate.rs:9:13 | LL | pub mod doesnt_exist { | ^^^^^^^^^^^^ error[E0432]: unresolved import `super::inner::doesnt_exist` - --> $DIR/diagnostics-same-crate.rs:31:23 + --> $DIR/diagnostics-same-crate.rs:33:23 | LL | use super::inner::doesnt_exist::hi; | ^^^^^^^^^^^^ could not find `doesnt_exist` in `inner` | note: found an item that was configured out - --> $DIR/diagnostics-same-crate.rs:7:13 + --> $DIR/diagnostics-same-crate.rs:9:13 | LL | pub mod doesnt_exist { | ^^^^^^^^^^^^ error[E0433]: failed to resolve: could not find `doesnt_exist` in `inner` - --> $DIR/diagnostics-same-crate.rs:50:12 + --> $DIR/diagnostics-same-crate.rs:52:12 | LL | inner::doesnt_exist::hello(); | ^^^^^^^^^^^^ could not find `doesnt_exist` in `inner` | note: found an item that was configured out - --> $DIR/diagnostics-same-crate.rs:7:13 + --> $DIR/diagnostics-same-crate.rs:9:13 | LL | pub mod doesnt_exist { | ^^^^^^^^^^^^ error[E0425]: cannot find function `uwu` in module `inner` - --> $DIR/diagnostics-same-crate.rs:45:12 + --> $DIR/diagnostics-same-crate.rs:47:12 | LL | inner::uwu(); | ^^^ not found in `inner` | note: found an item that was configured out - --> $DIR/diagnostics-same-crate.rs:3:12 + --> $DIR/diagnostics-same-crate.rs:5:12 | LL | pub fn uwu() {} | ^^^ error[E0425]: cannot find function `meow` in module `inner::right` - --> $DIR/diagnostics-same-crate.rs:54:19 + --> $DIR/diagnostics-same-crate.rs:56:19 | LL | inner::right::meow(); | ^^^^ not found in `inner::right` | note: found an item that was configured out - --> $DIR/diagnostics-same-crate.rs:22:16 + --> $DIR/diagnostics-same-crate.rs:24:16 | LL | pub fn meow() {} | ^^^^ = note: the item is gated behind the `what-a-cool-feature` feature error[E0425]: cannot find function `uwu` in this scope - --> $DIR/diagnostics-same-crate.rs:41:5 + --> $DIR/diagnostics-same-crate.rs:43:5 | LL | uwu(); | ^^^ not found in this scope error[E0425]: cannot find function `vanished` in this scope - --> $DIR/diagnostics-same-crate.rs:61:5 + --> $DIR/diagnostics-same-crate.rs:63:5 | LL | vanished(); | ^^^^^^^^ not found in this scope diff --git a/tests/ui/cfg/expanded-cfg.rs b/tests/ui/cfg/expanded-cfg.rs index 75860146e745f..ecafa40cadc9e 100644 --- a/tests/ui/cfg/expanded-cfg.rs +++ b/tests/ui/cfg/expanded-cfg.rs @@ -1,5 +1,7 @@ //@ check-pass +#![allow(unexpected_cfgs)] // since we different cfgs + macro_rules! mac { {} => { #[cfg(attr)] diff --git a/tests/ui/cfg/future-compat-crate-attributes-using-cfg_attr.rs b/tests/ui/cfg/future-compat-crate-attributes-using-cfg_attr.rs index 96e326e02ad44..3ced3a630e334 100644 --- a/tests/ui/cfg/future-compat-crate-attributes-using-cfg_attr.rs +++ b/tests/ui/cfg/future-compat-crate-attributes-using-cfg_attr.rs @@ -1,5 +1,5 @@ //@ check-fail -//@ compile-flags:--cfg foo +//@ compile-flags:--cfg foo --check-cfg=cfg(foo) #![cfg_attr(foo, crate_type="bin")] //~^ERROR `crate_type` within diff --git a/tests/ui/check-cfg/allow-at-crate-level.rs b/tests/ui/check-cfg/allow-at-crate-level.rs index 03b4676ad5f10..9dc2416a3a938 100644 --- a/tests/ui/check-cfg/allow-at-crate-level.rs +++ b/tests/ui/check-cfg/allow-at-crate-level.rs @@ -1,6 +1,7 @@ // This test check that #![allow(unexpected_cfgs)] works with --cfg // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --cfg=unexpected --check-cfg=cfg() #![allow(unexpected_cfgs)] diff --git a/tests/ui/check-cfg/allow-macro-cfg.rs b/tests/ui/check-cfg/allow-macro-cfg.rs index 3db6e18d77a8d..b3c706d6d2b74 100644 --- a/tests/ui/check-cfg/allow-macro-cfg.rs +++ b/tests/ui/check-cfg/allow-macro-cfg.rs @@ -1,6 +1,7 @@ // This test check that local #[allow(unexpected_cfgs)] works // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg() #[allow(unexpected_cfgs)] diff --git a/tests/ui/check-cfg/allow-same-level.rs b/tests/ui/check-cfg/allow-same-level.rs index e932ece6ee771..ff724174cea54 100644 --- a/tests/ui/check-cfg/allow-same-level.rs +++ b/tests/ui/check-cfg/allow-same-level.rs @@ -1,6 +1,7 @@ // This test check that #[allow(unexpected_cfgs)] doesn't work if put on the same level // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg() #[allow(unexpected_cfgs)] diff --git a/tests/ui/check-cfg/allow-same-level.stderr b/tests/ui/check-cfg/allow-same-level.stderr index 349f41cb142c8..ae4c1605f0162 100644 --- a/tests/ui/check-cfg/allow-same-level.stderr +++ b/tests/ui/check-cfg/allow-same-level.stderr @@ -1,10 +1,10 @@ warning: unexpected `cfg` condition name: `FALSE` - --> $DIR/allow-same-level.rs:7:7 + --> $DIR/allow-same-level.rs:8:7 | LL | #[cfg(FALSE)] | ^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(FALSE)` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/allow-top-level.rs b/tests/ui/check-cfg/allow-top-level.rs index 0f88543d8478d..cf94ed5da428f 100644 --- a/tests/ui/check-cfg/allow-top-level.rs +++ b/tests/ui/check-cfg/allow-top-level.rs @@ -1,6 +1,7 @@ // This test check that a top-level #![allow(unexpected_cfgs)] works // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg() #![allow(unexpected_cfgs)] diff --git a/tests/ui/check-cfg/allow-upper-level.rs b/tests/ui/check-cfg/allow-upper-level.rs index d03d0cab37b7d..2e6664c30d395 100644 --- a/tests/ui/check-cfg/allow-upper-level.rs +++ b/tests/ui/check-cfg/allow-upper-level.rs @@ -1,6 +1,7 @@ // This test check that #[allow(unexpected_cfgs)] work if put on an upper level // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg() #[allow(unexpected_cfgs)] diff --git a/tests/ui/check-cfg/cargo-feature.none.stderr b/tests/ui/check-cfg/cargo-feature.none.stderr index 0b914c2bc3559..627f03ddf5526 100644 --- a/tests/ui/check-cfg/cargo-feature.none.stderr +++ b/tests/ui/check-cfg/cargo-feature.none.stderr @@ -1,42 +1,42 @@ warning: unexpected `cfg` condition value: `serde` - --> $DIR/cargo-feature.rs:13:7 + --> $DIR/cargo-feature.rs:14:7 | LL | #[cfg(feature = "serde")] | ^^^^^^^^^^^^^^^^^ help: remove the condition | = note: no expected values for `feature` = help: consider adding `serde` as a feature in `Cargo.toml` - = note: see for more information about checking conditional configuration + = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: (none) - --> $DIR/cargo-feature.rs:17:7 + --> $DIR/cargo-feature.rs:18:7 | LL | #[cfg(feature)] | ^^^^^^^ help: remove the condition | = note: no expected values for `feature` = help: consider defining some features in `Cargo.toml` - = note: see for more information about checking conditional configuration + = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `tokio_unstable` - --> $DIR/cargo-feature.rs:21:7 + --> $DIR/cargo-feature.rs:22:7 | LL | #[cfg(tokio_unstable)] | ^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` - = help: consider using a Cargo feature instead or adding `println!("cargo:rustc-check-cfg=cfg(tokio_unstable)");` to the top of a `build.rs` - = note: see for more information about checking conditional configuration + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: consider using a Cargo feature instead or adding `println!("cargo::rustc-check-cfg=cfg(tokio_unstable)");` to the top of the `build.rs` + = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `CONFIG_NVME` - --> $DIR/cargo-feature.rs:25:7 + --> $DIR/cargo-feature.rs:26:7 | LL | #[cfg(CONFIG_NVME = "m")] | ^^^^^^^^^^^^^^^^^ | - = help: consider using a Cargo feature instead or adding `println!("cargo:rustc-check-cfg=cfg(CONFIG_NVME, values(\"m\"))");` to the top of a `build.rs` - = note: see for more information about checking conditional configuration + = help: consider using a Cargo feature instead or adding `println!("cargo::rustc-check-cfg=cfg(CONFIG_NVME, values(\"m\"))");` to the top of the `build.rs` + = note: see for more information about checking conditional configuration warning: 4 warnings emitted diff --git a/tests/ui/check-cfg/cargo-feature.rs b/tests/ui/check-cfg/cargo-feature.rs index ced0d381d2df0..13faf7f28200d 100644 --- a/tests/ui/check-cfg/cargo-feature.rs +++ b/tests/ui/check-cfg/cargo-feature.rs @@ -3,6 +3,7 @@ // list of all the expected names // //@ check-pass +//@ no-auto-check-cfg //@ revisions: some none //@ rustc-env:CARGO_CRATE_NAME=foo //@ [none]compile-flags: --check-cfg=cfg(feature,values()) diff --git a/tests/ui/check-cfg/cargo-feature.some.stderr b/tests/ui/check-cfg/cargo-feature.some.stderr index 1a4ef89efc1a6..9cc5fb6aca03d 100644 --- a/tests/ui/check-cfg/cargo-feature.some.stderr +++ b/tests/ui/check-cfg/cargo-feature.some.stderr @@ -1,36 +1,36 @@ warning: unexpected `cfg` condition value: `serde` - --> $DIR/cargo-feature.rs:13:7 + --> $DIR/cargo-feature.rs:14:7 | LL | #[cfg(feature = "serde")] | ^^^^^^^^^^^^^^^^^ | = note: expected values for `feature` are: `bitcode` = help: consider adding `serde` as a feature in `Cargo.toml` - = note: see for more information about checking conditional configuration + = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: (none) - --> $DIR/cargo-feature.rs:17:7 + --> $DIR/cargo-feature.rs:18:7 | LL | #[cfg(feature)] | ^^^^^^^- help: specify a config value: `= "bitcode"` | = note: expected values for `feature` are: `bitcode` = help: consider defining some features in `Cargo.toml` - = note: see for more information about checking conditional configuration + = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `tokio_unstable` - --> $DIR/cargo-feature.rs:21:7 + --> $DIR/cargo-feature.rs:22:7 | LL | #[cfg(tokio_unstable)] | ^^^^^^^^^^^^^^ | - = help: expected names are: `CONFIG_NVME`, `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` - = help: consider using a Cargo feature instead or adding `println!("cargo:rustc-check-cfg=cfg(tokio_unstable)");` to the top of a `build.rs` - = note: see for more information about checking conditional configuration + = help: expected names are: `CONFIG_NVME`, `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: consider using a Cargo feature instead or adding `println!("cargo::rustc-check-cfg=cfg(tokio_unstable)");` to the top of the `build.rs` + = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `m` - --> $DIR/cargo-feature.rs:25:7 + --> $DIR/cargo-feature.rs:26:7 | LL | #[cfg(CONFIG_NVME = "m")] | ^^^^^^^^^^^^^^--- @@ -38,8 +38,8 @@ LL | #[cfg(CONFIG_NVME = "m")] | help: there is a expected value with a similar name: `"y"` | = note: expected values for `CONFIG_NVME` are: `y` - = help: consider using a Cargo feature instead or adding `println!("cargo:rustc-check-cfg=cfg(CONFIG_NVME, values(\"m\"))");` to the top of a `build.rs` - = note: see for more information about checking conditional configuration + = help: consider using a Cargo feature instead or adding `println!("cargo::rustc-check-cfg=cfg(CONFIG_NVME, values(\"m\"))");` to the top of the `build.rs` + = note: see for more information about checking conditional configuration warning: 4 warnings emitted diff --git a/tests/ui/check-cfg/cfg-value-for-cfg-name-duplicate.rs b/tests/ui/check-cfg/cfg-value-for-cfg-name-duplicate.rs index 79d4e45c13b47..dd82ccd2c5125 100644 --- a/tests/ui/check-cfg/cfg-value-for-cfg-name-duplicate.rs +++ b/tests/ui/check-cfg/cfg-value-for-cfg-name-duplicate.rs @@ -2,6 +2,7 @@ // This test checks we won't suggest more than 3 span suggestions for cfg names // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg(foo,values("value")) --check-cfg=cfg(bar,values("value")) --check-cfg=cfg(bee,values("value")) --check-cfg=cfg(cow,values("value")) #[cfg(value)] diff --git a/tests/ui/check-cfg/cfg-value-for-cfg-name-duplicate.stderr b/tests/ui/check-cfg/cfg-value-for-cfg-name-duplicate.stderr index 23ae4c55e42be..4975129802b69 100644 --- a/tests/ui/check-cfg/cfg-value-for-cfg-name-duplicate.stderr +++ b/tests/ui/check-cfg/cfg-value-for-cfg-name-duplicate.stderr @@ -1,10 +1,10 @@ warning: unexpected `cfg` condition name: `value` - --> $DIR/cfg-value-for-cfg-name-duplicate.rs:7:7 + --> $DIR/cfg-value-for-cfg-name-duplicate.rs:8:7 | LL | #[cfg(value)] | ^^^^^ | - = help: expected names are: `bar`, `bee`, `clippy`, `cow`, `debug_assertions`, `doc`, `doctest`, `foo`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: expected names are: `bar`, `bee`, `clippy`, `cow`, `debug_assertions`, `doc`, `doctest`, `foo`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(value)` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/cfg-value-for-cfg-name-multiple.rs b/tests/ui/check-cfg/cfg-value-for-cfg-name-multiple.rs index f2fd050bb75ac..3a94b6a607238 100644 --- a/tests/ui/check-cfg/cfg-value-for-cfg-name-multiple.rs +++ b/tests/ui/check-cfg/cfg-value-for-cfg-name-multiple.rs @@ -2,6 +2,7 @@ // This test checks that when a single cfg has a value for user's specified name // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg(foo,values("my_value")) --check-cfg=cfg(bar,values("my_value")) #[cfg(my_value)] diff --git a/tests/ui/check-cfg/cfg-value-for-cfg-name-multiple.stderr b/tests/ui/check-cfg/cfg-value-for-cfg-name-multiple.stderr index b5faaf6029c49..6404556f46c4b 100644 --- a/tests/ui/check-cfg/cfg-value-for-cfg-name-multiple.stderr +++ b/tests/ui/check-cfg/cfg-value-for-cfg-name-multiple.stderr @@ -1,10 +1,10 @@ warning: unexpected `cfg` condition name: `my_value` - --> $DIR/cfg-value-for-cfg-name-multiple.rs:7:7 + --> $DIR/cfg-value-for-cfg-name-multiple.rs:8:7 | LL | #[cfg(my_value)] | ^^^^^^^^ | - = help: expected names are: `bar`, `clippy`, `debug_assertions`, `doc`, `doctest`, `foo`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: expected names are: `bar`, `clippy`, `debug_assertions`, `doc`, `doctest`, `foo`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(my_value)` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/cfg-value-for-cfg-name.rs b/tests/ui/check-cfg/cfg-value-for-cfg-name.rs index e8f9095655b53..50f2fbab60365 100644 --- a/tests/ui/check-cfg/cfg-value-for-cfg-name.rs +++ b/tests/ui/check-cfg/cfg-value-for-cfg-name.rs @@ -3,6 +3,7 @@ // suggest to use `#[cfg(target_os = "linux")]` instead of `#[cfg(linux)]` // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg() #[cfg(linux)] diff --git a/tests/ui/check-cfg/cfg-value-for-cfg-name.stderr b/tests/ui/check-cfg/cfg-value-for-cfg-name.stderr index 01586a6c71d2d..bda1a601410e6 100644 --- a/tests/ui/check-cfg/cfg-value-for-cfg-name.stderr +++ b/tests/ui/check-cfg/cfg-value-for-cfg-name.stderr @@ -1,16 +1,16 @@ warning: unexpected `cfg` condition name: `linux` - --> $DIR/cfg-value-for-cfg-name.rs:8:7 + --> $DIR/cfg-value-for-cfg-name.rs:9:7 | LL | #[cfg(linux)] | ^^^^^ help: found config with similar value: `target_os = "linux"` | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(linux)` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition name: `linux` - --> $DIR/cfg-value-for-cfg-name.rs:13:7 + --> $DIR/cfg-value-for-cfg-name.rs:14:7 | LL | #[cfg(linux = "os-name")] | ^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/check-cfg/compact-names.rs b/tests/ui/check-cfg/compact-names.rs index ddbd20b99b28e..931afdf986f4f 100644 --- a/tests/ui/check-cfg/compact-names.rs +++ b/tests/ui/check-cfg/compact-names.rs @@ -1,6 +1,7 @@ // This test check that we correctly emit an warning for compact cfg // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg() #![feature(cfg_target_compact)] diff --git a/tests/ui/check-cfg/compact-names.stderr b/tests/ui/check-cfg/compact-names.stderr index 929501b420a7b..079be8d08c29b 100644 --- a/tests/ui/check-cfg/compact-names.stderr +++ b/tests/ui/check-cfg/compact-names.stderr @@ -1,10 +1,10 @@ warning: unexpected `cfg` condition name: `target_architecture` - --> $DIR/compact-names.rs:11:28 + --> $DIR/compact-names.rs:12:28 | LL | #[cfg(target(os = "linux", architecture = "arm"))] | ^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(target_architecture, values("arm"))` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/compact-values.rs b/tests/ui/check-cfg/compact-values.rs index bda4686ebd742..f13c23f689572 100644 --- a/tests/ui/check-cfg/compact-values.rs +++ b/tests/ui/check-cfg/compact-values.rs @@ -1,6 +1,7 @@ // This test check that we correctly emit an warning for compact cfg // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg() #![feature(cfg_target_compact)] diff --git a/tests/ui/check-cfg/compact-values.stderr b/tests/ui/check-cfg/compact-values.stderr index 45d084c46bfa9..4fe921dd24b20 100644 --- a/tests/ui/check-cfg/compact-values.stderr +++ b/tests/ui/check-cfg/compact-values.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `X` - --> $DIR/compact-values.rs:11:28 + --> $DIR/compact-values.rs:12:28 | LL | #[cfg(target(os = "linux", pointer_width = "X"))] | ^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/check-cfg/concat-values.rs b/tests/ui/check-cfg/concat-values.rs index c546590a2c1ff..6cbc5d6074cfb 100644 --- a/tests/ui/check-cfg/concat-values.rs +++ b/tests/ui/check-cfg/concat-values.rs @@ -1,4 +1,5 @@ //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg(my_cfg,values("foo")) --check-cfg=cfg(my_cfg,values("bar")) //@ compile-flags: --check-cfg=cfg(my_cfg,values()) diff --git a/tests/ui/check-cfg/concat-values.stderr b/tests/ui/check-cfg/concat-values.stderr index ca8b58f73e5f3..a508c3976617d 100644 --- a/tests/ui/check-cfg/concat-values.stderr +++ b/tests/ui/check-cfg/concat-values.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: (none) - --> $DIR/concat-values.rs:5:7 + --> $DIR/concat-values.rs:6:7 | LL | #[cfg(my_cfg)] | ^^^^^^ @@ -10,7 +10,7 @@ LL | #[cfg(my_cfg)] = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `unk` - --> $DIR/concat-values.rs:9:7 + --> $DIR/concat-values.rs:10:7 | LL | #[cfg(my_cfg = "unk")] | ^^^^^^^^^^^^^^ diff --git a/tests/ui/check-cfg/diagnotics.cargo.stderr b/tests/ui/check-cfg/diagnotics.cargo.stderr index 05c52bf59fad6..1b7505682da36 100644 --- a/tests/ui/check-cfg/diagnotics.cargo.stderr +++ b/tests/ui/check-cfg/diagnotics.cargo.stderr @@ -1,62 +1,62 @@ warning: unexpected `cfg` condition name: `featur` - --> $DIR/diagnotics.rs:7:7 + --> $DIR/diagnotics.rs:8:7 | LL | #[cfg(featur)] | ^^^^^^ help: there is a config with a similar name: `feature` | = help: expected values for `feature` are: `foo` - = note: see for more information about checking conditional configuration + = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition name: `featur` - --> $DIR/diagnotics.rs:11:7 + --> $DIR/diagnotics.rs:12:7 | LL | #[cfg(featur = "foo")] | ^^^^^^^^^^^^^^ | - = note: see for more information about checking conditional configuration + = note: see for more information about checking conditional configuration help: there is a config with a similar name and value | LL | #[cfg(feature = "foo")] | ~~~~~~~ warning: unexpected `cfg` condition name: `featur` - --> $DIR/diagnotics.rs:15:7 + --> $DIR/diagnotics.rs:16:7 | LL | #[cfg(featur = "fo")] | ^^^^^^^^^^^^^ | = help: expected values for `feature` are: `foo` - = note: see for more information about checking conditional configuration + = note: see for more information about checking conditional configuration help: there is a config with a similar name and different values | LL | #[cfg(feature = "foo")] | ~~~~~~~~~~~~~~~ warning: unexpected `cfg` condition name: `no_value` - --> $DIR/diagnotics.rs:22:7 + --> $DIR/diagnotics.rs:23:7 | LL | #[cfg(no_value)] | ^^^^^^^^ help: there is a config with a similar name: `no_values` | - = help: consider using a Cargo feature instead or adding `println!("cargo:rustc-check-cfg=cfg(no_value)");` to the top of a `build.rs` - = note: see for more information about checking conditional configuration + = help: consider using a Cargo feature instead or adding `println!("cargo::rustc-check-cfg=cfg(no_value)");` to the top of the `build.rs` + = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `no_value` - --> $DIR/diagnotics.rs:26:7 + --> $DIR/diagnotics.rs:27:7 | LL | #[cfg(no_value = "foo")] | ^^^^^^^^^^^^^^^^ | - = help: consider using a Cargo feature instead or adding `println!("cargo:rustc-check-cfg=cfg(no_value, values(\"foo\"))");` to the top of a `build.rs` - = note: see for more information about checking conditional configuration + = help: consider using a Cargo feature instead or adding `println!("cargo::rustc-check-cfg=cfg(no_value, values(\"foo\"))");` to the top of the `build.rs` + = note: see for more information about checking conditional configuration help: there is a config with a similar name and no value | LL | #[cfg(no_values)] | ~~~~~~~~~ warning: unexpected `cfg` condition value: `bar` - --> $DIR/diagnotics.rs:30:7 + --> $DIR/diagnotics.rs:31:7 | LL | #[cfg(no_values = "bar")] | ^^^^^^^^^-------- @@ -64,8 +64,8 @@ LL | #[cfg(no_values = "bar")] | help: remove the value | = note: no expected value for `no_values` - = help: consider using a Cargo feature instead or adding `println!("cargo:rustc-check-cfg=cfg(no_values, values(\"bar\"))");` to the top of a `build.rs` - = note: see for more information about checking conditional configuration + = help: consider using a Cargo feature instead or adding `println!("cargo::rustc-check-cfg=cfg(no_values, values(\"bar\"))");` to the top of the `build.rs` + = note: see for more information about checking conditional configuration warning: 6 warnings emitted diff --git a/tests/ui/check-cfg/diagnotics.rs b/tests/ui/check-cfg/diagnotics.rs index cccd6f9bbc3e9..b8268ec560624 100644 --- a/tests/ui/check-cfg/diagnotics.rs +++ b/tests/ui/check-cfg/diagnotics.rs @@ -1,4 +1,5 @@ //@ check-pass +//@ no-auto-check-cfg //@ revisions: cargo rustc //@ [rustc]unset-rustc-env:CARGO_CRATE_NAME //@ [cargo]rustc-env:CARGO_CRATE_NAME=foo diff --git a/tests/ui/check-cfg/diagnotics.rustc.stderr b/tests/ui/check-cfg/diagnotics.rustc.stderr index 0a938d2143e95..0bd6ce156bb6d 100644 --- a/tests/ui/check-cfg/diagnotics.rustc.stderr +++ b/tests/ui/check-cfg/diagnotics.rustc.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition name: `featur` - --> $DIR/diagnotics.rs:7:7 + --> $DIR/diagnotics.rs:8:7 | LL | #[cfg(featur)] | ^^^^^^ help: there is a config with a similar name: `feature` @@ -10,7 +10,7 @@ LL | #[cfg(featur)] = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition name: `featur` - --> $DIR/diagnotics.rs:11:7 + --> $DIR/diagnotics.rs:12:7 | LL | #[cfg(featur = "foo")] | ^^^^^^^^^^^^^^ @@ -23,7 +23,7 @@ LL | #[cfg(feature = "foo")] | ~~~~~~~ warning: unexpected `cfg` condition name: `featur` - --> $DIR/diagnotics.rs:15:7 + --> $DIR/diagnotics.rs:16:7 | LL | #[cfg(featur = "fo")] | ^^^^^^^^^^^^^ @@ -37,7 +37,7 @@ LL | #[cfg(feature = "foo")] | ~~~~~~~~~~~~~~~ warning: unexpected `cfg` condition name: `no_value` - --> $DIR/diagnotics.rs:22:7 + --> $DIR/diagnotics.rs:23:7 | LL | #[cfg(no_value)] | ^^^^^^^^ help: there is a config with a similar name: `no_values` @@ -46,7 +46,7 @@ LL | #[cfg(no_value)] = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `no_value` - --> $DIR/diagnotics.rs:26:7 + --> $DIR/diagnotics.rs:27:7 | LL | #[cfg(no_value = "foo")] | ^^^^^^^^^^^^^^^^ @@ -59,7 +59,7 @@ LL | #[cfg(no_values)] | ~~~~~~~~~ warning: unexpected `cfg` condition value: `bar` - --> $DIR/diagnotics.rs:30:7 + --> $DIR/diagnotics.rs:31:7 | LL | #[cfg(no_values = "bar")] | ^^^^^^^^^-------- diff --git a/tests/ui/check-cfg/empty-values.rs b/tests/ui/check-cfg/empty-values.rs index cad2d351b9620..cf7a7d7d1c034 100644 --- a/tests/ui/check-cfg/empty-values.rs +++ b/tests/ui/check-cfg/empty-values.rs @@ -1,6 +1,7 @@ // Check that we detect unexpected value when none are allowed // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg(foo,values()) #[cfg(foo = "foo")] diff --git a/tests/ui/check-cfg/empty-values.stderr b/tests/ui/check-cfg/empty-values.stderr index 1f773b10316e0..7f57a4ba59344 100644 --- a/tests/ui/check-cfg/empty-values.stderr +++ b/tests/ui/check-cfg/empty-values.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `foo` - --> $DIR/empty-values.rs:6:7 + --> $DIR/empty-values.rs:7:7 | LL | #[cfg(foo = "foo")] | ^^^^^^^^^^^ help: remove the condition @@ -10,7 +10,7 @@ LL | #[cfg(foo = "foo")] = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: (none) - --> $DIR/empty-values.rs:10:7 + --> $DIR/empty-values.rs:11:7 | LL | #[cfg(foo)] | ^^^ help: remove the condition diff --git a/tests/ui/check-cfg/exhaustive-names-values.empty_cfg.stderr b/tests/ui/check-cfg/exhaustive-names-values.empty_cfg.stderr index 9537d4f517291..c196f607376fb 100644 --- a/tests/ui/check-cfg/exhaustive-names-values.empty_cfg.stderr +++ b/tests/ui/check-cfg/exhaustive-names-values.empty_cfg.stderr @@ -1,16 +1,16 @@ warning: unexpected `cfg` condition name: `unknown_key` - --> $DIR/exhaustive-names-values.rs:9:7 + --> $DIR/exhaustive-names-values.rs:10:7 | LL | #[cfg(unknown_key = "value")] | ^^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(unknown_key, values("value"))` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `value` - --> $DIR/exhaustive-names-values.rs:13:7 + --> $DIR/exhaustive-names-values.rs:14:7 | LL | #[cfg(test = "value")] | ^^^^---------- @@ -21,7 +21,7 @@ LL | #[cfg(test = "value")] = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `feature` - --> $DIR/exhaustive-names-values.rs:17:7 + --> $DIR/exhaustive-names-values.rs:18:7 | LL | #[cfg(feature = "unk")] | ^^^^^^^^^^^^^^^ @@ -30,7 +30,7 @@ LL | #[cfg(feature = "unk")] = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `feature` - --> $DIR/exhaustive-names-values.rs:24:7 + --> $DIR/exhaustive-names-values.rs:25:7 | LL | #[cfg(feature = "std")] | ^^^^^^^^^^^^^^^ diff --git a/tests/ui/check-cfg/exhaustive-names-values.feature.stderr b/tests/ui/check-cfg/exhaustive-names-values.feature.stderr index d63d862795349..6344739ae7670 100644 --- a/tests/ui/check-cfg/exhaustive-names-values.feature.stderr +++ b/tests/ui/check-cfg/exhaustive-names-values.feature.stderr @@ -1,16 +1,16 @@ warning: unexpected `cfg` condition name: `unknown_key` - --> $DIR/exhaustive-names-values.rs:9:7 + --> $DIR/exhaustive-names-values.rs:10:7 | LL | #[cfg(unknown_key = "value")] | ^^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(unknown_key, values("value"))` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `value` - --> $DIR/exhaustive-names-values.rs:13:7 + --> $DIR/exhaustive-names-values.rs:14:7 | LL | #[cfg(test = "value")] | ^^^^---------- @@ -21,7 +21,7 @@ LL | #[cfg(test = "value")] = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `unk` - --> $DIR/exhaustive-names-values.rs:17:7 + --> $DIR/exhaustive-names-values.rs:18:7 | LL | #[cfg(feature = "unk")] | ^^^^^^^^^^^^^^^ diff --git a/tests/ui/check-cfg/exhaustive-names-values.full.stderr b/tests/ui/check-cfg/exhaustive-names-values.full.stderr index d63d862795349..6344739ae7670 100644 --- a/tests/ui/check-cfg/exhaustive-names-values.full.stderr +++ b/tests/ui/check-cfg/exhaustive-names-values.full.stderr @@ -1,16 +1,16 @@ warning: unexpected `cfg` condition name: `unknown_key` - --> $DIR/exhaustive-names-values.rs:9:7 + --> $DIR/exhaustive-names-values.rs:10:7 | LL | #[cfg(unknown_key = "value")] | ^^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(unknown_key, values("value"))` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `value` - --> $DIR/exhaustive-names-values.rs:13:7 + --> $DIR/exhaustive-names-values.rs:14:7 | LL | #[cfg(test = "value")] | ^^^^---------- @@ -21,7 +21,7 @@ LL | #[cfg(test = "value")] = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `unk` - --> $DIR/exhaustive-names-values.rs:17:7 + --> $DIR/exhaustive-names-values.rs:18:7 | LL | #[cfg(feature = "unk")] | ^^^^^^^^^^^^^^^ diff --git a/tests/ui/check-cfg/exhaustive-names-values.rs b/tests/ui/check-cfg/exhaustive-names-values.rs index f6c3e1f575adf..a6190f15dbb4b 100644 --- a/tests/ui/check-cfg/exhaustive-names-values.rs +++ b/tests/ui/check-cfg/exhaustive-names-values.rs @@ -1,6 +1,7 @@ // Check warning for unexpected cfg in the code. // //@ check-pass +//@ no-auto-check-cfg //@ revisions: empty_cfg feature full //@ [empty_cfg]compile-flags: --check-cfg=cfg() //@ [feature]compile-flags: --check-cfg=cfg(feature,values("std")) diff --git a/tests/ui/check-cfg/exhaustive-names.rs b/tests/ui/check-cfg/exhaustive-names.rs index 23bde4dff5505..5d77cc10ca4d3 100644 --- a/tests/ui/check-cfg/exhaustive-names.rs +++ b/tests/ui/check-cfg/exhaustive-names.rs @@ -1,6 +1,7 @@ // Check warning for unexpected cfg // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg() #[cfg(unknown_key = "value")] diff --git a/tests/ui/check-cfg/exhaustive-names.stderr b/tests/ui/check-cfg/exhaustive-names.stderr index c42adec94b2bf..605825cd4e584 100644 --- a/tests/ui/check-cfg/exhaustive-names.stderr +++ b/tests/ui/check-cfg/exhaustive-names.stderr @@ -1,10 +1,10 @@ warning: unexpected `cfg` condition name: `unknown_key` - --> $DIR/exhaustive-names.rs:6:7 + --> $DIR/exhaustive-names.rs:7:7 | LL | #[cfg(unknown_key = "value")] | ^^^^^^^^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(unknown_key, values("value"))` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/exhaustive-values.empty_cfg.stderr b/tests/ui/check-cfg/exhaustive-values.empty_cfg.stderr index 63ba2c686254c..a3c0f36aee8b3 100644 --- a/tests/ui/check-cfg/exhaustive-values.empty_cfg.stderr +++ b/tests/ui/check-cfg/exhaustive-values.empty_cfg.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `value` - --> $DIR/exhaustive-values.rs:8:7 + --> $DIR/exhaustive-values.rs:9:7 | LL | #[cfg(test = "value")] | ^^^^---------- diff --git a/tests/ui/check-cfg/exhaustive-values.rs b/tests/ui/check-cfg/exhaustive-values.rs index 029b2ff2c6914..b4ce2ac98dc05 100644 --- a/tests/ui/check-cfg/exhaustive-values.rs +++ b/tests/ui/check-cfg/exhaustive-values.rs @@ -1,6 +1,7 @@ // Check warning for unexpected cfg value // //@ check-pass +//@ no-auto-check-cfg //@ revisions: empty_cfg without_names //@ [empty_cfg]compile-flags: --check-cfg=cfg() //@ [without_names]compile-flags: --check-cfg=cfg(any()) diff --git a/tests/ui/check-cfg/exhaustive-values.without_names.stderr b/tests/ui/check-cfg/exhaustive-values.without_names.stderr index 63ba2c686254c..a3c0f36aee8b3 100644 --- a/tests/ui/check-cfg/exhaustive-values.without_names.stderr +++ b/tests/ui/check-cfg/exhaustive-values.without_names.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `value` - --> $DIR/exhaustive-values.rs:8:7 + --> $DIR/exhaustive-values.rs:9:7 | LL | #[cfg(test = "value")] | ^^^^---------- diff --git a/tests/ui/check-cfg/invalid-arguments.rs b/tests/ui/check-cfg/invalid-arguments.rs index 84087a16e80eb..c0b58ede97f40 100644 --- a/tests/ui/check-cfg/invalid-arguments.rs +++ b/tests/ui/check-cfg/invalid-arguments.rs @@ -1,6 +1,7 @@ // Check that invalid --check-cfg are rejected // //@ check-fail +//@ no-auto-check-cfg //@ revisions: anything_else //@ revisions: string_for_name_1 string_for_name_2 multiple_any multiple_values //@ revisions: multiple_values_any not_empty_any not_empty_values_any diff --git a/tests/ui/check-cfg/mix.rs b/tests/ui/check-cfg/mix.rs index ab8a180bc6f41..ac244f4fc09df 100644 --- a/tests/ui/check-cfg/mix.rs +++ b/tests/ui/check-cfg/mix.rs @@ -3,6 +3,7 @@ // we correctly lint on the `cfg!` macro and `cfg_attr` attribute. // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --cfg feature="bar" --cfg unknown_name //@ compile-flags: --check-cfg=cfg(feature,values("foo")) diff --git a/tests/ui/check-cfg/mix.stderr b/tests/ui/check-cfg/mix.stderr index 557fdcbf38dbe..5459169914530 100644 --- a/tests/ui/check-cfg/mix.stderr +++ b/tests/ui/check-cfg/mix.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition name: `widnows` - --> $DIR/mix.rs:12:7 + --> $DIR/mix.rs:13:7 | LL | #[cfg(widnows)] | ^^^^^^^ help: there is a config with a similar name: `windows` @@ -9,7 +9,7 @@ LL | #[cfg(widnows)] = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: (none) - --> $DIR/mix.rs:16:7 + --> $DIR/mix.rs:17:7 | LL | #[cfg(feature)] | ^^^^^^^- help: specify a config value: `= "foo"` @@ -19,7 +19,7 @@ LL | #[cfg(feature)] = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `bar` - --> $DIR/mix.rs:23:7 + --> $DIR/mix.rs:24:7 | LL | #[cfg(feature = "bar")] | ^^^^^^^^^^^^^^^ @@ -29,7 +29,7 @@ LL | #[cfg(feature = "bar")] = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `zebra` - --> $DIR/mix.rs:27:7 + --> $DIR/mix.rs:28:7 | LL | #[cfg(feature = "zebra")] | ^^^^^^^^^^^^^^^^^ @@ -39,17 +39,17 @@ LL | #[cfg(feature = "zebra")] = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `uu` - --> $DIR/mix.rs:31:12 + --> $DIR/mix.rs:32:12 | LL | #[cfg_attr(uu, test)] | ^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `feature`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(uu)` = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `widnows` - --> $DIR/mix.rs:40:10 + --> $DIR/mix.rs:41:10 | LL | cfg!(widnows); | ^^^^^^^ help: there is a config with a similar name: `windows` @@ -58,7 +58,7 @@ LL | cfg!(widnows); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `bar` - --> $DIR/mix.rs:43:10 + --> $DIR/mix.rs:44:10 | LL | cfg!(feature = "bar"); | ^^^^^^^^^^^^^^^ @@ -68,7 +68,7 @@ LL | cfg!(feature = "bar"); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `zebra` - --> $DIR/mix.rs:45:10 + --> $DIR/mix.rs:46:10 | LL | cfg!(feature = "zebra"); | ^^^^^^^^^^^^^^^^^ @@ -78,7 +78,7 @@ LL | cfg!(feature = "zebra"); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `xxx` - --> $DIR/mix.rs:47:10 + --> $DIR/mix.rs:48:10 | LL | cfg!(xxx = "foo"); | ^^^^^^^^^^^ @@ -87,7 +87,7 @@ LL | cfg!(xxx = "foo"); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `xxx` - --> $DIR/mix.rs:49:10 + --> $DIR/mix.rs:50:10 | LL | cfg!(xxx); | ^^^ @@ -96,7 +96,7 @@ LL | cfg!(xxx); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `xxx` - --> $DIR/mix.rs:51:14 + --> $DIR/mix.rs:52:14 | LL | cfg!(any(xxx, windows)); | ^^^ @@ -105,7 +105,7 @@ LL | cfg!(any(xxx, windows)); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `bad` - --> $DIR/mix.rs:53:14 + --> $DIR/mix.rs:54:14 | LL | cfg!(any(feature = "bad", windows)); | ^^^^^^^^^^^^^^^ @@ -115,7 +115,7 @@ LL | cfg!(any(feature = "bad", windows)); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `xxx` - --> $DIR/mix.rs:55:23 + --> $DIR/mix.rs:56:23 | LL | cfg!(any(windows, xxx)); | ^^^ @@ -124,7 +124,7 @@ LL | cfg!(any(windows, xxx)); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `xxx` - --> $DIR/mix.rs:57:20 + --> $DIR/mix.rs:58:20 | LL | cfg!(all(unix, xxx)); | ^^^ @@ -133,7 +133,7 @@ LL | cfg!(all(unix, xxx)); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `aa` - --> $DIR/mix.rs:59:14 + --> $DIR/mix.rs:60:14 | LL | cfg!(all(aa, bb)); | ^^ @@ -142,7 +142,7 @@ LL | cfg!(all(aa, bb)); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `bb` - --> $DIR/mix.rs:59:18 + --> $DIR/mix.rs:60:18 | LL | cfg!(all(aa, bb)); | ^^ @@ -151,7 +151,7 @@ LL | cfg!(all(aa, bb)); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `aa` - --> $DIR/mix.rs:62:14 + --> $DIR/mix.rs:63:14 | LL | cfg!(any(aa, bb)); | ^^ @@ -160,7 +160,7 @@ LL | cfg!(any(aa, bb)); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `bb` - --> $DIR/mix.rs:62:18 + --> $DIR/mix.rs:63:18 | LL | cfg!(any(aa, bb)); | ^^ @@ -169,7 +169,7 @@ LL | cfg!(any(aa, bb)); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `zebra` - --> $DIR/mix.rs:65:20 + --> $DIR/mix.rs:66:20 | LL | cfg!(any(unix, feature = "zebra")); | ^^^^^^^^^^^^^^^^^ @@ -179,7 +179,7 @@ LL | cfg!(any(unix, feature = "zebra")); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `xxx` - --> $DIR/mix.rs:67:14 + --> $DIR/mix.rs:68:14 | LL | cfg!(any(xxx, feature = "zebra")); | ^^^ @@ -188,7 +188,7 @@ LL | cfg!(any(xxx, feature = "zebra")); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `zebra` - --> $DIR/mix.rs:67:19 + --> $DIR/mix.rs:68:19 | LL | cfg!(any(xxx, feature = "zebra")); | ^^^^^^^^^^^^^^^^^ @@ -198,7 +198,7 @@ LL | cfg!(any(xxx, feature = "zebra")); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `xxx` - --> $DIR/mix.rs:70:14 + --> $DIR/mix.rs:71:14 | LL | cfg!(any(xxx, unix, xxx)); | ^^^ @@ -207,7 +207,7 @@ LL | cfg!(any(xxx, unix, xxx)); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `xxx` - --> $DIR/mix.rs:70:25 + --> $DIR/mix.rs:71:25 | LL | cfg!(any(xxx, unix, xxx)); | ^^^ @@ -216,7 +216,7 @@ LL | cfg!(any(xxx, unix, xxx)); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `zebra` - --> $DIR/mix.rs:73:14 + --> $DIR/mix.rs:74:14 | LL | cfg!(all(feature = "zebra", feature = "zebra", feature = "zebra")); | ^^^^^^^^^^^^^^^^^ @@ -226,7 +226,7 @@ LL | cfg!(all(feature = "zebra", feature = "zebra", feature = "zebra")); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `zebra` - --> $DIR/mix.rs:73:33 + --> $DIR/mix.rs:74:33 | LL | cfg!(all(feature = "zebra", feature = "zebra", feature = "zebra")); | ^^^^^^^^^^^^^^^^^ @@ -236,7 +236,7 @@ LL | cfg!(all(feature = "zebra", feature = "zebra", feature = "zebra")); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `zebra` - --> $DIR/mix.rs:73:52 + --> $DIR/mix.rs:74:52 | LL | cfg!(all(feature = "zebra", feature = "zebra", feature = "zebra")); | ^^^^^^^^^^^^^^^^^ @@ -246,7 +246,7 @@ LL | cfg!(all(feature = "zebra", feature = "zebra", feature = "zebra")); = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `zebra` - --> $DIR/mix.rs:77:10 + --> $DIR/mix.rs:78:10 | LL | cfg!(target_feature = "zebra"); | ^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/check-cfg/no-expected-values.empty.stderr b/tests/ui/check-cfg/no-expected-values.empty.stderr index 0f181cc2ab12d..9c7d970f35e53 100644 --- a/tests/ui/check-cfg/no-expected-values.empty.stderr +++ b/tests/ui/check-cfg/no-expected-values.empty.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `foo` - --> $DIR/no-expected-values.rs:10:7 + --> $DIR/no-expected-values.rs:11:7 | LL | #[cfg(feature = "foo")] | ^^^^^^^-------- @@ -12,7 +12,7 @@ LL | #[cfg(feature = "foo")] = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `foo` - --> $DIR/no-expected-values.rs:14:7 + --> $DIR/no-expected-values.rs:15:7 | LL | #[cfg(test = "foo")] | ^^^^-------- diff --git a/tests/ui/check-cfg/no-expected-values.mixed.stderr b/tests/ui/check-cfg/no-expected-values.mixed.stderr index 0f181cc2ab12d..9c7d970f35e53 100644 --- a/tests/ui/check-cfg/no-expected-values.mixed.stderr +++ b/tests/ui/check-cfg/no-expected-values.mixed.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `foo` - --> $DIR/no-expected-values.rs:10:7 + --> $DIR/no-expected-values.rs:11:7 | LL | #[cfg(feature = "foo")] | ^^^^^^^-------- @@ -12,7 +12,7 @@ LL | #[cfg(feature = "foo")] = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `foo` - --> $DIR/no-expected-values.rs:14:7 + --> $DIR/no-expected-values.rs:15:7 | LL | #[cfg(test = "foo")] | ^^^^-------- diff --git a/tests/ui/check-cfg/no-expected-values.rs b/tests/ui/check-cfg/no-expected-values.rs index 42e7f45fa7a9c..58e0e0a10e249 100644 --- a/tests/ui/check-cfg/no-expected-values.rs +++ b/tests/ui/check-cfg/no-expected-values.rs @@ -1,6 +1,7 @@ // Check that we detect unexpected value when none are allowed // //@ check-pass +//@ no-auto-check-cfg //@ revisions: simple mixed empty //@ compile-flags: --check-cfg=cfg(values,simple,mixed,empty) //@ [simple]compile-flags: --check-cfg=cfg(test) --check-cfg=cfg(feature) diff --git a/tests/ui/check-cfg/no-expected-values.simple.stderr b/tests/ui/check-cfg/no-expected-values.simple.stderr index 0f181cc2ab12d..9c7d970f35e53 100644 --- a/tests/ui/check-cfg/no-expected-values.simple.stderr +++ b/tests/ui/check-cfg/no-expected-values.simple.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `foo` - --> $DIR/no-expected-values.rs:10:7 + --> $DIR/no-expected-values.rs:11:7 | LL | #[cfg(feature = "foo")] | ^^^^^^^-------- @@ -12,7 +12,7 @@ LL | #[cfg(feature = "foo")] = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `foo` - --> $DIR/no-expected-values.rs:14:7 + --> $DIR/no-expected-values.rs:15:7 | LL | #[cfg(test = "foo")] | ^^^^-------- diff --git a/tests/ui/check-cfg/order-independant.rs b/tests/ui/check-cfg/order-independant.rs index 671d2e764d30c..6acd1a41bab37 100644 --- a/tests/ui/check-cfg/order-independant.rs +++ b/tests/ui/check-cfg/order-independant.rs @@ -1,5 +1,6 @@ //@ check-pass // +//@ no-auto-check-cfg //@ revisions: values_before values_after //@ compile-flags: --check-cfg=cfg(values_before,values_after) //@ [values_before]compile-flags: --check-cfg=cfg(a,values("b")) --check-cfg=cfg(a) diff --git a/tests/ui/check-cfg/order-independant.values_after.stderr b/tests/ui/check-cfg/order-independant.values_after.stderr index 7e18df8e1c293..69c3aa32020f5 100644 --- a/tests/ui/check-cfg/order-independant.values_after.stderr +++ b/tests/ui/check-cfg/order-independant.values_after.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `unk` - --> $DIR/order-independant.rs:11:7 + --> $DIR/order-independant.rs:12:7 | LL | #[cfg(a = "unk")] | ^^^^^^^^^ diff --git a/tests/ui/check-cfg/order-independant.values_before.stderr b/tests/ui/check-cfg/order-independant.values_before.stderr index 7e18df8e1c293..69c3aa32020f5 100644 --- a/tests/ui/check-cfg/order-independant.values_before.stderr +++ b/tests/ui/check-cfg/order-independant.values_before.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `unk` - --> $DIR/order-independant.rs:11:7 + --> $DIR/order-independant.rs:12:7 | LL | #[cfg(a = "unk")] | ^^^^^^^^^ diff --git a/tests/ui/check-cfg/stmt-no-ice.rs b/tests/ui/check-cfg/stmt-no-ice.rs index 866a5836db0dc..edd9febbe3770 100644 --- a/tests/ui/check-cfg/stmt-no-ice.rs +++ b/tests/ui/check-cfg/stmt-no-ice.rs @@ -1,6 +1,7 @@ // This test checks that there is no ICE with this code // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags:--check-cfg=cfg() fn main() { diff --git a/tests/ui/check-cfg/stmt-no-ice.stderr b/tests/ui/check-cfg/stmt-no-ice.stderr index e686cdddc1c27..ab0deae428d17 100644 --- a/tests/ui/check-cfg/stmt-no-ice.stderr +++ b/tests/ui/check-cfg/stmt-no-ice.stderr @@ -1,10 +1,10 @@ warning: unexpected `cfg` condition name: `crossbeam_loom` - --> $DIR/stmt-no-ice.rs:7:11 + --> $DIR/stmt-no-ice.rs:8:11 | LL | #[cfg(crossbeam_loom)] | ^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(crossbeam_loom)` = note: see for more information about checking conditional configuration = note: `#[warn(unexpected_cfgs)]` on by default diff --git a/tests/ui/check-cfg/unexpected-cfg-name.rs b/tests/ui/check-cfg/unexpected-cfg-name.rs index 365c29d10fbb0..8178df8b87c5b 100644 --- a/tests/ui/check-cfg/unexpected-cfg-name.rs +++ b/tests/ui/check-cfg/unexpected-cfg-name.rs @@ -1,6 +1,7 @@ // Check warning for unexpected configuration name // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg() #[cfg(widnows)] diff --git a/tests/ui/check-cfg/unexpected-cfg-name.stderr b/tests/ui/check-cfg/unexpected-cfg-name.stderr index 0b265078aa501..c652c8e27bc69 100644 --- a/tests/ui/check-cfg/unexpected-cfg-name.stderr +++ b/tests/ui/check-cfg/unexpected-cfg-name.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition name: `widnows` - --> $DIR/unexpected-cfg-name.rs:6:7 + --> $DIR/unexpected-cfg-name.rs:7:7 | LL | #[cfg(widnows)] | ^^^^^^^ help: there is a config with a similar name: `windows` diff --git a/tests/ui/check-cfg/unexpected-cfg-value.rs b/tests/ui/check-cfg/unexpected-cfg-value.rs index 583cf40c48518..b6efcaac44cee 100644 --- a/tests/ui/check-cfg/unexpected-cfg-value.rs +++ b/tests/ui/check-cfg/unexpected-cfg-value.rs @@ -1,6 +1,7 @@ // Check for unexpected configuration value in the code. // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --cfg=feature="rand" //@ compile-flags: --check-cfg=cfg(feature,values("serde","full")) diff --git a/tests/ui/check-cfg/unexpected-cfg-value.stderr b/tests/ui/check-cfg/unexpected-cfg-value.stderr index c300120849202..efcf65bb707e3 100644 --- a/tests/ui/check-cfg/unexpected-cfg-value.stderr +++ b/tests/ui/check-cfg/unexpected-cfg-value.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `sedre` - --> $DIR/unexpected-cfg-value.rs:7:7 + --> $DIR/unexpected-cfg-value.rs:8:7 | LL | #[cfg(feature = "sedre")] | ^^^^^^^^^^------- @@ -12,7 +12,7 @@ LL | #[cfg(feature = "sedre")] = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `rand` - --> $DIR/unexpected-cfg-value.rs:14:7 + --> $DIR/unexpected-cfg-value.rs:15:7 | LL | #[cfg(feature = "rand")] | ^^^^^^^^^^^^^^^^ diff --git a/tests/ui/check-cfg/unknown-values.rs b/tests/ui/check-cfg/unknown-values.rs index 7b2b00fe9d4ca..ef0590d76d2c0 100644 --- a/tests/ui/check-cfg/unknown-values.rs +++ b/tests/ui/check-cfg/unknown-values.rs @@ -1,6 +1,7 @@ // Check that no warning is emitted for unknown cfg value // //@ check-pass +//@ no-auto-check-cfg //@ revisions: simple mixed with_values //@ compile-flags: --check-cfg=cfg(simple,mixed,with_values) //@ [simple]compile-flags: --check-cfg=cfg(foo,values(any())) diff --git a/tests/ui/check-cfg/values-none.explicit.stderr b/tests/ui/check-cfg/values-none.explicit.stderr index f75cc08f551e5..000eabdb22ede 100644 --- a/tests/ui/check-cfg/values-none.explicit.stderr +++ b/tests/ui/check-cfg/values-none.explicit.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `too` - --> $DIR/values-none.rs:10:7 + --> $DIR/values-none.rs:11:7 | LL | #[cfg(foo = "too")] | ^^^-------- @@ -12,7 +12,7 @@ LL | #[cfg(foo = "too")] = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `bar` - --> $DIR/values-none.rs:15:7 + --> $DIR/values-none.rs:16:7 | LL | #[cfg(foo = "bar")] | ^^^-------- diff --git a/tests/ui/check-cfg/values-none.implicit.stderr b/tests/ui/check-cfg/values-none.implicit.stderr index f75cc08f551e5..000eabdb22ede 100644 --- a/tests/ui/check-cfg/values-none.implicit.stderr +++ b/tests/ui/check-cfg/values-none.implicit.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `too` - --> $DIR/values-none.rs:10:7 + --> $DIR/values-none.rs:11:7 | LL | #[cfg(foo = "too")] | ^^^-------- @@ -12,7 +12,7 @@ LL | #[cfg(foo = "too")] = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `bar` - --> $DIR/values-none.rs:15:7 + --> $DIR/values-none.rs:16:7 | LL | #[cfg(foo = "bar")] | ^^^-------- diff --git a/tests/ui/check-cfg/values-none.rs b/tests/ui/check-cfg/values-none.rs index bd9c0255b7db2..6856d2f33af07 100644 --- a/tests/ui/check-cfg/values-none.rs +++ b/tests/ui/check-cfg/values-none.rs @@ -1,5 +1,6 @@ //@ check-pass // +//@ no-auto-check-cfg //@ revisions: explicit implicit //@ [explicit]compile-flags: --check-cfg=cfg(foo,values(none())) //@ [implicit]compile-flags: --check-cfg=cfg(foo) diff --git a/tests/ui/check-cfg/values-target-json.rs b/tests/ui/check-cfg/values-target-json.rs index f3a27043e6714..b52decdf6c0c4 100644 --- a/tests/ui/check-cfg/values-target-json.rs +++ b/tests/ui/check-cfg/values-target-json.rs @@ -1,6 +1,7 @@ // This test checks that we don't lint values defined by a custom target (target json) // //@ check-pass +//@ no-auto-check-cfg //@ needs-llvm-components: x86 //@ compile-flags: --crate-type=lib --check-cfg=cfg() --target={{src-base}}/check-cfg/my-awesome-platform.json diff --git a/tests/ui/check-cfg/well-known-names.rs b/tests/ui/check-cfg/well-known-names.rs index c277b84d9bd6f..b84710ca8399f 100644 --- a/tests/ui/check-cfg/well-known-names.rs +++ b/tests/ui/check-cfg/well-known-names.rs @@ -1,6 +1,7 @@ // This test checks that we lint on non well known names and that we don't lint on well known names // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg() #[cfg(target_oz = "linux")] diff --git a/tests/ui/check-cfg/well-known-names.stderr b/tests/ui/check-cfg/well-known-names.stderr index b2db777e8a842..2ce6fe80ef20f 100644 --- a/tests/ui/check-cfg/well-known-names.stderr +++ b/tests/ui/check-cfg/well-known-names.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition name: `target_oz` - --> $DIR/well-known-names.rs:6:7 + --> $DIR/well-known-names.rs:7:7 | LL | #[cfg(target_oz = "linux")] | ^^^^^^^^^^^^^^^^^^^ @@ -13,17 +13,17 @@ LL | #[cfg(target_os = "linux")] | ~~~~~~~~~ warning: unexpected `cfg` condition name: `features` - --> $DIR/well-known-names.rs:13:7 + --> $DIR/well-known-names.rs:14:7 | LL | #[cfg(features = "foo")] | ^^^^^^^^^^^^^^^^ | - = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` + = help: expected names are: `clippy`, `debug_assertions`, `doc`, `doctest`, `miri`, `overflow_checks`, `panic`, `proc_macro`, `relocation_model`, `rustfmt`, `sanitize`, `sanitizer_cfi_generalize_pointers`, `sanitizer_cfi_normalize_integers`, `target_abi`, `target_arch`, `target_endian`, `target_env`, `target_family`, `target_feature`, `target_has_atomic`, `target_has_atomic_equal_alignment`, `target_has_atomic_load_store`, `target_os`, `target_pointer_width`, `target_thread_local`, `target_vendor`, `test`, `ub_checks`, `unix`, `windows` = help: to expect this configuration use `--check-cfg=cfg(features, values("foo"))` = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `feature` - --> $DIR/well-known-names.rs:17:7 + --> $DIR/well-known-names.rs:18:7 | LL | #[cfg(feature = "foo")] | ^^^^^^^^^^^^^^^ @@ -32,7 +32,7 @@ LL | #[cfg(feature = "foo")] = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition name: `uniw` - --> $DIR/well-known-names.rs:21:7 + --> $DIR/well-known-names.rs:22:7 | LL | #[cfg(uniw)] | ^^^^ help: there is a config with a similar name: `unix` diff --git a/tests/ui/check-cfg/well-known-values.rs b/tests/ui/check-cfg/well-known-values.rs index 4c010a62d2101..d5fe746479222 100644 --- a/tests/ui/check-cfg/well-known-values.rs +++ b/tests/ui/check-cfg/well-known-values.rs @@ -5,6 +5,7 @@ // values since the suggestion shows them. // //@ check-pass +//@ no-auto-check-cfg //@ compile-flags: --check-cfg=cfg() //@ compile-flags: -Zcheck-cfg-all-expected @@ -42,6 +43,8 @@ //~^ WARN unexpected `cfg` condition value relocation_model = "_UNEXPECTED_VALUE", //~^ WARN unexpected `cfg` condition value + rustfmt = "_UNEXPECTED_VALUE", + //~^ WARN unexpected `cfg` condition value sanitize = "_UNEXPECTED_VALUE", //~^ WARN unexpected `cfg` condition value target_abi = "_UNEXPECTED_VALUE", @@ -114,4 +117,7 @@ fn doc() {} #[cfg(clippy)] fn clippy() {} +#[cfg_attr(rustfmt, rustfmt::skip)] +fn rustfmt() {} + fn main() {} diff --git a/tests/ui/check-cfg/well-known-values.stderr b/tests/ui/check-cfg/well-known-values.stderr index 1863032c38659..db4a5fd49e6a9 100644 --- a/tests/ui/check-cfg/well-known-values.stderr +++ b/tests/ui/check-cfg/well-known-values.stderr @@ -1,5 +1,5 @@ warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:27:5 + --> $DIR/well-known-values.rs:28:5 | LL | clippy = "_UNEXPECTED_VALUE", | ^^^^^^---------------------- @@ -11,7 +11,7 @@ LL | clippy = "_UNEXPECTED_VALUE", = note: `#[warn(unexpected_cfgs)]` on by default warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:29:5 + --> $DIR/well-known-values.rs:30:5 | LL | debug_assertions = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^---------------------- @@ -22,7 +22,7 @@ LL | debug_assertions = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:31:5 + --> $DIR/well-known-values.rs:32:5 | LL | doc = "_UNEXPECTED_VALUE", | ^^^---------------------- @@ -33,7 +33,7 @@ LL | doc = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:33:5 + --> $DIR/well-known-values.rs:34:5 | LL | doctest = "_UNEXPECTED_VALUE", | ^^^^^^^---------------------- @@ -44,7 +44,7 @@ LL | doctest = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:35:5 + --> $DIR/well-known-values.rs:36:5 | LL | miri = "_UNEXPECTED_VALUE", | ^^^^---------------------- @@ -55,7 +55,7 @@ LL | miri = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:37:5 + --> $DIR/well-known-values.rs:38:5 | LL | overflow_checks = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^---------------------- @@ -66,7 +66,7 @@ LL | overflow_checks = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:39:5 + --> $DIR/well-known-values.rs:40:5 | LL | panic = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -75,7 +75,7 @@ LL | panic = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:41:5 + --> $DIR/well-known-values.rs:42:5 | LL | proc_macro = "_UNEXPECTED_VALUE", | ^^^^^^^^^^---------------------- @@ -86,7 +86,7 @@ LL | proc_macro = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:43:5 + --> $DIR/well-known-values.rs:44:5 | LL | relocation_model = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -95,7 +95,18 @@ LL | relocation_model = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:45:5 + --> $DIR/well-known-values.rs:46:5 + | +LL | rustfmt = "_UNEXPECTED_VALUE", + | ^^^^^^^---------------------- + | | + | help: remove the value + | + = note: no expected value for `rustfmt` + = note: see for more information about checking conditional configuration + +warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` + --> $DIR/well-known-values.rs:48:5 | LL | sanitize = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -104,7 +115,7 @@ LL | sanitize = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:47:5 + --> $DIR/well-known-values.rs:50:5 | LL | target_abi = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -113,7 +124,7 @@ LL | target_abi = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:49:5 + --> $DIR/well-known-values.rs:52:5 | LL | target_arch = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -122,7 +133,7 @@ LL | target_arch = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:51:5 + --> $DIR/well-known-values.rs:54:5 | LL | target_endian = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -131,7 +142,7 @@ LL | target_endian = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:53:5 + --> $DIR/well-known-values.rs:56:5 | LL | target_env = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -140,7 +151,7 @@ LL | target_env = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:55:5 + --> $DIR/well-known-values.rs:58:5 | LL | target_family = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -149,7 +160,7 @@ LL | target_family = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:57:5 + --> $DIR/well-known-values.rs:60:5 | LL | target_feature = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -158,7 +169,7 @@ LL | target_feature = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:59:5 + --> $DIR/well-known-values.rs:62:5 | LL | target_has_atomic = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -167,7 +178,7 @@ LL | target_has_atomic = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:61:5 + --> $DIR/well-known-values.rs:64:5 | LL | target_has_atomic_equal_alignment = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -176,7 +187,7 @@ LL | target_has_atomic_equal_alignment = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:63:5 + --> $DIR/well-known-values.rs:66:5 | LL | target_has_atomic_load_store = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -185,7 +196,7 @@ LL | target_has_atomic_load_store = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:65:5 + --> $DIR/well-known-values.rs:68:5 | LL | target_os = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -194,7 +205,7 @@ LL | target_os = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:67:5 + --> $DIR/well-known-values.rs:70:5 | LL | target_pointer_width = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -203,7 +214,7 @@ LL | target_pointer_width = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:69:5 + --> $DIR/well-known-values.rs:72:5 | LL | target_thread_local = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^---------------------- @@ -214,7 +225,7 @@ LL | target_thread_local = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:71:5 + --> $DIR/well-known-values.rs:74:5 | LL | target_vendor = "_UNEXPECTED_VALUE", | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -223,7 +234,7 @@ LL | target_vendor = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:73:5 + --> $DIR/well-known-values.rs:76:5 | LL | test = "_UNEXPECTED_VALUE", | ^^^^---------------------- @@ -234,7 +245,7 @@ LL | test = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:75:5 + --> $DIR/well-known-values.rs:78:5 | LL | ub_checks = "_UNEXPECTED_VALUE", | ^^^^^^^^^---------------------- @@ -245,7 +256,7 @@ LL | ub_checks = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:77:5 + --> $DIR/well-known-values.rs:80:5 | LL | unix = "_UNEXPECTED_VALUE", | ^^^^---------------------- @@ -256,7 +267,7 @@ LL | unix = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `_UNEXPECTED_VALUE` - --> $DIR/well-known-values.rs:79:5 + --> $DIR/well-known-values.rs:82:5 | LL | windows = "_UNEXPECTED_VALUE", | ^^^^^^^---------------------- @@ -267,7 +278,7 @@ LL | windows = "_UNEXPECTED_VALUE", = note: see for more information about checking conditional configuration warning: unexpected `cfg` condition value: `linuz` - --> $DIR/well-known-values.rs:85:7 + --> $DIR/well-known-values.rs:88:7 | LL | #[cfg(target_os = "linuz")] // testing that we suggest `linux` | ^^^^^^^^^^^^------- @@ -277,5 +288,5 @@ LL | #[cfg(target_os = "linuz")] // testing that we suggest `linux` = note: expected values for `target_os` are: `aix`, `android`, `cuda`, `dragonfly`, `emscripten`, `espidf`, `freebsd`, `fuchsia`, `haiku`, `hermit`, `horizon`, `hurd`, `illumos`, `ios`, `l4re`, `linux`, `macos`, `netbsd`, `none`, `nto`, `openbsd`, `psp`, `redox`, `solaris`, `solid_asp3`, `teeos`, `tvos`, `uefi`, `unknown`, `visionos`, `vita`, `vxworks`, `wasi`, `watchos`, `windows`, `xous`, `zkvm` = note: see for more information about checking conditional configuration -warning: 28 warnings emitted +warning: 29 warnings emitted diff --git a/tests/ui/coercion/coerce-loop-issue-122561.rs b/tests/ui/coercion/coerce-loop-issue-122561.rs new file mode 100644 index 0000000000000..e08884ad6a4a2 --- /dev/null +++ b/tests/ui/coercion/coerce-loop-issue-122561.rs @@ -0,0 +1,110 @@ +// Regression test for #122561 + +fn for_infinite() -> bool { + for i in 0.. { + //~^ ERROR mismatched types + return false; + } +} + +fn for_finite() -> String { + for i in 0..5 { + //~^ ERROR mismatched types + return String::from("test"); + } +} + +fn for_zero_times() -> bool { + for i in 0..0 { + //~^ ERROR mismatched types + return true; + } +} + +fn for_never_type() -> ! { + for i in 0..5 { + //~^ ERROR mismatched types + } +} + +// Entire function on a single line. +// Tests that we format the suggestion +// correctly in this case +fn for_single_line() -> bool { for i in 0.. { return false; } } +//~^ ERROR mismatched types + +// Loop in an anon const in function args +// Tests that we: +// a. deal properly with this complex case +// b. format the suggestion correctly so +// that it's readable +fn for_in_arg(a: &[(); for x in 0..2 {}]) -> bool { +//~^ ERROR `for` is not allowed in a `const` +//~| ERROR mismatched types + true +} + +fn while_inifinite() -> bool { + while true { + //~^ ERROR mismatched types + //~| WARN denote infinite loops with `loop { ... }` [while_true] + return true; + } +} + +fn while_finite() -> bool { + let mut i = 0; + while i < 3 { + //~^ ERROR mismatched types + i += 1; + return true; + } +} + +fn while_zero_times() -> bool { + while false { + //~^ ERROR mismatched types + return true; + } +} + +fn while_never_type() -> ! { + while true { + //~^ ERROR mismatched types + //~| WARN denote infinite loops with `loop { ... }` [while_true] + } +} + +// No type mismatch error in this case +fn loop_() -> bool { + loop { + return true; + } +} + +const C: i32 = { + for i in 0.. { + //~^ ERROR `for` is not allowed in a `const` + //~| ERROR mismatched types + } +}; + +fn main() { + let _ = [10; { + for i in 0..5 { + //~^ ERROR `for` is not allowed in a `const` + //~| ERROR mismatched types + } + }]; + + let _ = [10; { + while false { + //~^ ERROR mismatched types + } + }]; + + + let _ = |a: &[(); for x in 0..2 {}]| {}; + //~^ ERROR `for` is not allowed in a `const` + //~| ERROR mismatched types +} diff --git a/tests/ui/coercion/coerce-loop-issue-122561.stderr b/tests/ui/coercion/coerce-loop-issue-122561.stderr new file mode 100644 index 0000000000000..0f77fd1364d6b --- /dev/null +++ b/tests/ui/coercion/coerce-loop-issue-122561.stderr @@ -0,0 +1,299 @@ +warning: denote infinite loops with `loop { ... }` + --> $DIR/coerce-loop-issue-122561.rs:48:5 + | +LL | while true { + | ^^^^^^^^^^ help: use `loop` + | + = note: `#[warn(while_true)]` on by default + +warning: denote infinite loops with `loop { ... }` + --> $DIR/coerce-loop-issue-122561.rs:72:5 + | +LL | while true { + | ^^^^^^^^^^ help: use `loop` + +error[E0658]: `for` is not allowed in a `const` + --> $DIR/coerce-loop-issue-122561.rs:41:24 + | +LL | fn for_in_arg(a: &[(); for x in 0..2 {}]) -> bool { + | ^^^^^^^^^^^^^^^^ + | + = note: see issue #87575 for more information + = help: add `#![feature(const_for)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: `for` is not allowed in a `const` + --> $DIR/coerce-loop-issue-122561.rs:86:5 + | +LL | / for i in 0.. { +LL | | +LL | | +LL | | } + | |_____^ + | + = note: see issue #87575 for more information + = help: add `#![feature(const_for)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: `for` is not allowed in a `const` + --> $DIR/coerce-loop-issue-122561.rs:94:9 + | +LL | / for i in 0..5 { +LL | | +LL | | +LL | | } + | |_________^ + | + = note: see issue #87575 for more information + = help: add `#![feature(const_for)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0658]: `for` is not allowed in a `const` + --> $DIR/coerce-loop-issue-122561.rs:107:23 + | +LL | let _ = |a: &[(); for x in 0..2 {}]| {}; + | ^^^^^^^^^^^^^^^^ + | + = note: see issue #87575 for more information + = help: add `#![feature(const_for)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:41:24 + | +LL | fn for_in_arg(a: &[(); for x in 0..2 {}]) -> bool { + | ^^^^^^^^^^^^^^^^ expected `usize`, found `()` + | + = note: `for` loops evaluate to unit type `()` +help: consider returning a value here + | +LL | fn for_in_arg(a: &[(); for x in 0..2 {} /* `usize` value */]) -> bool { + | +++++++++++++++++++ + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:86:5 + | +LL | / for i in 0.. { +LL | | +LL | | +LL | | } + | |_____^ expected `i32`, found `()` + | + = note: `for` loops evaluate to unit type `()` +help: consider returning a value here + | +LL ~ } +LL + /* `i32` value */ + | + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:4:5 + | +LL | fn for_infinite() -> bool { + | ---- expected `bool` because of return type +LL | / for i in 0.. { +LL | | +LL | | return false; +LL | | } + | |_____^ expected `bool`, found `()` + | + = note: `for` loops evaluate to unit type `()` +help: consider returning a value here + | +LL ~ } +LL + /* `bool` value */ + | + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:11:5 + | +LL | fn for_finite() -> String { + | ------ expected `String` because of return type +LL | / for i in 0..5 { +LL | | +LL | | return String::from("test"); +LL | | } + | |_____^ expected `String`, found `()` + | + = note: `for` loops evaluate to unit type `()` +help: consider returning a value here + | +LL ~ } +LL + /* `String` value */ + | + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:18:5 + | +LL | fn for_zero_times() -> bool { + | ---- expected `bool` because of return type +LL | / for i in 0..0 { +LL | | +LL | | return true; +LL | | } + | |_____^ expected `bool`, found `()` + | + = note: `for` loops evaluate to unit type `()` +help: consider returning a value here + | +LL ~ } +LL + /* `bool` value */ + | + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:25:5 + | +LL | fn for_never_type() -> ! { + | - expected `!` because of return type +LL | / for i in 0..5 { +LL | | +LL | | } + | |_____^ expected `!`, found `()` + | + = note: expected type `!` + found unit type `()` + = note: `for` loops evaluate to unit type `()` +help: consider adding a diverging expression here + | +LL ~ } +LL + /* `loop {}` or `panic!("...")` */ + | + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:33:32 + | +LL | fn for_single_line() -> bool { for i in 0.. { return false; } } + | ---- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `bool`, found `()` + | | + | expected `bool` because of return type + | + = note: `for` loops evaluate to unit type `()` +help: consider returning a value here + | +LL | fn for_single_line() -> bool { for i in 0.. { return false; } /* `bool` value */ } + | ++++++++++++++++++ + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:48:5 + | +LL | fn while_inifinite() -> bool { + | ---- expected `bool` because of return type +LL | / while true { +LL | | +LL | | +LL | | return true; +LL | | } + | |_____^ expected `bool`, found `()` + | + = note: `while` loops evaluate to unit type `()` +help: consider returning a value here + | +LL ~ } +LL + /* `bool` value */ + | + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:57:5 + | +LL | fn while_finite() -> bool { + | ---- expected `bool` because of return type +LL | let mut i = 0; +LL | / while i < 3 { +LL | | +LL | | i += 1; +LL | | return true; +LL | | } + | |_____^ expected `bool`, found `()` + | + = note: `while` loops evaluate to unit type `()` +help: consider returning a value here + | +LL ~ } +LL + /* `bool` value */ + | + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:65:5 + | +LL | fn while_zero_times() -> bool { + | ---- expected `bool` because of return type +LL | / while false { +LL | | +LL | | return true; +LL | | } + | |_____^ expected `bool`, found `()` + | + = note: `while` loops evaluate to unit type `()` +help: consider returning a value here + | +LL ~ } +LL + /* `bool` value */ + | + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:72:5 + | +LL | fn while_never_type() -> ! { + | - expected `!` because of return type +LL | / while true { +LL | | +LL | | +LL | | } + | |_____^ expected `!`, found `()` + | + = note: expected type `!` + found unit type `()` + = note: `while` loops evaluate to unit type `()` +help: consider adding a diverging expression here + | +LL ~ } +LL + /* `loop {}` or `panic!("...")` */ + | + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:94:9 + | +LL | / for i in 0..5 { +LL | | +LL | | +LL | | } + | |_________^ expected `usize`, found `()` + | + = note: `for` loops evaluate to unit type `()` +help: consider returning a value here + | +LL ~ } +LL + /* `usize` value */ + | + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:101:9 + | +LL | / while false { +LL | | +LL | | } + | |_________^ expected `usize`, found `()` + | + = note: `while` loops evaluate to unit type `()` +help: consider returning a value here + | +LL ~ } +LL + /* `usize` value */ + | + +error[E0308]: mismatched types + --> $DIR/coerce-loop-issue-122561.rs:107:23 + | +LL | let _ = |a: &[(); for x in 0..2 {}]| {}; + | ^^^^^^^^^^^^^^^^ expected `usize`, found `()` + | + = note: `for` loops evaluate to unit type `()` +help: consider returning a value here + | +LL | let _ = |a: &[(); for x in 0..2 {} /* `usize` value */]| {}; + | +++++++++++++++++++ + +error: aborting due to 18 previous errors; 2 warnings emitted + +Some errors have detailed explanations: E0308, E0658. +For more information about an error, try `rustc --explain E0308`. diff --git a/tests/ui/coercion/mut-mut-wont-coerce.rs b/tests/ui/coercion/mut-mut-wont-coerce.rs new file mode 100644 index 0000000000000..e99566461a24b --- /dev/null +++ b/tests/ui/coercion/mut-mut-wont-coerce.rs @@ -0,0 +1,43 @@ +// Documents that Rust currently does not permit the coercion &mut &mut T -> *mut *mut T +// Making this compile was a feature request in rust-lang/rust#34117 but this is currently +// "working as intended". Allowing "deep pointer coercion" seems footgun-prone, and would +// require proceeding carefully. +use std::ops::{Deref, DerefMut}; + +struct Foo(i32); + +struct SmartPtr(*mut T); + +impl SmartPtr { + fn get_addr(&mut self) -> &mut *mut T { + &mut self.0 + } +} + +impl Deref for SmartPtr { + type Target = T; + fn deref(&self) -> &T { + unsafe { &*self.0 } + } +} +impl DerefMut for SmartPtr { + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.0 } + } +} + +/// Puts a Foo into the pointer provided by the caller +fn make_foo(_: *mut *mut Foo) { + unimplemented!() +} + +fn main() { + let mut result: SmartPtr = SmartPtr(std::ptr::null_mut()); + make_foo(&mut &mut *result); //~ mismatched types + //~^ expected `*mut *mut Foo`, found `&mut &mut Foo` + make_foo(out(&mut result)); // works, but makes one wonder why above coercion cannot happen +} + +fn out(ptr: &mut SmartPtr) -> &mut *mut T { + ptr.get_addr() +} diff --git a/tests/ui/coercion/mut-mut-wont-coerce.stderr b/tests/ui/coercion/mut-mut-wont-coerce.stderr new file mode 100644 index 0000000000000..5daf9cbd3d360 --- /dev/null +++ b/tests/ui/coercion/mut-mut-wont-coerce.stderr @@ -0,0 +1,19 @@ +error[E0308]: mismatched types + --> $DIR/mut-mut-wont-coerce.rs:36:14 + | +LL | make_foo(&mut &mut *result); + | -------- ^^^^^^^^^^^^^^^^^ expected `*mut *mut Foo`, found `&mut &mut Foo` + | | + | arguments to this function are incorrect + | + = note: expected raw pointer `*mut *mut Foo` + found mutable reference `&mut &mut Foo` +note: function defined here + --> $DIR/mut-mut-wont-coerce.rs:30:4 + | +LL | fn make_foo(_: *mut *mut Foo) { + | ^^^^^^^^ ---------------- + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0308`. diff --git a/tests/ui/coherence/occurs-check/opaques.next.stderr b/tests/ui/coherence/occurs-check/opaques.next.stderr index a5182eb5d9c32..f6c5255a18693 100644 --- a/tests/ui/coherence/occurs-check/opaques.next.stderr +++ b/tests/ui/coherence/occurs-check/opaques.next.stderr @@ -11,7 +11,7 @@ error[E0282]: type annotations needed --> $DIR/opaques.rs:13:20 | LL | pub fn cast(x: Container, T>) -> Container { - | ^ cannot infer type for struct `Container` + | ^ cannot infer type for associated type `>::Assoc` error: aborting due to 2 previous errors diff --git a/tests/ui/conditional-compilation/cfg-attr-cfg-2.rs b/tests/ui/conditional-compilation/cfg-attr-cfg-2.rs index ae0afc7dfa77e..c801bbccedd6e 100644 --- a/tests/ui/conditional-compilation/cfg-attr-cfg-2.rs +++ b/tests/ui/conditional-compilation/cfg-attr-cfg-2.rs @@ -1,6 +1,5 @@ -// //@ error-pattern: `main` function not found -//@ compile-flags: --cfg foo +//@ compile-flags: --cfg foo --check-cfg=cfg(foo,bar) // main is conditionally compiled, but the conditional compilation // is conditional too! diff --git a/tests/ui/conditional-compilation/cfg-attr-cfg-2.stderr b/tests/ui/conditional-compilation/cfg-attr-cfg-2.stderr index 5f7fea0965f65..64595241dc729 100644 --- a/tests/ui/conditional-compilation/cfg-attr-cfg-2.stderr +++ b/tests/ui/conditional-compilation/cfg-attr-cfg-2.stderr @@ -1,5 +1,5 @@ error[E0601]: `main` function not found in crate `cfg_attr_cfg_2` - --> $DIR/cfg-attr-cfg-2.rs:9:14 + --> $DIR/cfg-attr-cfg-2.rs:8:14 | LL | fn main() { } | ^ consider adding a `main` function to `$DIR/cfg-attr-cfg-2.rs` diff --git a/tests/ui/conditional-compilation/cfg-attr-crate-2.rs b/tests/ui/conditional-compilation/cfg-attr-crate-2.rs index 710dbd8e81841..4b7d1c4523498 100644 --- a/tests/ui/conditional-compilation/cfg-attr-crate-2.rs +++ b/tests/ui/conditional-compilation/cfg-attr-crate-2.rs @@ -1,6 +1,6 @@ // https://github.com/rust-lang/rust/issues/21833#issuecomment-72353044 -//@ compile-flags: --cfg broken +//@ compile-flags: --cfg broken --check-cfg=cfg(broken) #![crate_type = "lib"] #![cfg_attr(broken, no_core)] //~ ERROR the `#[no_core]` attribute is an experimental feature diff --git a/tests/ui/conditional-compilation/cfg-attr-multi-invalid-1.rs b/tests/ui/conditional-compilation/cfg-attr-multi-invalid-1.rs index de2c7557a6db7..d881634abc347 100644 --- a/tests/ui/conditional-compilation/cfg-attr-multi-invalid-1.rs +++ b/tests/ui/conditional-compilation/cfg-attr-multi-invalid-1.rs @@ -1,4 +1,4 @@ -//@ compile-flags: --cfg broken +//@ compile-flags: --cfg broken --check-cfg=cfg(broken) #![crate_type = "lib"] #![cfg_attr(broken, no_core, no_std)] diff --git a/tests/ui/conditional-compilation/cfg-attr-multi-invalid-2.rs b/tests/ui/conditional-compilation/cfg-attr-multi-invalid-2.rs index e222b79c9d877..6cac52983b53b 100644 --- a/tests/ui/conditional-compilation/cfg-attr-multi-invalid-2.rs +++ b/tests/ui/conditional-compilation/cfg-attr-multi-invalid-2.rs @@ -1,4 +1,4 @@ -//@ compile-flags: --cfg broken +//@ compile-flags: --cfg broken --check-cfg=cfg(broken) #![crate_type = "lib"] #![cfg_attr(broken, no_std, no_core)] diff --git a/tests/ui/conditional-compilation/cfg-generic-params.rs b/tests/ui/conditional-compilation/cfg-generic-params.rs index 2a83be214988b..4bb8f8ae94f69 100644 --- a/tests/ui/conditional-compilation/cfg-generic-params.rs +++ b/tests/ui/conditional-compilation/cfg-generic-params.rs @@ -1,4 +1,4 @@ -//@ compile-flags:--cfg yes +//@ compile-flags:--cfg yes --check-cfg=cfg(yes,no) fn f_lt<#[cfg(yes)] 'a: 'a, #[cfg(FALSE)] T>() {} fn f_ty<#[cfg(FALSE)] 'a: 'a, #[cfg(yes)] T>() {} diff --git a/tests/ui/conditional-compilation/test-cfg.rs b/tests/ui/conditional-compilation/test-cfg.rs index 7c6c692072de4..adbbc309be447 100644 --- a/tests/ui/conditional-compilation/test-cfg.rs +++ b/tests/ui/conditional-compilation/test-cfg.rs @@ -1,4 +1,4 @@ -//@ compile-flags: --cfg foo +//@ compile-flags: --cfg foo --check-cfg=cfg(foo,bar) #[cfg(all(foo, bar))] // foo AND bar fn foo() {} diff --git a/tests/ui/consts/miri_unleashed/const_refers_to_static_cross_crate.rs b/tests/ui/consts/miri_unleashed/const_refers_to_static_cross_crate.rs index 5e7845e4e82f6..fa3ca6928e35b 100644 --- a/tests/ui/consts/miri_unleashed/const_refers_to_static_cross_crate.rs +++ b/tests/ui/consts/miri_unleashed/const_refers_to_static_cross_crate.rs @@ -2,7 +2,7 @@ //@ aux-build:static_cross_crate.rs //@ normalize-stderr-test "(the raw bytes of the constant) \(size: [0-9]*, align: [0-9]*\)" -> "$1 (size: $$SIZE, align: $$ALIGN)" //@ normalize-stderr-test "([0-9a-f][0-9a-f] |╾─*ALLOC[0-9]+(\+[a-z0-9]+)?()?─*╼ )+ *│.*" -> "HEX_DUMP" -#![feature(exclusive_range_pattern, half_open_range_patterns_in_slices)] +#![feature(half_open_range_patterns_in_slices)] #![allow(static_mut_refs)] extern crate static_cross_crate; diff --git a/tests/ui/diagnostic_namespace/do_not_recommend/simple.current.stderr b/tests/ui/diagnostic_namespace/do_not_recommend/simple.current.stderr new file mode 100644 index 0000000000000..a4d4b7b359ec8 --- /dev/null +++ b/tests/ui/diagnostic_namespace/do_not_recommend/simple.current.stderr @@ -0,0 +1,20 @@ +error[E0277]: the trait bound `*mut (): Foo` is not satisfied + --> $DIR/simple.rs:19:17 + | +LL | needs_foo::<*mut ()>(); + | ^^^^^^^ the trait `Send` is not implemented for `*mut ()`, which is required by `*mut (): Foo` + | +note: required for `*mut ()` to implement `Foo` + --> $DIR/simple.rs:10:9 + | +LL | impl Foo for T where T: Send {} + | ^^^ ^ ---- unsatisfied trait bound introduced here +note: required by a bound in `needs_foo` + --> $DIR/simple.rs:14:17 + | +LL | fn needs_foo() {} + | ^^^ required by this bound in `needs_foo` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/diagnostic_namespace/do_not_recommend/simple.next.stderr b/tests/ui/diagnostic_namespace/do_not_recommend/simple.next.stderr new file mode 100644 index 0000000000000..1341ca8175aff --- /dev/null +++ b/tests/ui/diagnostic_namespace/do_not_recommend/simple.next.stderr @@ -0,0 +1,15 @@ +error[E0277]: the trait bound `*mut (): Foo` is not satisfied + --> $DIR/simple.rs:19:17 + | +LL | needs_foo::<*mut ()>(); + | ^^^^^^^ the trait `Foo` is not implemented for `*mut ()` + | +note: required by a bound in `needs_foo` + --> $DIR/simple.rs:14:17 + | +LL | fn needs_foo() {} + | ^^^ required by this bound in `needs_foo` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/diagnostic_namespace/do_not_recommend/simple.rs b/tests/ui/diagnostic_namespace/do_not_recommend/simple.rs new file mode 100644 index 0000000000000..15ff80ae4d953 --- /dev/null +++ b/tests/ui/diagnostic_namespace/do_not_recommend/simple.rs @@ -0,0 +1,23 @@ +//@ revisions: current next +//@ ignore-compare-mode-next-solver (explicit revisions) +//@[next] compile-flags: -Znext-solver + +#![feature(do_not_recommend)] + +trait Foo {} + +#[do_not_recommend] +impl Foo for T where T: Send {} +//[current]~^ NOTE required for `*mut ()` to implement `Foo` +//[current]~| NOTE unsatisfied trait bound introduced here + +fn needs_foo() {} +//~^ NOTE required by a bound in `needs_foo` +//~| NOTE required by this bound in `needs_foo` + +fn main() { + needs_foo::<*mut ()>(); + //~^ ERROR the trait bound `*mut (): Foo` is not satisfied + //[current]~| NOTE the trait `Send` is not implemented for `*mut ()` + //[next]~| NOTE the trait `Foo` is not implemented for `*mut ()` +} diff --git a/tests/ui/did_you_mean/compatible-variants.stderr b/tests/ui/did_you_mean/compatible-variants.stderr index f2bbd8ced8f24..2c75537ca194f 100644 --- a/tests/ui/did_you_mean/compatible-variants.stderr +++ b/tests/ui/did_you_mean/compatible-variants.stderr @@ -11,6 +11,7 @@ LL | | } | = note: expected enum `Option<()>` found unit type `()` + = note: `while` loops evaluate to unit type `()` help: try adding an expression at the end of the block | LL ~ } @@ -49,6 +50,7 @@ LL | | } | = note: expected enum `Option<()>` found unit type `()` + = note: `for` loops evaluate to unit type `()` help: try adding an expression at the end of the block | LL ~ } @@ -106,6 +108,7 @@ LL | while false {} | = note: expected enum `Option<()>` found unit type `()` + = note: `while` loops evaluate to unit type `()` help: try adding an expression at the end of the block | LL ~ while false {} diff --git a/tests/ui/feature-gates/feature-gate-cfg-target-compact.rs b/tests/ui/feature-gates/feature-gate-cfg-target-compact.rs index df81b7d2297ea..e9dd81cea1bfd 100644 --- a/tests/ui/feature-gates/feature-gate-cfg-target-compact.rs +++ b/tests/ui/feature-gates/feature-gate-cfg-target-compact.rs @@ -1,13 +1,13 @@ -#[cfg(target(os = "x"))] //~ ERROR compact `cfg(target(..))` is experimental +#[cfg(target(os = "linux"))] //~ ERROR compact `cfg(target(..))` is experimental struct Foo(u64, u64); -#[cfg_attr(target(os = "x"), x)] //~ ERROR compact `cfg(target(..))` is experimental +#[cfg_attr(target(os = "linux"), non_exhaustive)] //~ ERROR compact `cfg(target(..))` is experimental struct Bar(u64, u64); -#[cfg(not(any(all(target(os = "x")))))] //~ ERROR compact `cfg(target(..))` is experimental +#[cfg(not(any(all(target(os = "linux")))))] //~ ERROR compact `cfg(target(..))` is experimental fn foo() {} fn main() { - cfg!(target(os = "x")); + cfg!(target(os = "linux")); //~^ ERROR compact `cfg(target(..))` is experimental and subject to change } diff --git a/tests/ui/feature-gates/feature-gate-cfg-target-compact.stderr b/tests/ui/feature-gates/feature-gate-cfg-target-compact.stderr index 1fd59651957ed..75c5ab37a4dce 100644 --- a/tests/ui/feature-gates/feature-gate-cfg-target-compact.stderr +++ b/tests/ui/feature-gates/feature-gate-cfg-target-compact.stderr @@ -1,8 +1,8 @@ error[E0658]: compact `cfg(target(..))` is experimental and subject to change --> $DIR/feature-gate-cfg-target-compact.rs:1:7 | -LL | #[cfg(target(os = "x"))] - | ^^^^^^^^^^^^^^^^ +LL | #[cfg(target(os = "linux"))] + | ^^^^^^^^^^^^^^^^^^^^ | = note: see issue #96901 for more information = help: add `#![feature(cfg_target_compact)]` to the crate attributes to enable @@ -11,8 +11,8 @@ LL | #[cfg(target(os = "x"))] error[E0658]: compact `cfg(target(..))` is experimental and subject to change --> $DIR/feature-gate-cfg-target-compact.rs:4:12 | -LL | #[cfg_attr(target(os = "x"), x)] - | ^^^^^^^^^^^^^^^^ +LL | #[cfg_attr(target(os = "linux"), non_exhaustive)] + | ^^^^^^^^^^^^^^^^^^^^ | = note: see issue #96901 for more information = help: add `#![feature(cfg_target_compact)]` to the crate attributes to enable @@ -21,8 +21,8 @@ LL | #[cfg_attr(target(os = "x"), x)] error[E0658]: compact `cfg(target(..))` is experimental and subject to change --> $DIR/feature-gate-cfg-target-compact.rs:7:19 | -LL | #[cfg(not(any(all(target(os = "x")))))] - | ^^^^^^^^^^^^^^^^ +LL | #[cfg(not(any(all(target(os = "linux")))))] + | ^^^^^^^^^^^^^^^^^^^^ | = note: see issue #96901 for more information = help: add `#![feature(cfg_target_compact)]` to the crate attributes to enable @@ -31,8 +31,8 @@ LL | #[cfg(not(any(all(target(os = "x")))))] error[E0658]: compact `cfg(target(..))` is experimental and subject to change --> $DIR/feature-gate-cfg-target-compact.rs:11:10 | -LL | cfg!(target(os = "x")); - | ^^^^^^^^^^^^^^^^ +LL | cfg!(target(os = "linux")); + | ^^^^^^^^^^^^^^^^^^^^ | = note: see issue #96901 for more information = help: add `#![feature(cfg_target_compact)]` to the crate attributes to enable diff --git a/tests/ui/feature-gates/feature-gate-exclusive-range-pattern.rs b/tests/ui/feature-gates/feature-gate-exclusive-range-pattern.rs deleted file mode 100644 index ded08b93fe81c..0000000000000 --- a/tests/ui/feature-gates/feature-gate-exclusive-range-pattern.rs +++ /dev/null @@ -1,6 +0,0 @@ -pub fn main() { - match 22 { - 0 .. 3 => {} //~ ERROR exclusive range pattern syntax is experimental - _ => {} - } -} diff --git a/tests/ui/feature-gates/feature-gate-exclusive-range-pattern.stderr b/tests/ui/feature-gates/feature-gate-exclusive-range-pattern.stderr deleted file mode 100644 index 5e3d34aa9f3ed..0000000000000 --- a/tests/ui/feature-gates/feature-gate-exclusive-range-pattern.stderr +++ /dev/null @@ -1,14 +0,0 @@ -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/feature-gate-exclusive-range-pattern.rs:3:9 - | -LL | 0 .. 3 => {} - | ^^^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/feature-gates/feature-gate-result_ffi_guarantees.rs b/tests/ui/feature-gates/feature-gate-result_ffi_guarantees.rs new file mode 100644 index 0000000000000..dda317aecc3c3 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-result_ffi_guarantees.rs @@ -0,0 +1,99 @@ +#![allow(dead_code)] +#![deny(improper_ctypes)] +#![feature(ptr_internals)] + +use std::num; + +enum Z {} + +#[repr(transparent)] +struct TransparentStruct(T, std::marker::PhantomData); + +#[repr(transparent)] +enum TransparentEnum { + Variant(T, std::marker::PhantomData), +} + +struct NoField; + +extern "C" { + fn result_ref_t(x: Result<&'static u8, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_fn_t(x: Result); + //~^ ERROR `extern` block uses type `Result + fn result_nonnull_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_unique_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_u8_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_u16_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_u32_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_u64_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_usize_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_i8_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_i16_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_i32_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_i64_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_isize_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_transparent_struct_t(x: Result>, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_transparent_enum_t(x: Result>, ()>); + //~^ ERROR `extern` block uses type `Result + fn result_phantom_t(x: Result, std::marker::PhantomData<()>>); + //~^ ERROR `extern` block uses type `Result + fn result_1zst_exhaustive_no_variant_t(x: Result, Z>); + //~^ ERROR `extern` block uses type `Result + fn result_1zst_exhaustive_no_field_t(x: Result, NoField>); + //~^ ERROR `extern` block uses type `Result + + fn result_ref_e(x: Result<(), &'static u8>); + //~^ ERROR `extern` block uses type `Result + fn result_fn_e(x: Result<(), extern "C" fn()>); + //~^ ERROR `extern` block uses type `Result + fn result_nonnull_e(x: Result<(), std::ptr::NonNull>); + //~^ ERROR `extern` block uses type `Result + fn result_unique_e(x: Result<(), std::ptr::Unique>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_u8_e(x: Result<(), num::NonZero>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_u16_e(x: Result<(), num::NonZero>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_u32_e(x: Result<(), num::NonZero>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_u64_e(x: Result<(), num::NonZero>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_usize_e(x: Result<(), num::NonZero>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_i8_e(x: Result<(), num::NonZero>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_i16_e(x: Result<(), num::NonZero>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_i32_e(x: Result<(), num::NonZero>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_i64_e(x: Result<(), num::NonZero>); + //~^ ERROR `extern` block uses type `Result + fn result_nonzero_isize_e(x: Result<(), num::NonZero>); + //~^ ERROR `extern` block uses type `Result + fn result_transparent_struct_e(x: Result<(), TransparentStruct>>); + //~^ ERROR `extern` block uses type `Result + fn result_transparent_enum_e(x: Result<(), TransparentEnum>>); + //~^ ERROR `extern` block uses type `Result + fn result_phantom_e(x: Result, std::marker::PhantomData<()>>); + //~^ ERROR `extern` block uses type `Result + fn result_1zst_exhaustive_no_variant_e(x: Result>); + //~^ ERROR `extern` block uses type `Result + fn result_1zst_exhaustive_no_field_e(x: Result>); + //~^ ERROR `extern` block uses type `Result +} + +pub fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-result_ffi_guarantees.stderr b/tests/ui/feature-gates/feature-gate-result_ffi_guarantees.stderr new file mode 100644 index 0000000000000..94416eb99c878 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-result_ffi_guarantees.stderr @@ -0,0 +1,349 @@ +error: `extern` block uses type `Result<&u8, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:20:24 + | +LL | fn result_ref_t(x: Result<&'static u8, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint +note: the lint level is defined here + --> $DIR/feature-gate-result_ffi_guarantees.rs:2:9 + | +LL | #![deny(improper_ctypes)] + | ^^^^^^^^^^^^^^^ + +error: `extern` block uses type `Result`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:22:23 + | +LL | fn result_fn_t(x: Result); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:24:28 + | +LL | fn result_nonnull_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:26:27 + | +LL | fn result_unique_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:28:31 + | +LL | fn result_nonzero_u8_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:30:32 + | +LL | fn result_nonzero_u16_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:32:32 + | +LL | fn result_nonzero_u32_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:34:32 + | +LL | fn result_nonzero_u64_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:36:34 + | +LL | fn result_nonzero_usize_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:38:31 + | +LL | fn result_nonzero_i8_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:40:32 + | +LL | fn result_nonzero_i16_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:42:32 + | +LL | fn result_nonzero_i32_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:44:32 + | +LL | fn result_nonzero_i64_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:46:34 + | +LL | fn result_nonzero_isize_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result>, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:48:39 + | +LL | fn result_transparent_struct_t(x: Result>, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result>, ()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:50:37 + | +LL | fn result_transparent_enum_t(x: Result>, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, PhantomData<()>>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:52:28 + | +LL | fn result_phantom_t(x: Result, std::marker::PhantomData<()>>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, Z>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:54:47 + | +LL | fn result_1zst_exhaustive_no_variant_t(x: Result, Z>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, NoField>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:56:45 + | +LL | fn result_1zst_exhaustive_no_field_t(x: Result, NoField>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), &u8>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:59:24 + | +LL | fn result_ref_e(x: Result<(), &'static u8>); + | ^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), extern "C" fn()>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:61:23 + | +LL | fn result_fn_e(x: Result<(), extern "C" fn()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), NonNull>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:63:28 + | +LL | fn result_nonnull_e(x: Result<(), std::ptr::NonNull>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), Unique>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:65:27 + | +LL | fn result_unique_e(x: Result<(), std::ptr::Unique>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), NonZero>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:67:31 + | +LL | fn result_nonzero_u8_e(x: Result<(), num::NonZero>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), NonZero>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:69:32 + | +LL | fn result_nonzero_u16_e(x: Result<(), num::NonZero>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), NonZero>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:71:32 + | +LL | fn result_nonzero_u32_e(x: Result<(), num::NonZero>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), NonZero>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:73:32 + | +LL | fn result_nonzero_u64_e(x: Result<(), num::NonZero>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), NonZero>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:75:34 + | +LL | fn result_nonzero_usize_e(x: Result<(), num::NonZero>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), NonZero>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:77:31 + | +LL | fn result_nonzero_i8_e(x: Result<(), num::NonZero>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), NonZero>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:79:32 + | +LL | fn result_nonzero_i16_e(x: Result<(), num::NonZero>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), NonZero>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:81:32 + | +LL | fn result_nonzero_i32_e(x: Result<(), num::NonZero>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), NonZero>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:83:32 + | +LL | fn result_nonzero_i64_e(x: Result<(), num::NonZero>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), NonZero>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:85:34 + | +LL | fn result_nonzero_isize_e(x: Result<(), num::NonZero>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), TransparentStruct>>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:87:39 + | +LL | fn result_transparent_struct_e(x: Result<(), TransparentStruct>>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), TransparentEnum>>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:89:37 + | +LL | fn result_transparent_enum_e(x: Result<(), TransparentEnum>>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, PhantomData<()>>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:91:28 + | +LL | fn result_phantom_e(x: Result, std::marker::PhantomData<()>>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:93:47 + | +LL | fn result_1zst_exhaustive_no_variant_e(x: Result>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result>`, which is not FFI-safe + --> $DIR/feature-gate-result_ffi_guarantees.rs:95:45 + | +LL | fn result_1zst_exhaustive_no_field_e(x: Result>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: aborting due to 38 previous errors + diff --git a/tests/ui/feature-gates/feature-gate-unix_sigpipe.rs b/tests/ui/feature-gates/feature-gate-unix_sigpipe.rs deleted file mode 100644 index 46dc3f6cc17a5..0000000000000 --- a/tests/ui/feature-gates/feature-gate-unix_sigpipe.rs +++ /dev/null @@ -1,4 +0,0 @@ -#![crate_type = "bin"] - -#[unix_sigpipe = "inherit"] //~ the `#[unix_sigpipe]` attribute is an experimental feature -fn main () {} diff --git a/tests/ui/feature-gates/feature-gate-unix_sigpipe.stderr b/tests/ui/feature-gates/feature-gate-unix_sigpipe.stderr deleted file mode 100644 index 88c18e726835e..0000000000000 --- a/tests/ui/feature-gates/feature-gate-unix_sigpipe.stderr +++ /dev/null @@ -1,13 +0,0 @@ -error[E0658]: the `#[unix_sigpipe]` attribute is an experimental feature - --> $DIR/feature-gate-unix_sigpipe.rs:3:1 - | -LL | #[unix_sigpipe = "inherit"] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #97889 for more information - = help: add `#![feature(unix_sigpipe)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/for-loop-while/break-while-condition.stderr b/tests/ui/for-loop-while/break-while-condition.stderr index 48b29f44fa106..07a57424575fd 100644 --- a/tests/ui/for-loop-while/break-while-condition.stderr +++ b/tests/ui/for-loop-while/break-while-condition.stderr @@ -20,6 +20,12 @@ LL | | } | = note: expected type `!` found unit type `()` + = note: `while` loops evaluate to unit type `()` +help: consider adding a diverging expression here + | +LL ~ } +LL + /* `loop {}` or `panic!("...")` */ + | error[E0308]: mismatched types --> $DIR/break-while-condition.rs:24:13 @@ -31,14 +37,12 @@ LL | | } | = note: expected type `!` found unit type `()` -note: the function expects a value to always be returned, but loops might run zero times - --> $DIR/break-while-condition.rs:24:13 + = note: `while` loops evaluate to unit type `()` +help: consider adding a diverging expression here + | +LL ~ } +LL + /* `loop {}` or `panic!("...")` */ | -LL | while false { - | ^^^^^^^^^^^ this might have zero elements to iterate on -LL | return - | ------ if the loop doesn't execute, this value would never get returned - = help: return a value for the case when the loop has zero elements to iterate on, otherwise consider changing the return type to account for that possibility error: aborting due to 3 previous errors diff --git a/tests/ui/for/issue-20605.next.stderr b/tests/ui/for/issue-20605.next.stderr index 0669999cb82e1..6855e17df9aac 100644 --- a/tests/ui/for/issue-20605.next.stderr +++ b/tests/ui/for/issue-20605.next.stderr @@ -2,9 +2,14 @@ error[E0277]: `dyn Iterator` is not an iterator --> $DIR/issue-20605.rs:6:17 | LL | for item in *things { *item = 0 } - | ^^^^^^^ `dyn Iterator` is not an iterator + | ^^^^^^^ the trait `IntoIterator` is not implemented for `dyn Iterator` | - = help: the trait `IntoIterator` is not implemented for `dyn Iterator` + = note: the trait bound `dyn Iterator: IntoIterator` is not satisfied + = note: required for `dyn Iterator` to implement `IntoIterator` +help: consider mutably borrowing here + | +LL | for item in &mut *things { *item = 0 } + | ++++ error: the type ` as IntoIterator>::IntoIter` is not well-formed --> $DIR/issue-20605.rs:6:17 diff --git a/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision.rs b/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision.rs index b2e9ffb57727e..dd4fe7c78b76d 100644 --- a/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision.rs +++ b/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision.rs @@ -1,5 +1,4 @@ #![feature(half_open_range_patterns_in_slices)] -#![feature(exclusive_range_pattern)] fn main() { match [5..4, 99..105, 43..44] { diff --git a/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision.stderr b/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision.stderr index 357d3a4a124d9..5ee31a0a23b22 100644 --- a/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision.stderr +++ b/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/exclusive_range_pattern_syntax_collision.rs:6:13 + --> $DIR/exclusive_range_pattern_syntax_collision.rs:5:13 | LL | match [5..4, 99..105, 43..44] { | ----------------------- this expression has type `[std::ops::Range<{integer}>; 3]` diff --git a/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision2.rs b/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision2.rs index 20f4d8f882a75..1b06181464f69 100644 --- a/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision2.rs +++ b/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision2.rs @@ -1,5 +1,4 @@ #![feature(half_open_range_patterns_in_slices)] -#![feature(exclusive_range_pattern)] fn main() { match [5..4, 99..105, 43..44] { diff --git a/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision2.stderr b/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision2.stderr index 6f56ecd4c1c9c..9ad6d5363adcb 100644 --- a/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision2.stderr +++ b/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision2.stderr @@ -1,11 +1,11 @@ error[E0527]: pattern requires 2 elements but array has 3 - --> $DIR/exclusive_range_pattern_syntax_collision2.rs:6:9 + --> $DIR/exclusive_range_pattern_syntax_collision2.rs:5:9 | LL | [_, 99..] => {}, | ^^^^^^^^^ expected 3 elements error[E0308]: mismatched types - --> $DIR/exclusive_range_pattern_syntax_collision2.rs:6:13 + --> $DIR/exclusive_range_pattern_syntax_collision2.rs:5:13 | LL | match [5..4, 99..105, 43..44] { | ----------------------- this expression has type `[std::ops::Range<{integer}>; 3]` diff --git a/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision3.rs b/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision3.rs index 14ca07d0a5388..a3aca8dfac7fc 100644 --- a/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision3.rs +++ b/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision3.rs @@ -1,5 +1,3 @@ -#![feature(exclusive_range_pattern)] - fn main() { match [5..4, 99..105, 43..44] { [..9, 99..100, _] => {}, diff --git a/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision3.stderr b/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision3.stderr index b9b272c4c7cb6..4a4a4c00b2e67 100644 --- a/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision3.stderr +++ b/tests/ui/half-open-range-patterns/exclusive_range_pattern_syntax_collision3.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/exclusive_range_pattern_syntax_collision3.rs:5:12 + --> $DIR/exclusive_range_pattern_syntax_collision3.rs:3:12 | LL | match [5..4, 99..105, 43..44] { | ----------------------- this expression has type `[std::ops::Range<{integer}>; 3]` @@ -10,7 +10,7 @@ LL | [..9, 99..100, _] => {}, found type `{integer}` error[E0308]: mismatched types - --> $DIR/exclusive_range_pattern_syntax_collision3.rs:5:15 + --> $DIR/exclusive_range_pattern_syntax_collision3.rs:3:15 | LL | match [5..4, 99..105, 43..44] { | ----------------------- this expression has type `[std::ops::Range<{integer}>; 3]` @@ -23,7 +23,7 @@ LL | [..9, 99..100, _] => {}, found type `{integer}` error[E0308]: mismatched types - --> $DIR/exclusive_range_pattern_syntax_collision3.rs:5:19 + --> $DIR/exclusive_range_pattern_syntax_collision3.rs:3:19 | LL | match [5..4, 99..105, 43..44] { | ----------------------- this expression has type `[std::ops::Range<{integer}>; 3]` diff --git a/tests/ui/half-open-range-patterns/feature-gate-half-open-range-patterns-in-slices.rs b/tests/ui/half-open-range-patterns/feature-gate-half-open-range-patterns-in-slices.rs index 99de7845d7b65..a7b0ca6fe4a54 100644 --- a/tests/ui/half-open-range-patterns/feature-gate-half-open-range-patterns-in-slices.rs +++ b/tests/ui/half-open-range-patterns/feature-gate-half-open-range-patterns-in-slices.rs @@ -1,5 +1,3 @@ -#![feature(exclusive_range_pattern)] - fn main() { let xs = [13, 1, 5, 2, 3, 1, 21, 8]; let [a @ 3.., b @ ..3, c @ 4..6, ..] = xs; diff --git a/tests/ui/half-open-range-patterns/feature-gate-half-open-range-patterns-in-slices.stderr b/tests/ui/half-open-range-patterns/feature-gate-half-open-range-patterns-in-slices.stderr index b011044f4ddc4..af11bc82d0c2e 100644 --- a/tests/ui/half-open-range-patterns/feature-gate-half-open-range-patterns-in-slices.stderr +++ b/tests/ui/half-open-range-patterns/feature-gate-half-open-range-patterns-in-slices.stderr @@ -1,5 +1,5 @@ error[E0658]: `X..` patterns in slices are experimental - --> $DIR/feature-gate-half-open-range-patterns-in-slices.rs:5:10 + --> $DIR/feature-gate-half-open-range-patterns-in-slices.rs:3:10 | LL | let [a @ 3.., b @ ..3, c @ 4..6, ..] = xs; | ^^^^^^^ @@ -9,7 +9,7 @@ LL | let [a @ 3.., b @ ..3, c @ 4..6, ..] = xs; = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0005]: refutable pattern in local binding - --> $DIR/feature-gate-half-open-range-patterns-in-slices.rs:5:9 + --> $DIR/feature-gate-half-open-range-patterns-in-slices.rs:3:9 | LL | let [a @ 3.., b @ ..3, c @ 4..6, ..] = xs; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ pattern `[i32::MIN..=2_i32, ..]` not covered diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-bad-types.rs b/tests/ui/half-open-range-patterns/half-open-range-pats-bad-types.rs index 17ea2b13f690f..b133e32452fb0 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-bad-types.rs +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-bad-types.rs @@ -1,5 +1,3 @@ -#![feature(exclusive_range_pattern)] - fn main() { let "a".. = "a"; //~ ERROR only `char` and numeric types are allowed in range patterns let .."a" = "a"; //~ ERROR only `char` and numeric types are allowed in range patterns diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-bad-types.stderr b/tests/ui/half-open-range-patterns/half-open-range-pats-bad-types.stderr index f7c59a1961933..c14c38eca6e24 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-bad-types.stderr +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-bad-types.stderr @@ -1,17 +1,17 @@ error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/half-open-range-pats-bad-types.rs:4:9 + --> $DIR/half-open-range-pats-bad-types.rs:2:9 | LL | let "a".. = "a"; | ^^^ this is of type `&'static str` but it should be `char` or numeric error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/half-open-range-pats-bad-types.rs:5:11 + --> $DIR/half-open-range-pats-bad-types.rs:3:11 | LL | let .."a" = "a"; | ^^^ this is of type `&'static str` but it should be `char` or numeric error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/half-open-range-pats-bad-types.rs:6:12 + --> $DIR/half-open-range-pats-bad-types.rs:4:12 | LL | let ..="a" = "a"; | ^^^ this is of type `&'static str` but it should be `char` or numeric diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-exhaustive-fail.rs b/tests/ui/half-open-range-patterns/half-open-range-pats-exhaustive-fail.rs index 9d067229b6de8..2059c9707d224 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-exhaustive-fail.rs +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-exhaustive-fail.rs @@ -1,6 +1,5 @@ // Test various non-exhaustive matches for `X..`, `..=X` and `..X` ranges. -#![feature(exclusive_range_pattern)] #![allow(non_contiguous_range_endpoints)] fn main() {} diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-exhaustive-fail.stderr b/tests/ui/half-open-range-patterns/half-open-range-pats-exhaustive-fail.stderr index bb4c2a4c52353..78970f8c6497d 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-exhaustive-fail.stderr +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-exhaustive-fail.stderr @@ -1,5 +1,5 @@ error[E0004]: non-exhaustive patterns: `_` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:15:8 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:14:8 | LL | m!(0f32, f32::NEG_INFINITY..); | ^^^^ pattern `_` not covered @@ -11,7 +11,7 @@ LL | match $s { $($t)+ => {}, _ => todo!() } | ++++++++++++++ error[E0004]: non-exhaustive patterns: `_` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:16:8 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:15:8 | LL | m!(0f32, ..f32::INFINITY); | ^^^^ pattern `_` not covered @@ -23,7 +23,7 @@ LL | match $s { $($t)+ => {}, _ => todo!() } | ++++++++++++++ error[E0004]: non-exhaustive patterns: `'\u{10ffff}'` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:25:8 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:24:8 | LL | m!('a', ..core::char::MAX); | ^^^ pattern `'\u{10ffff}'` not covered @@ -35,7 +35,7 @@ LL | match $s { $($t)+ => {}, '\u{10ffff}' => todo!() } | +++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `'\u{10fffe}'..='\u{10ffff}'` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:26:8 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:25:8 | LL | m!('a', ..ALMOST_MAX); | ^^^ pattern `'\u{10fffe}'..='\u{10ffff}'` not covered @@ -47,7 +47,7 @@ LL | match $s { $($t)+ => {}, '\u{10fffe}'..='\u{10ffff}' => todo!() } | ++++++++++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `'\0'` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:27:8 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:26:8 | LL | m!('a', ALMOST_MIN..); | ^^^ pattern `'\0'` not covered @@ -59,7 +59,7 @@ LL | match $s { $($t)+ => {}, '\0' => todo!() } | +++++++++++++++++ error[E0004]: non-exhaustive patterns: `'\u{10ffff}'` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:28:8 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:27:8 | LL | m!('a', ..=ALMOST_MAX); | ^^^ pattern `'\u{10ffff}'` not covered @@ -71,7 +71,7 @@ LL | match $s { $($t)+ => {}, '\u{10ffff}' => todo!() } | +++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `'b'` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:29:8 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:28:8 | LL | m!('a', ..=VAL | VAL_2..); | ^^^ pattern `'b'` not covered @@ -83,7 +83,7 @@ LL | match $s { $($t)+ => {}, 'b' => todo!() } | ++++++++++++++++ error[E0004]: non-exhaustive patterns: `'b'` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:30:8 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:29:8 | LL | m!('a', ..VAL_1 | VAL_2..); | ^^^ pattern `'b'` not covered @@ -95,7 +95,7 @@ LL | match $s { $($t)+ => {}, 'b' => todo!() } | ++++++++++++++++ error[E0004]: non-exhaustive patterns: `u8::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:40:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:39:12 | LL | m!(0, ..u8::MAX); | ^ pattern `u8::MAX` not covered @@ -107,7 +107,7 @@ LL | match $s { $($t)+ => {}, u8::MAX => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `254_u8..=u8::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:41:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:40:12 | LL | m!(0, ..ALMOST_MAX); | ^ pattern `254_u8..=u8::MAX` not covered @@ -119,7 +119,7 @@ LL | match $s { $($t)+ => {}, 254_u8..=u8::MAX => todo!() } | +++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `0_u8` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:42:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:41:12 | LL | m!(0, ALMOST_MIN..); | ^ pattern `0_u8` not covered @@ -131,7 +131,7 @@ LL | match $s { $($t)+ => {}, 0_u8 => todo!() } | +++++++++++++++++ error[E0004]: non-exhaustive patterns: `u8::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:43:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:42:12 | LL | m!(0, ..=ALMOST_MAX); | ^ pattern `u8::MAX` not covered @@ -143,7 +143,7 @@ LL | match $s { $($t)+ => {}, u8::MAX => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_u8` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:44:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:43:12 | LL | m!(0, ..=VAL | VAL_2..); | ^ pattern `43_u8` not covered @@ -155,7 +155,7 @@ LL | match $s { $($t)+ => {}, 43_u8 => todo!() } | ++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_u8` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:45:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:44:12 | LL | m!(0, ..VAL_1 | VAL_2..); | ^ pattern `43_u8` not covered @@ -167,7 +167,7 @@ LL | match $s { $($t)+ => {}, 43_u8 => todo!() } | ++++++++++++++++++ error[E0004]: non-exhaustive patterns: `u16::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:53:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:52:12 | LL | m!(0, ..u16::MAX); | ^ pattern `u16::MAX` not covered @@ -179,7 +179,7 @@ LL | match $s { $($t)+ => {}, u16::MAX => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `65534_u16..=u16::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:54:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:53:12 | LL | m!(0, ..ALMOST_MAX); | ^ pattern `65534_u16..=u16::MAX` not covered @@ -191,7 +191,7 @@ LL | match $s { $($t)+ => {}, 65534_u16..=u16::MAX => todo!() } | +++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `0_u16` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:55:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:54:12 | LL | m!(0, ALMOST_MIN..); | ^ pattern `0_u16` not covered @@ -203,7 +203,7 @@ LL | match $s { $($t)+ => {}, 0_u16 => todo!() } | ++++++++++++++++++ error[E0004]: non-exhaustive patterns: `u16::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:56:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:55:12 | LL | m!(0, ..=ALMOST_MAX); | ^ pattern `u16::MAX` not covered @@ -215,7 +215,7 @@ LL | match $s { $($t)+ => {}, u16::MAX => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_u16` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:57:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:56:12 | LL | m!(0, ..=VAL | VAL_2..); | ^ pattern `43_u16` not covered @@ -227,7 +227,7 @@ LL | match $s { $($t)+ => {}, 43_u16 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_u16` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:58:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:57:12 | LL | m!(0, ..VAL_1 | VAL_2..); | ^ pattern `43_u16` not covered @@ -239,7 +239,7 @@ LL | match $s { $($t)+ => {}, 43_u16 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `u32::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:66:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:65:12 | LL | m!(0, ..u32::MAX); | ^ pattern `u32::MAX` not covered @@ -251,7 +251,7 @@ LL | match $s { $($t)+ => {}, u32::MAX => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `4294967294_u32..=u32::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:67:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:66:12 | LL | m!(0, ..ALMOST_MAX); | ^ pattern `4294967294_u32..=u32::MAX` not covered @@ -263,7 +263,7 @@ LL | match $s { $($t)+ => {}, 4294967294_u32..=u32::MAX => todo!() } | ++++++++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `0_u32` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:68:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:67:12 | LL | m!(0, ALMOST_MIN..); | ^ pattern `0_u32` not covered @@ -275,7 +275,7 @@ LL | match $s { $($t)+ => {}, 0_u32 => todo!() } | ++++++++++++++++++ error[E0004]: non-exhaustive patterns: `u32::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:69:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:68:12 | LL | m!(0, ..=ALMOST_MAX); | ^ pattern `u32::MAX` not covered @@ -287,7 +287,7 @@ LL | match $s { $($t)+ => {}, u32::MAX => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_u32` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:70:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:69:12 | LL | m!(0, ..=VAL | VAL_2..); | ^ pattern `43_u32` not covered @@ -299,7 +299,7 @@ LL | match $s { $($t)+ => {}, 43_u32 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_u32` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:71:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:70:12 | LL | m!(0, ..VAL_1 | VAL_2..); | ^ pattern `43_u32` not covered @@ -311,7 +311,7 @@ LL | match $s { $($t)+ => {}, 43_u32 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `u64::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:79:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:78:12 | LL | m!(0, ..u64::MAX); | ^ pattern `u64::MAX` not covered @@ -323,7 +323,7 @@ LL | match $s { $($t)+ => {}, u64::MAX => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `18446744073709551614_u64..=u64::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:80:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:79:12 | LL | m!(0, ..ALMOST_MAX); | ^ pattern `18446744073709551614_u64..=u64::MAX` not covered @@ -335,7 +335,7 @@ LL | match $s { $($t)+ => {}, 18446744073709551614_u64..=u64::MAX => tod | ++++++++++++++++++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `0_u64` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:81:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:80:12 | LL | m!(0, ALMOST_MIN..); | ^ pattern `0_u64` not covered @@ -347,7 +347,7 @@ LL | match $s { $($t)+ => {}, 0_u64 => todo!() } | ++++++++++++++++++ error[E0004]: non-exhaustive patterns: `u64::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:82:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:81:12 | LL | m!(0, ..=ALMOST_MAX); | ^ pattern `u64::MAX` not covered @@ -359,7 +359,7 @@ LL | match $s { $($t)+ => {}, u64::MAX => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_u64` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:83:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:82:12 | LL | m!(0, ..=VAL | VAL_2..); | ^ pattern `43_u64` not covered @@ -371,7 +371,7 @@ LL | match $s { $($t)+ => {}, 43_u64 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_u64` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:84:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:83:12 | LL | m!(0, ..VAL_1 | VAL_2..); | ^ pattern `43_u64` not covered @@ -383,7 +383,7 @@ LL | match $s { $($t)+ => {}, 43_u64 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `u128::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:92:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:91:12 | LL | m!(0, ..u128::MAX); | ^ pattern `u128::MAX` not covered @@ -395,7 +395,7 @@ LL | match $s { $($t)+ => {}, u128::MAX => todo!() } | ++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `340282366920938463463374607431768211454_u128..` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:93:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:92:12 | LL | m!(0, ..ALMOST_MAX); | ^ pattern `340282366920938463463374607431768211454_u128..` not covered @@ -407,7 +407,7 @@ LL | match $s { $($t)+ => {}, 340282366920938463463374607431768211454_u1 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `0_u128` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:94:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:93:12 | LL | m!(0, ALMOST_MIN..); | ^ pattern `0_u128` not covered @@ -419,7 +419,7 @@ LL | match $s { $($t)+ => {}, 0_u128 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `u128::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:95:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:94:12 | LL | m!(0, ..=ALMOST_MAX); | ^ pattern `u128::MAX` not covered @@ -431,7 +431,7 @@ LL | match $s { $($t)+ => {}, u128::MAX => todo!() } | ++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_u128` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:96:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:95:12 | LL | m!(0, ..=VAL | VAL_2..); | ^ pattern `43_u128` not covered @@ -443,7 +443,7 @@ LL | match $s { $($t)+ => {}, 43_u128 => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_u128` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:97:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:96:12 | LL | m!(0, ..VAL_1 | VAL_2..); | ^ pattern `43_u128` not covered @@ -455,7 +455,7 @@ LL | match $s { $($t)+ => {}, 43_u128 => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i8::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:108:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:107:12 | LL | m!(0, ..i8::MAX); | ^ pattern `i8::MAX` not covered @@ -467,7 +467,7 @@ LL | match $s { $($t)+ => {}, i8::MAX => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `126_i8..=i8::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:109:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:108:12 | LL | m!(0, ..ALMOST_MAX); | ^ pattern `126_i8..=i8::MAX` not covered @@ -479,7 +479,7 @@ LL | match $s { $($t)+ => {}, 126_i8..=i8::MAX => todo!() } | +++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i8::MIN` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:110:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:109:12 | LL | m!(0, ALMOST_MIN..); | ^ pattern `i8::MIN` not covered @@ -491,7 +491,7 @@ LL | match $s { $($t)+ => {}, i8::MIN => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i8::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:111:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:110:12 | LL | m!(0, ..=ALMOST_MAX); | ^ pattern `i8::MAX` not covered @@ -503,7 +503,7 @@ LL | match $s { $($t)+ => {}, i8::MAX => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_i8` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:112:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:111:12 | LL | m!(0, ..=VAL | VAL_2..); | ^ pattern `43_i8` not covered @@ -515,7 +515,7 @@ LL | match $s { $($t)+ => {}, 43_i8 => todo!() } | ++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_i8` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:113:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:112:12 | LL | m!(0, ..VAL_1 | VAL_2..); | ^ pattern `43_i8` not covered @@ -527,7 +527,7 @@ LL | match $s { $($t)+ => {}, 43_i8 => todo!() } | ++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i16::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:121:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:120:12 | LL | m!(0, ..i16::MAX); | ^ pattern `i16::MAX` not covered @@ -539,7 +539,7 @@ LL | match $s { $($t)+ => {}, i16::MAX => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `32766_i16..=i16::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:122:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:121:12 | LL | m!(0, ..ALMOST_MAX); | ^ pattern `32766_i16..=i16::MAX` not covered @@ -551,7 +551,7 @@ LL | match $s { $($t)+ => {}, 32766_i16..=i16::MAX => todo!() } | +++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i16::MIN` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:123:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:122:12 | LL | m!(0, ALMOST_MIN..); | ^ pattern `i16::MIN` not covered @@ -563,7 +563,7 @@ LL | match $s { $($t)+ => {}, i16::MIN => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i16::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:124:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:123:12 | LL | m!(0, ..=ALMOST_MAX); | ^ pattern `i16::MAX` not covered @@ -575,7 +575,7 @@ LL | match $s { $($t)+ => {}, i16::MAX => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_i16` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:125:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:124:12 | LL | m!(0, ..=VAL | VAL_2..); | ^ pattern `43_i16` not covered @@ -587,7 +587,7 @@ LL | match $s { $($t)+ => {}, 43_i16 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_i16` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:126:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:125:12 | LL | m!(0, ..VAL_1 | VAL_2..); | ^ pattern `43_i16` not covered @@ -599,7 +599,7 @@ LL | match $s { $($t)+ => {}, 43_i16 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i32::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:134:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:133:12 | LL | m!(0, ..i32::MAX); | ^ pattern `i32::MAX` not covered @@ -611,7 +611,7 @@ LL | match $s { $($t)+ => {}, i32::MAX => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `2147483646_i32..=i32::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:135:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:134:12 | LL | m!(0, ..ALMOST_MAX); | ^ pattern `2147483646_i32..=i32::MAX` not covered @@ -623,7 +623,7 @@ LL | match $s { $($t)+ => {}, 2147483646_i32..=i32::MAX => todo!() } | ++++++++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i32::MIN` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:136:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:135:12 | LL | m!(0, ALMOST_MIN..); | ^ pattern `i32::MIN` not covered @@ -635,7 +635,7 @@ LL | match $s { $($t)+ => {}, i32::MIN => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i32::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:137:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:136:12 | LL | m!(0, ..=ALMOST_MAX); | ^ pattern `i32::MAX` not covered @@ -647,7 +647,7 @@ LL | match $s { $($t)+ => {}, i32::MAX => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_i32` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:138:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:137:12 | LL | m!(0, ..=VAL | VAL_2..); | ^ pattern `43_i32` not covered @@ -659,7 +659,7 @@ LL | match $s { $($t)+ => {}, 43_i32 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_i32` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:139:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:138:12 | LL | m!(0, ..VAL_1 | VAL_2..); | ^ pattern `43_i32` not covered @@ -671,7 +671,7 @@ LL | match $s { $($t)+ => {}, 43_i32 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i64::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:147:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:146:12 | LL | m!(0, ..i64::MAX); | ^ pattern `i64::MAX` not covered @@ -683,7 +683,7 @@ LL | match $s { $($t)+ => {}, i64::MAX => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `9223372036854775806_i64..=i64::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:148:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:147:12 | LL | m!(0, ..ALMOST_MAX); | ^ pattern `9223372036854775806_i64..=i64::MAX` not covered @@ -695,7 +695,7 @@ LL | match $s { $($t)+ => {}, 9223372036854775806_i64..=i64::MAX => todo | +++++++++++++++++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i64::MIN` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:149:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:148:12 | LL | m!(0, ALMOST_MIN..); | ^ pattern `i64::MIN` not covered @@ -707,7 +707,7 @@ LL | match $s { $($t)+ => {}, i64::MIN => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i64::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:150:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:149:12 | LL | m!(0, ..=ALMOST_MAX); | ^ pattern `i64::MAX` not covered @@ -719,7 +719,7 @@ LL | match $s { $($t)+ => {}, i64::MAX => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_i64` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:151:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:150:12 | LL | m!(0, ..=VAL | VAL_2..); | ^ pattern `43_i64` not covered @@ -731,7 +731,7 @@ LL | match $s { $($t)+ => {}, 43_i64 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_i64` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:152:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:151:12 | LL | m!(0, ..VAL_1 | VAL_2..); | ^ pattern `43_i64` not covered @@ -743,7 +743,7 @@ LL | match $s { $($t)+ => {}, 43_i64 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i128::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:160:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:159:12 | LL | m!(0, ..i128::MAX); | ^ pattern `i128::MAX` not covered @@ -755,7 +755,7 @@ LL | match $s { $($t)+ => {}, i128::MAX => todo!() } | ++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `170141183460469231731687303715884105726_i128..` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:161:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:160:12 | LL | m!(0, ..ALMOST_MAX); | ^ pattern `170141183460469231731687303715884105726_i128..` not covered @@ -767,7 +767,7 @@ LL | match $s { $($t)+ => {}, 170141183460469231731687303715884105726_i1 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i128::MIN` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:162:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:161:12 | LL | m!(0, ALMOST_MIN..); | ^ pattern `i128::MIN` not covered @@ -779,7 +779,7 @@ LL | match $s { $($t)+ => {}, i128::MIN => todo!() } | ++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i128::MAX` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:163:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:162:12 | LL | m!(0, ..=ALMOST_MAX); | ^ pattern `i128::MAX` not covered @@ -791,7 +791,7 @@ LL | match $s { $($t)+ => {}, i128::MAX => todo!() } | ++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_i128` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:164:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:163:12 | LL | m!(0, ..=VAL | VAL_2..); | ^ pattern `43_i128` not covered @@ -803,7 +803,7 @@ LL | match $s { $($t)+ => {}, 43_i128 => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `43_i128` not covered - --> $DIR/half-open-range-pats-exhaustive-fail.rs:165:12 + --> $DIR/half-open-range-pats-exhaustive-fail.rs:164:12 | LL | m!(0, ..VAL_1 | VAL_2..); | ^ pattern `43_i128` not covered diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-exhaustive-pass.rs b/tests/ui/half-open-range-patterns/half-open-range-pats-exhaustive-pass.rs index fe2db67013ecc..0d92ff90cc539 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-exhaustive-pass.rs +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-exhaustive-pass.rs @@ -2,8 +2,6 @@ // Test various exhaustive matches for `X..`, `..=X` and `..X` ranges. -#![feature(exclusive_range_pattern)] - fn main() {} macro_rules! m { diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-semantics.rs b/tests/ui/half-open-range-patterns/half-open-range-pats-semantics.rs index 03ff706fe6aef..3487bac528249 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-semantics.rs +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-semantics.rs @@ -3,7 +3,6 @@ // Test half-open range patterns against their expression equivalents // via `.contains(...)` and make sure the dynamic semantics match. -#![feature(exclusive_range_pattern)] #![allow(unreachable_patterns)] macro_rules! yes { diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-syntactic-pass.rs b/tests/ui/half-open-range-patterns/half-open-range-pats-syntactic-pass.rs index 98e8b2b04620a..4e3fffbef2de5 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-syntactic-pass.rs +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-syntactic-pass.rs @@ -2,8 +2,6 @@ // Test the parsing of half-open ranges. -#![feature(exclusive_range_pattern)] - fn main() {} #[cfg(FALSE)] diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-thir-lower-empty.rs b/tests/ui/half-open-range-patterns/half-open-range-pats-thir-lower-empty.rs index 158da6509662f..9ca8dd25ed76f 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-thir-lower-empty.rs +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-thir-lower-empty.rs @@ -1,5 +1,3 @@ -#![feature(exclusive_range_pattern)] - macro_rules! m { ($s:expr, $($t:tt)+) => { match $s { $($t)+ => {} } diff --git a/tests/ui/half-open-range-patterns/half-open-range-pats-thir-lower-empty.stderr b/tests/ui/half-open-range-patterns/half-open-range-pats-thir-lower-empty.stderr index 169e776fc20fd..668b5c858f06c 100644 --- a/tests/ui/half-open-range-patterns/half-open-range-pats-thir-lower-empty.stderr +++ b/tests/ui/half-open-range-patterns/half-open-range-pats-thir-lower-empty.stderr @@ -1,77 +1,77 @@ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:10:11 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:8:11 | LL | m!(0, ..u8::MIN); | ^^^^^^^^^ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:12:11 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:10:11 | LL | m!(0, ..u16::MIN); | ^^^^^^^^^^ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:14:11 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:12:11 | LL | m!(0, ..u32::MIN); | ^^^^^^^^^^ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:16:11 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:14:11 | LL | m!(0, ..u64::MIN); | ^^^^^^^^^^ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:18:11 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:16:11 | LL | m!(0, ..u128::MIN); | ^^^^^^^^^^^ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:21:11 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:19:11 | LL | m!(0, ..i8::MIN); | ^^^^^^^^^ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:23:11 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:21:11 | LL | m!(0, ..i16::MIN); | ^^^^^^^^^^ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:25:11 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:23:11 | LL | m!(0, ..i32::MIN); | ^^^^^^^^^^ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:27:11 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:25:11 | LL | m!(0, ..i64::MIN); | ^^^^^^^^^^ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:29:11 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:27:11 | LL | m!(0, ..i128::MIN); | ^^^^^^^^^^^ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:32:14 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:30:14 | LL | m!(0f32, ..f32::NEG_INFINITY); | ^^^^^^^^^^^^^^^^^^^ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:34:14 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:32:14 | LL | m!(0f64, ..f64::NEG_INFINITY); | ^^^^^^^^^^^^^^^^^^^ error[E0579]: lower range bound must be less than upper - --> $DIR/half-open-range-pats-thir-lower-empty.rs:37:13 + --> $DIR/half-open-range-pats-thir-lower-empty.rs:35:13 | LL | m!('a', ..'\u{0}'); | ^^^^^^^^^ diff --git a/tests/ui/half-open-range-patterns/pat-tuple-4.rs b/tests/ui/half-open-range-patterns/pat-tuple-4.rs index 95aae25ada894..325293aa486ec 100644 --- a/tests/ui/half-open-range-patterns/pat-tuple-4.rs +++ b/tests/ui/half-open-range-patterns/pat-tuple-4.rs @@ -1,7 +1,5 @@ //@ check-pass -#![feature(exclusive_range_pattern)] - fn main() { const PAT: u8 = 1; diff --git a/tests/ui/half-open-range-patterns/pat-tuple-5.rs b/tests/ui/half-open-range-patterns/pat-tuple-5.rs index 995ef03c83ed7..4ed43954e0294 100644 --- a/tests/ui/half-open-range-patterns/pat-tuple-5.rs +++ b/tests/ui/half-open-range-patterns/pat-tuple-5.rs @@ -1,5 +1,3 @@ -#![feature(exclusive_range_pattern)] - fn main() { const PAT: u8 = 1; diff --git a/tests/ui/half-open-range-patterns/pat-tuple-5.stderr b/tests/ui/half-open-range-patterns/pat-tuple-5.stderr index a7dd413979237..e6d33947d46ef 100644 --- a/tests/ui/half-open-range-patterns/pat-tuple-5.stderr +++ b/tests/ui/half-open-range-patterns/pat-tuple-5.stderr @@ -1,5 +1,5 @@ error[E0308]: mismatched types - --> $DIR/pat-tuple-5.rs:7:10 + --> $DIR/pat-tuple-5.rs:5:10 | LL | match (0, 1) { | ------ this expression has type `({integer}, {integer})` diff --git a/tests/ui/half-open-range-patterns/range_pat_interactions0.rs b/tests/ui/half-open-range-patterns/range_pat_interactions0.rs index 53b6b89ed1662..f943ea0271da2 100644 --- a/tests/ui/half-open-range-patterns/range_pat_interactions0.rs +++ b/tests/ui/half-open-range-patterns/range_pat_interactions0.rs @@ -1,6 +1,5 @@ //@ run-pass #![allow(non_contiguous_range_endpoints)] -#![feature(exclusive_range_pattern)] #![feature(inline_const_pat)] fn main() { diff --git a/tests/ui/half-open-range-patterns/range_pat_interactions1.rs b/tests/ui/half-open-range-patterns/range_pat_interactions1.rs index 0c050c550c4ce..4d7c9f10261f2 100644 --- a/tests/ui/half-open-range-patterns/range_pat_interactions1.rs +++ b/tests/ui/half-open-range-patterns/range_pat_interactions1.rs @@ -9,26 +9,19 @@ fn main() { for x in -9 + 1..=(9 - 2) { if let n @ 2..3|4 = x { //~^ error: variable `n` is not bound in all patterns - //~| exclusive range pattern syntax is experimental errors_only.push(x); } else if let 2..3 | 4 = x { - //~^ exclusive range pattern syntax is experimental if_lettable.push(x); } match x as i32 { 0..5+1 => errors_only.push(x), //~^ error: expected a pattern range bound, found an expression - //~| error: exclusive range pattern syntax is experimental 1 | -3..0 => first_or.push(x), - //~^ error: exclusive range pattern syntax is experimental y @ (0..5 | 6) => or_two.push(y), - //~^ error: exclusive range pattern syntax is experimental y @ 0..const { 5 + 1 } => assert_eq!(y, 5), - //~^ error: exclusive range pattern syntax is experimental - //~| error: inline-const in pattern position is experimental + //~^ error: inline-const in pattern position is experimental [E0658] y @ -5.. => range_from.push(y), y @ ..-7 => assert_eq!(y, -8), - //~^ error: exclusive range pattern syntax is experimental y => bottom.push(y), } } diff --git a/tests/ui/half-open-range-patterns/range_pat_interactions1.stderr b/tests/ui/half-open-range-patterns/range_pat_interactions1.stderr index cc481f7a79e13..c14021e009bd1 100644 --- a/tests/ui/half-open-range-patterns/range_pat_interactions1.stderr +++ b/tests/ui/half-open-range-patterns/range_pat_interactions1.stderr @@ -1,5 +1,5 @@ error: expected a pattern range bound, found an expression - --> $DIR/range_pat_interactions1.rs:19:16 + --> $DIR/range_pat_interactions1.rs:17:16 | LL | 0..5+1 => errors_only.push(x), | ^^^ arbitrary expressions are not allowed in patterns @@ -13,7 +13,7 @@ LL | if let n @ 2..3|4 = x { | variable not in all patterns error[E0658]: inline-const in pattern position is experimental - --> $DIR/range_pat_interactions1.rs:26:20 + --> $DIR/range_pat_interactions1.rs:21:20 | LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), | ^^^^^ @@ -22,84 +22,7 @@ LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), = help: add `#![feature(inline_const_pat)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions1.rs:10:20 - | -LL | if let n @ 2..3|4 = x { - | ^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions1.rs:14:23 - | -LL | } else if let 2..3 | 4 = x { - | ^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions1.rs:19:13 - | -LL | 0..5+1 => errors_only.push(x), - | ^^^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions1.rs:22:17 - | -LL | 1 | -3..0 => first_or.push(x), - | ^^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions1.rs:24:18 - | -LL | y @ (0..5 | 6) => or_two.push(y), - | ^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions1.rs:26:17 - | -LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), - | ^^^^^^^^^^^^^^^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions1.rs:30:17 - | -LL | y @ ..-7 => assert_eq!(y, -8), - | ^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error: aborting due to 10 previous errors +error: aborting due to 3 previous errors Some errors have detailed explanations: E0408, E0658. For more information about an error, try `rustc --explain E0408`. diff --git a/tests/ui/half-open-range-patterns/range_pat_interactions2.rs b/tests/ui/half-open-range-patterns/range_pat_interactions2.rs index 068104c4b1b8c..0dbdb8fe7b6ef 100644 --- a/tests/ui/half-open-range-patterns/range_pat_interactions2.rs +++ b/tests/ui/half-open-range-patterns/range_pat_interactions2.rs @@ -11,15 +11,11 @@ fn main() { //~^ error: expected a pattern range bound, found an expression //~| error: range pattern bounds cannot have parentheses 1 | -3..0 => first_or.push(x), - //~^ error: exclusive range pattern syntax is experimental y @ (0..5 | 6) => or_two.push(y), - //~^ error: exclusive range pattern syntax is experimental y @ 0..const { 5 + 1 } => assert_eq!(y, 5), //~^ error: inline-const in pattern position is experimental - //~| error: exclusive range pattern syntax is experimental y @ -5.. => range_from.push(y), y @ ..-7 => assert_eq!(y, -8), - //~^ error: exclusive range pattern syntax is experimental y => bottom.push(y), } } diff --git a/tests/ui/half-open-range-patterns/range_pat_interactions2.stderr b/tests/ui/half-open-range-patterns/range_pat_interactions2.stderr index 8f21a6149fb89..136296fa5b0f0 100644 --- a/tests/ui/half-open-range-patterns/range_pat_interactions2.stderr +++ b/tests/ui/half-open-range-patterns/range_pat_interactions2.stderr @@ -17,7 +17,7 @@ LL + 0..=5+1 => errors_only.push(x), | error[E0658]: inline-const in pattern position is experimental - --> $DIR/range_pat_interactions2.rs:17:20 + --> $DIR/range_pat_interactions2.rs:15:20 | LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), | ^^^^^ @@ -26,50 +26,6 @@ LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), = help: add `#![feature(inline_const_pat)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions2.rs:13:17 - | -LL | 1 | -3..0 => first_or.push(x), - | ^^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions2.rs:15:18 - | -LL | y @ (0..5 | 6) => or_two.push(y), - | ^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions2.rs:17:17 - | -LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), - | ^^^^^^^^^^^^^^^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions2.rs:21:17 - | -LL | y @ ..-7 => assert_eq!(y, -8), - | ^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error: aborting due to 7 previous errors +error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/half-open-range-patterns/range_pat_interactions3.rs b/tests/ui/half-open-range-patterns/range_pat_interactions3.rs index 446ed45f9c6f0..2f2778095cf49 100644 --- a/tests/ui/half-open-range-patterns/range_pat_interactions3.rs +++ b/tests/ui/half-open-range-patterns/range_pat_interactions3.rs @@ -8,15 +8,11 @@ fn main() { match x as i32 { 8.. => bottom.push(x), 1 | -3..0 => first_or.push(x), - //~^ exclusive range pattern syntax is experimental y @ (0..5 | 6) => or_two.push(y), - //~^ exclusive range pattern syntax is experimental y @ 0..const { 5 + 1 } => assert_eq!(y, 5), //~^ inline-const in pattern position is experimental - //~| exclusive range pattern syntax is experimental y @ -5.. => range_from.push(y), y @ ..-7 => assert_eq!(y, -8), - //~^ exclusive range pattern syntax is experimental y => bottom.push(y), } } diff --git a/tests/ui/half-open-range-patterns/range_pat_interactions3.stderr b/tests/ui/half-open-range-patterns/range_pat_interactions3.stderr index 51cc22e7d5602..dc7dc0efa7a28 100644 --- a/tests/ui/half-open-range-patterns/range_pat_interactions3.stderr +++ b/tests/ui/half-open-range-patterns/range_pat_interactions3.stderr @@ -1,5 +1,5 @@ error[E0658]: inline-const in pattern position is experimental - --> $DIR/range_pat_interactions3.rs:14:20 + --> $DIR/range_pat_interactions3.rs:12:20 | LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), | ^^^^^ @@ -8,50 +8,6 @@ LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), = help: add `#![feature(inline_const_pat)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions3.rs:10:17 - | -LL | 1 | -3..0 => first_or.push(x), - | ^^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions3.rs:12:18 - | -LL | y @ (0..5 | 6) => or_two.push(y), - | ^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions3.rs:14:17 - | -LL | y @ 0..const { 5 + 1 } => assert_eq!(y, 5), - | ^^^^^^^^^^^^^^^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range_pat_interactions3.rs:18:17 - | -LL | y @ ..-7 => assert_eq!(y, -8), - | ^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error: aborting due to 5 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem0.rs b/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem0.rs index d54cbfbf4bbf9..aa2690f377768 100644 --- a/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem0.rs +++ b/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem0.rs @@ -1,5 +1,4 @@ #![feature(half_open_range_patterns_in_slices)] -#![feature(exclusive_range_pattern)] fn main() { let xs = [13, 1, 5, 2, 3, 1, 21, 8]; diff --git a/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem0.stderr b/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem0.stderr index eca5c3301801f..5bcbe21a6a930 100644 --- a/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem0.stderr +++ b/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem0.stderr @@ -1,5 +1,5 @@ error[E0527]: pattern requires 2 elements but array has 8 - --> $DIR/slice_pattern_syntax_problem0.rs:11:9 + --> $DIR/slice_pattern_syntax_problem0.rs:10:9 | LL | let [first_three @ ..3, rest @ 2..] = xs; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected 8 elements diff --git a/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem1.rs b/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem1.rs index cd38154437266..60b056fbcb694 100644 --- a/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem1.rs +++ b/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem1.rs @@ -3,7 +3,5 @@ fn main() { let xs = [13, 1, 5, 2, 3, 1, 21, 8]; let [a @ 3.., b @ ..3, c @ 4..6, ..] = xs; //~^ `X..` patterns in slices are experimental - //~| exclusive range pattern syntax is experimental - //~| exclusive range pattern syntax is experimental //~| ERROR: refutable pattern } diff --git a/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem1.stderr b/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem1.stderr index fc549eb65c0ed..4951591990462 100644 --- a/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem1.stderr +++ b/tests/ui/half-open-range-patterns/slice_pattern_syntax_problem1.stderr @@ -8,28 +8,6 @@ LL | let [a @ 3.., b @ ..3, c @ 4..6, ..] = xs; = help: add `#![feature(half_open_range_patterns_in_slices)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/slice_pattern_syntax_problem1.rs:4:23 - | -LL | let [a @ 3.., b @ ..3, c @ 4..6, ..] = xs; - | ^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/slice_pattern_syntax_problem1.rs:4:32 - | -LL | let [a @ 3.., b @ ..3, c @ 4..6, ..] = xs; - | ^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - error[E0005]: refutable pattern in local binding --> $DIR/slice_pattern_syntax_problem1.rs:4:9 | @@ -44,7 +22,7 @@ help: you might want to use `let else` to handle the variant that isn't matched LL | let [a @ 3.., b @ ..3, c @ 4..6, ..] = xs else { todo!() }; | ++++++++++++++++ -error: aborting due to 4 previous errors +error: aborting due to 2 previous errors Some errors have detailed explanations: E0005, E0658. For more information about an error, try `rustc --explain E0005`. diff --git a/tests/ui/higher-ranked/leak-check/leak-check-in-selection-3.next.stderr b/tests/ui/higher-ranked/leak-check/leak-check-in-selection-3.next.stderr index 8a8118dea859b..5be683cd3191b 100644 --- a/tests/ui/higher-ranked/leak-check/leak-check-in-selection-3.next.stderr +++ b/tests/ui/higher-ranked/leak-check/leak-check-in-selection-3.next.stderr @@ -23,7 +23,20 @@ error[E0283]: type annotations needed LL | impls_indirect_leak::>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type of the type parameter `T` declared on the function `impls_indirect_leak` | - = note: cannot satisfy `for<'a> Box<_>: IndirectLeak<'a>` +note: multiple `impl`s satisfying `for<'a> Box<_>: Leak<'a>` found + --> $DIR/leak-check-in-selection-3.rs:9:1 + | +LL | impl Leak<'_> for Box {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | impl Leak<'static> for Box {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +note: required for `Box<_>` to implement `for<'a> IndirectLeak<'a>` + --> $DIR/leak-check-in-selection-3.rs:23:23 + | +LL | impl<'a, T: Leak<'a>> IndirectLeak<'a> for T {} + | -------- ^^^^^^^^^^^^^^^^ ^ + | | + | unsatisfied trait bound introduced here note: required by a bound in `impls_indirect_leak` --> $DIR/leak-check-in-selection-3.rs:25:27 | diff --git a/tests/ui/imports/extern-prelude-extern-crate-cfg.rs b/tests/ui/imports/extern-prelude-extern-crate-cfg.rs index 346d63dabe7ee..49b90e4391534 100644 --- a/tests/ui/imports/extern-prelude-extern-crate-cfg.rs +++ b/tests/ui/imports/extern-prelude-extern-crate-cfg.rs @@ -1,5 +1,5 @@ //@ build-pass (FIXME(62277): could be check-pass?) -//@ compile-flags:--cfg my_feature +//@ compile-flags:--cfg my_feature --check-cfg=cfg(my_feature) #![no_std] diff --git a/tests/ui/inline-const/const-match-pat-range.rs b/tests/ui/inline-const/const-match-pat-range.rs index 7f51815cb7792..7202c0c04521e 100644 --- a/tests/ui/inline-const/const-match-pat-range.rs +++ b/tests/ui/inline-const/const-match-pat-range.rs @@ -1,6 +1,6 @@ //@ build-pass -#![feature(inline_const_pat, exclusive_range_pattern)] +#![feature(inline_const_pat)] fn main() { const N: u32 = 10; diff --git a/tests/ui/instrument-coverage/on-values.rs b/tests/ui/instrument-coverage/on-values.rs index 36643c40525ee..a6793b2c304f2 100644 --- a/tests/ui/instrument-coverage/on-values.rs +++ b/tests/ui/instrument-coverage/on-values.rs @@ -1,11 +1,11 @@ //@ check-pass //@ needs-profiler-support -//@ revisions: default y yes on true all +//@ revisions: default y yes on true_ all //@ [default] compile-flags: -Cinstrument-coverage //@ [y] compile-flags: -Cinstrument-coverage=y //@ [yes] compile-flags: -Cinstrument-coverage=yes //@ [on] compile-flags: -Cinstrument-coverage=on -//@ [true] compile-flags: -Cinstrument-coverage=true +//@ [true_] compile-flags: -Cinstrument-coverage=true //@ [all] compile-flags: -Cinstrument-coverage=all fn main() {} diff --git a/tests/ui/issues/issue-11085.rs b/tests/ui/issues/issue-11085.rs index 300be10226c6c..f646ba35cbfae 100644 --- a/tests/ui/issues/issue-11085.rs +++ b/tests/ui/issues/issue-11085.rs @@ -1,9 +1,8 @@ //@ run-pass -#![allow(dead_code)] -//@ compile-flags: --cfg foo - //@ pretty-expanded FIXME #23616 +#![allow(dead_code)] + struct Foo { #[cfg(FALSE)] bar: baz, @@ -11,7 +10,7 @@ struct Foo { } struct Foo2 { - #[cfg(foo)] + #[cfg(all())] foo: isize, } diff --git a/tests/ui/issues/issue-24434.rs b/tests/ui/issues/issue-24434.rs index 4cf1f8b50f7c4..991084c274093 100644 --- a/tests/ui/issues/issue-24434.rs +++ b/tests/ui/issues/issue-24434.rs @@ -1,7 +1,6 @@ //@ check-pass -//@ compile-flags:--cfg set1 -#![cfg_attr(set1, feature(rustc_attrs))] +#![cfg_attr(all(), feature(rustc_attrs))] #![rustc_dummy] fn main() {} diff --git a/tests/ui/issues/issue-27042.stderr b/tests/ui/issues/issue-27042.stderr index ba39399e46eda..6586e61f2f644 100644 --- a/tests/ui/issues/issue-27042.stderr +++ b/tests/ui/issues/issue-27042.stderr @@ -40,6 +40,8 @@ error[E0308]: mismatched types LL | / 'c: LL | | for _ in None { break }; // but here we cite the whole loop | |_______________________________^ expected `i32`, found `()` + | + = note: `for` loops evaluate to unit type `()` error[E0308]: mismatched types --> $DIR/issue-27042.rs:15:9 diff --git a/tests/ui/issues/issue-50585.stderr b/tests/ui/issues/issue-50585.stderr index 13181f1cf7fe4..e7f13e634750c 100644 --- a/tests/ui/issues/issue-50585.stderr +++ b/tests/ui/issues/issue-50585.stderr @@ -13,6 +13,12 @@ error[E0308]: mismatched types | LL | |y: Vec<[(); for x in 0..2 {}]>| {}; | ^^^^^^^^^^^^^^^^ expected `usize`, found `()` + | + = note: `for` loops evaluate to unit type `()` +help: consider returning a value here + | +LL | |y: Vec<[(); for x in 0..2 {} /* `usize` value */]>| {}; + | +++++++++++++++++++ error: aborting due to 2 previous errors diff --git a/tests/ui/lint/lint-ctypes-enum.rs b/tests/ui/lint/lint-ctypes-enum.rs index c60290f8553a7..cb8e9e8067513 100644 --- a/tests/ui/lint/lint-ctypes-enum.rs +++ b/tests/ui/lint/lint-ctypes-enum.rs @@ -2,6 +2,7 @@ #![deny(improper_ctypes)] #![feature(ptr_internals)] #![feature(transparent_unions)] +#![feature(result_ffi_guarantees)] use std::num; @@ -55,38 +56,123 @@ union TransparentUnion { struct Rust(T); +struct NoField; + +#[repr(transparent)] +struct Field(()); + +#[non_exhaustive] +enum NonExhaustive {} + extern "C" { - fn zf(x: Z); - fn uf(x: U); //~ ERROR `extern` block uses type `U` - fn bf(x: B); //~ ERROR `extern` block uses type `B` - fn tf(x: T); //~ ERROR `extern` block uses type `T` - fn repr_c(x: ReprC); - fn repr_u8(x: U8); - fn repr_isize(x: Isize); - fn option_ref(x: Option<&'static u8>); - fn option_fn(x: Option); - fn nonnull(x: Option>); - fn unique(x: Option>); - fn nonzero_u8(x: Option>); - fn nonzero_u16(x: Option>); - fn nonzero_u32(x: Option>); - fn nonzero_u64(x: Option>); - fn nonzero_u128(x: Option>); - //~^ ERROR `extern` block uses type `u128` - fn nonzero_usize(x: Option>); - fn nonzero_i8(x: Option>); - fn nonzero_i16(x: Option>); - fn nonzero_i32(x: Option>); - fn nonzero_i64(x: Option>); - fn nonzero_i128(x: Option>); - //~^ ERROR `extern` block uses type `i128` - fn nonzero_isize(x: Option>); - fn transparent_struct(x: Option>>); - fn transparent_enum(x: Option>>); - fn transparent_union(x: Option>>); - //~^ ERROR `extern` block uses type - fn repr_rust(x: Option>>); //~ ERROR `extern` block uses type - fn no_result(x: Result<(), num::NonZero>); //~ ERROR `extern` block uses type + fn zf(x: Z); + fn uf(x: U); //~ ERROR `extern` block uses type `U` + fn bf(x: B); //~ ERROR `extern` block uses type `B` + fn tf(x: T); //~ ERROR `extern` block uses type `T` + fn repr_c(x: ReprC); + fn repr_u8(x: U8); + fn repr_isize(x: Isize); + fn option_ref(x: Option<&'static u8>); + fn option_fn(x: Option); + fn option_nonnull(x: Option>); + fn option_unique(x: Option>); + fn option_nonzero_u8(x: Option>); + fn option_nonzero_u16(x: Option>); + fn option_nonzero_u32(x: Option>); + fn option_nonzero_u64(x: Option>); + fn option_nonzero_u128(x: Option>); + //~^ ERROR `extern` block uses type `u128` + fn option_nonzero_usize(x: Option>); + fn option_nonzero_i8(x: Option>); + fn option_nonzero_i16(x: Option>); + fn option_nonzero_i32(x: Option>); + fn option_nonzero_i64(x: Option>); + fn option_nonzero_i128(x: Option>); + //~^ ERROR `extern` block uses type `i128` + fn option_nonzero_isize(x: Option>); + fn option_transparent_struct(x: Option>>); + fn option_transparent_enum(x: Option>>); + fn option_transparent_union(x: Option>>); + //~^ ERROR `extern` block uses type + fn option_repr_rust(x: Option>>); //~ ERROR `extern` block uses type + + fn result_ref_t(x: Result<&'static u8, ()>); + fn result_fn_t(x: Result); + fn result_nonnull_t(x: Result, ()>); + fn result_unique_t(x: Result, ()>); + fn result_nonzero_u8_t(x: Result, ()>); + fn result_nonzero_u16_t(x: Result, ()>); + fn result_nonzero_u32_t(x: Result, ()>); + fn result_nonzero_u64_t(x: Result, ()>); + fn result_nonzero_u128_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `u128` + fn result_nonzero_usize_t(x: Result, ()>); + fn result_nonzero_i8_t(x: Result, ()>); + fn result_nonzero_i16_t(x: Result, ()>); + fn result_nonzero_i32_t(x: Result, ()>); + fn result_nonzero_i64_t(x: Result, ()>); + fn result_nonzero_i128_t(x: Result, ()>); + //~^ ERROR `extern` block uses type `i128` + fn result_nonzero_isize_t(x: Result, ()>); + fn result_transparent_struct_t(x: Result>, ()>); + fn result_transparent_enum_t(x: Result>, ()>); + fn result_transparent_union_t(x: Result>, ()>); + //~^ ERROR `extern` block uses type + fn result_repr_rust_t(x: Result>, ()>); + //~^ ERROR `extern` block uses type + fn result_phantom_t(x: Result, std::marker::PhantomData<()>>); + fn result_1zst_exhaustive_no_variant_t(x: Result, Z>); + fn result_1zst_exhaustive_single_variant_t(x: Result, U>); + //~^ ERROR `extern` block uses type + fn result_1zst_exhaustive_multiple_variant_t(x: Result, B>); + //~^ ERROR `extern` block uses type + fn result_1zst_non_exhaustive_no_variant_t(x: Result, NonExhaustive>); + //~^ ERROR `extern` block uses type + fn result_1zst_exhaustive_no_field_t(x: Result, NoField>); + fn result_1zst_exhaustive_single_field_t(x: Result, Field>); + //~^ ERROR `extern` block uses type + fn result_cascading_t(x: Result>, ()>); + //~^ ERROR `extern` block uses type + + fn result_ref_e(x: Result<(), &'static u8>); + fn result_fn_e(x: Result<(), extern "C" fn()>); + fn result_nonnull_e(x: Result<(), std::ptr::NonNull>); + fn result_unique_e(x: Result<(), std::ptr::Unique>); + fn result_nonzero_u8_e(x: Result<(), num::NonZero>); + fn result_nonzero_u16_e(x: Result<(), num::NonZero>); + fn result_nonzero_u32_e(x: Result<(), num::NonZero>); + fn result_nonzero_u64_e(x: Result<(), num::NonZero>); + fn result_nonzero_u128_e(x: Result<(), num::NonZero>); + //~^ ERROR `extern` block uses type `u128` + fn result_nonzero_usize_e(x: Result<(), num::NonZero>); + fn result_nonzero_i8_e(x: Result<(), num::NonZero>); + fn result_nonzero_i16_e(x: Result<(), num::NonZero>); + fn result_nonzero_i32_e(x: Result<(), num::NonZero>); + fn result_nonzero_i64_e(x: Result<(), num::NonZero>); + fn result_nonzero_i128_e(x: Result<(), num::NonZero>); + //~^ ERROR `extern` block uses type `i128` + fn result_nonzero_isize_e(x: Result<(), num::NonZero>); + fn result_transparent_struct_e(x: Result<(), TransparentStruct>>); + fn result_transparent_enum_e(x: Result<(), TransparentEnum>>); + fn result_transparent_union_e(x: Result<(), TransparentUnion>>); + //~^ ERROR `extern` block uses type + fn result_repr_rust_e(x: Result<(), Rust>>); + //~^ ERROR `extern` block uses type + fn result_phantom_e(x: Result, std::marker::PhantomData<()>>); + fn result_1zst_exhaustive_no_variant_e(x: Result>); + fn result_1zst_exhaustive_single_variant_e(x: Result>); + //~^ ERROR `extern` block uses type + fn result_1zst_exhaustive_multiple_variant_e(x: Result>); + //~^ ERROR `extern` block uses type + fn result_1zst_non_exhaustive_no_variant_e(x: Result>); + //~^ ERROR `extern` block uses type + fn result_1zst_exhaustive_no_field_e(x: Result>); + fn result_1zst_exhaustive_single_field_e(x: Result>); + //~^ ERROR `extern` block uses type + fn result_cascading_e(x: Result<(), Result<(), num::NonZero>>); + //~^ ERROR `extern` block uses type + fn result_unit_t_e(x: Result<(), ()>); + //~^ ERROR `extern` block uses type } pub fn main() {} diff --git a/tests/ui/lint/lint-ctypes-enum.stderr b/tests/ui/lint/lint-ctypes-enum.stderr index 103fda8d40253..bba5b09b69cc9 100644 --- a/tests/ui/lint/lint-ctypes-enum.stderr +++ b/tests/ui/lint/lint-ctypes-enum.stderr @@ -1,13 +1,13 @@ error: `extern` block uses type `U`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:60:13 + --> $DIR/lint-ctypes-enum.rs:69:14 | -LL | fn uf(x: U); - | ^ not FFI-safe +LL | fn uf(x: U); + | ^ not FFI-safe | = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum = note: enum has no representation hint note: the type is defined here - --> $DIR/lint-ctypes-enum.rs:9:1 + --> $DIR/lint-ctypes-enum.rs:10:1 | LL | enum U { | ^^^^^^ @@ -18,75 +18,233 @@ LL | #![deny(improper_ctypes)] | ^^^^^^^^^^^^^^^ error: `extern` block uses type `B`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:61:13 + --> $DIR/lint-ctypes-enum.rs:70:14 | -LL | fn bf(x: B); - | ^ not FFI-safe +LL | fn bf(x: B); + | ^ not FFI-safe | = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum = note: enum has no representation hint note: the type is defined here - --> $DIR/lint-ctypes-enum.rs:12:1 + --> $DIR/lint-ctypes-enum.rs:13:1 | LL | enum B { | ^^^^^^ error: `extern` block uses type `T`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:62:13 + --> $DIR/lint-ctypes-enum.rs:71:14 | -LL | fn tf(x: T); - | ^ not FFI-safe +LL | fn tf(x: T); + | ^ not FFI-safe | = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum = note: enum has no representation hint note: the type is defined here - --> $DIR/lint-ctypes-enum.rs:16:1 + --> $DIR/lint-ctypes-enum.rs:17:1 | LL | enum T { | ^^^^^^ error: `extern` block uses type `u128`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:74:23 + --> $DIR/lint-ctypes-enum.rs:83:31 | -LL | fn nonzero_u128(x: Option>); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe +LL | fn option_nonzero_u128(x: Option>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe | = note: 128-bit integers don't currently have a known stable ABI error: `extern` block uses type `i128`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:81:23 + --> $DIR/lint-ctypes-enum.rs:90:31 | -LL | fn nonzero_i128(x: Option>); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe +LL | fn option_nonzero_i128(x: Option>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe | = note: 128-bit integers don't currently have a known stable ABI error: `extern` block uses type `Option>>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:86:28 + --> $DIR/lint-ctypes-enum.rs:95:36 | -LL | fn transparent_union(x: Option>>); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe +LL | fn option_transparent_union(x: Option>>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe | = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum = note: enum has no representation hint error: `extern` block uses type `Option>>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:88:20 + --> $DIR/lint-ctypes-enum.rs:97:28 | -LL | fn repr_rust(x: Option>>); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe +LL | fn option_repr_rust(x: Option>>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe | = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum = note: enum has no representation hint -error: `extern` block uses type `Result<(), NonZero>`, which is not FFI-safe - --> $DIR/lint-ctypes-enum.rs:89:20 +error: `extern` block uses type `u128`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:107:33 + | +LL | fn result_nonzero_u128_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = note: 128-bit integers don't currently have a known stable ABI + +error: `extern` block uses type `i128`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:114:33 + | +LL | fn result_nonzero_i128_t(x: Result, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = note: 128-bit integers don't currently have a known stable ABI + +error: `extern` block uses type `Result>, ()>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:119:38 + | +LL | fn result_transparent_union_t(x: Result>, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result>, ()>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:121:30 + | +LL | fn result_repr_rust_t(x: Result>, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, U>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:125:51 + | +LL | fn result_1zst_exhaustive_single_variant_t(x: Result, U>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, B>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:127:53 + | +LL | fn result_1zst_exhaustive_multiple_variant_t(x: Result, B>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, NonExhaustive>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:129:51 + | +LL | fn result_1zst_non_exhaustive_no_variant_t(x: Result, NonExhaustive>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result, Field>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:132:49 + | +LL | fn result_1zst_exhaustive_single_field_t(x: Result, Field>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result>, ()>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:134:30 + | +LL | fn result_cascading_t(x: Result>, ()>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `u128`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:145:33 + | +LL | fn result_nonzero_u128_e(x: Result<(), num::NonZero>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = note: 128-bit integers don't currently have a known stable ABI + +error: `extern` block uses type `i128`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:152:33 + | +LL | fn result_nonzero_i128_e(x: Result<(), num::NonZero>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = note: 128-bit integers don't currently have a known stable ABI + +error: `extern` block uses type `Result<(), TransparentUnion>>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:157:38 + | +LL | fn result_transparent_union_e(x: Result<(), TransparentUnion>>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), Rust>>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:159:30 + | +LL | fn result_repr_rust_e(x: Result<(), Rust>>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:163:51 + | +LL | fn result_1zst_exhaustive_single_variant_e(x: Result>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:165:53 + | +LL | fn result_1zst_exhaustive_multiple_variant_e(x: Result>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:167:51 + | +LL | fn result_1zst_non_exhaustive_no_variant_e(x: Result>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:170:49 + | +LL | fn result_1zst_exhaustive_single_field_e(x: Result>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), Result<(), NonZero>>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:172:30 + | +LL | fn result_cascading_e(x: Result<(), Result<(), num::NonZero>>); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum + = note: enum has no representation hint + +error: `extern` block uses type `Result<(), ()>`, which is not FFI-safe + --> $DIR/lint-ctypes-enum.rs:174:27 | -LL | fn no_result(x: Result<(), num::NonZero>); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not FFI-safe +LL | fn result_unit_t_e(x: Result<(), ()>); + | ^^^^^^^^^^^^^^ not FFI-safe | = help: consider adding a `#[repr(C)]`, `#[repr(transparent)]`, or integer `#[repr(...)]` attribute to this enum = note: enum has no representation hint -error: aborting due to 8 previous errors +error: aborting due to 26 previous errors diff --git a/tests/ui/macros/macro-comma-support-rpass.rs b/tests/ui/macros/macro-comma-support-rpass.rs index 724bd5af2dcff..5a4bac70b1ce6 100644 --- a/tests/ui/macros/macro-comma-support-rpass.rs +++ b/tests/ui/macros/macro-comma-support-rpass.rs @@ -51,6 +51,7 @@ fn assert_ne() { } #[test] +#[allow(unexpected_cfgs)] fn cfg() { let _ = cfg!(pants); let _ = cfg!(pants,); diff --git a/tests/ui/macros/macro-meta-items.rs b/tests/ui/macros/macro-meta-items.rs index 10c57fba24483..35ef10fef5a84 100644 --- a/tests/ui/macros/macro-meta-items.rs +++ b/tests/ui/macros/macro-meta-items.rs @@ -1,6 +1,7 @@ //@ run-pass +//@ compile-flags: --cfg foo --check-cfg=cfg(foo) + #![allow(dead_code)] -//@ compile-flags: --cfg foo macro_rules! compiles_fine { ($at:meta) => { @@ -16,7 +17,7 @@ macro_rules! emit { } // item -compiles_fine!(bar); +compiles_fine!(FALSE); emit!(foo); fn foo() { @@ -25,7 +26,7 @@ fn foo() { pub fn main() { // statement - compiles_fine!(baz); - emit!(baz); + compiles_fine!(FALSE); + emit!(FALSE); println!("{}", MISTYPED); } diff --git a/tests/ui/macros/macro-with-attrs1.rs b/tests/ui/macros/macro-with-attrs1.rs index cfd5691fe94bd..a3030e744db71 100644 --- a/tests/ui/macros/macro-with-attrs1.rs +++ b/tests/ui/macros/macro-with-attrs1.rs @@ -1,5 +1,5 @@ //@ run-pass -//@ compile-flags: --cfg foo +//@ compile-flags: --cfg foo --check-cfg=cfg(foo) #[cfg(foo)] diff --git a/tests/ui/macros/syntax-extension-cfg.rs b/tests/ui/macros/syntax-extension-cfg.rs index 56d869f3dc121..6e7f3e2ed5d44 100644 --- a/tests/ui/macros/syntax-extension-cfg.rs +++ b/tests/ui/macros/syntax-extension-cfg.rs @@ -1,6 +1,6 @@ //@ run-pass //@ compile-flags: --cfg foo --cfg qux="foo" - +//@ compile-flags: --check-cfg=cfg(foo) --check-cfg=cfg(qux,values("foo")) pub fn main() { // check @@ -14,11 +14,11 @@ pub fn main() { if cfg!(not(all(foo, qux="foo"))) { panic!() } if cfg!(all(not(all(foo, qux="foo")))) { panic!() } - if cfg!(not_a_cfg) { panic!() } - if cfg!(all(not_a_cfg, foo, qux="foo")) { panic!() } - if cfg!(all(not_a_cfg, foo, qux="foo")) { panic!() } - if ! cfg!(any(not_a_cfg, foo)) { panic!() } + if cfg!(FALSE) { panic!() } + if cfg!(all(FALSE, foo, qux="foo")) { panic!() } + if cfg!(all(FALSE, foo, qux="foo")) { panic!() } + if ! cfg!(any(FALSE, foo)) { panic!() } - if ! cfg!(not(not_a_cfg)) { panic!() } - if ! cfg!(all(not(not_a_cfg), foo, qux="foo")) { panic!() } + if ! cfg!(not(FALSE)) { panic!() } + if ! cfg!(all(not(FALSE), foo, qux="foo")) { panic!() } } diff --git a/tests/ui/match/match-range-fail-2.rs b/tests/ui/match/match-range-fail-2.rs index 4489cf1ab1f2b..524e84323e7cd 100644 --- a/tests/ui/match/match-range-fail-2.rs +++ b/tests/ui/match/match-range-fail-2.rs @@ -1,5 +1,3 @@ -#![feature(exclusive_range_pattern)] - fn main() { match 5 { 6 ..= 1 => { } diff --git a/tests/ui/match/match-range-fail-2.stderr b/tests/ui/match/match-range-fail-2.stderr index 089fa851f97c2..8bad2e6e1470f 100644 --- a/tests/ui/match/match-range-fail-2.stderr +++ b/tests/ui/match/match-range-fail-2.stderr @@ -1,17 +1,17 @@ error[E0030]: lower range bound must be less than or equal to upper - --> $DIR/match-range-fail-2.rs:5:9 + --> $DIR/match-range-fail-2.rs:3:9 | LL | 6 ..= 1 => { } | ^^^^^^^ lower bound larger than upper bound error[E0579]: lower range bound must be less than upper - --> $DIR/match-range-fail-2.rs:11:9 + --> $DIR/match-range-fail-2.rs:9:9 | LL | 0 .. 0 => { } | ^^^^^^ error[E0030]: lower range bound must be less than or equal to upper - --> $DIR/match-range-fail-2.rs:17:9 + --> $DIR/match-range-fail-2.rs:15:9 | LL | 0xFFFF_FFFF_FFFF_FFFF ..= 1 => { } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ lower bound larger than upper bound diff --git a/tests/ui/match/validate-range-endpoints.rs b/tests/ui/match/validate-range-endpoints.rs index 31d5bc3b65d50..46d4239886d3c 100644 --- a/tests/ui/match/validate-range-endpoints.rs +++ b/tests/ui/match/validate-range-endpoints.rs @@ -1,4 +1,3 @@ -#![feature(exclusive_range_pattern)] #![feature(inline_const_pat)] #![allow(overlapping_range_endpoints)] diff --git a/tests/ui/match/validate-range-endpoints.stderr b/tests/ui/match/validate-range-endpoints.stderr index b3b4066cd9158..2d0538804a378 100644 --- a/tests/ui/match/validate-range-endpoints.stderr +++ b/tests/ui/match/validate-range-endpoints.stderr @@ -1,59 +1,59 @@ error: literal out of range for `u8` - --> $DIR/validate-range-endpoints.rs:8:12 + --> $DIR/validate-range-endpoints.rs:7:12 | LL | 1..257 => {} | ^^^ this value does not fit into the type `u8` whose range is `0..=255` error: literal out of range for `u8` - --> $DIR/validate-range-endpoints.rs:10:13 + --> $DIR/validate-range-endpoints.rs:9:13 | LL | 1..=256 => {} | ^^^ this value does not fit into the type `u8` whose range is `0..=255` error[E0030]: lower range bound must be less than or equal to upper - --> $DIR/validate-range-endpoints.rs:19:9 + --> $DIR/validate-range-endpoints.rs:18:9 | LL | 1..=TOO_BIG => {} | ^^^^^^^^^^^ lower bound larger than upper bound error[E0030]: lower range bound must be less than or equal to upper - --> $DIR/validate-range-endpoints.rs:21:9 + --> $DIR/validate-range-endpoints.rs:20:9 | LL | 1..=const { 256 } => {} | ^^^^^^^^^^^^^^^^^ lower bound larger than upper bound error: literal out of range for `u64` - --> $DIR/validate-range-endpoints.rs:27:32 + --> $DIR/validate-range-endpoints.rs:26:32 | LL | 10000000000000000000..=99999999999999999999 => {} | ^^^^^^^^^^^^^^^^^^^^ this value does not fit into the type `u64` whose range is `0..=18446744073709551615` error: literal out of range for `i8` - --> $DIR/validate-range-endpoints.rs:33:12 + --> $DIR/validate-range-endpoints.rs:32:12 | LL | 0..129 => {} | ^^^ this value does not fit into the type `i8` whose range is `-128..=127` error: literal out of range for `i8` - --> $DIR/validate-range-endpoints.rs:35:13 + --> $DIR/validate-range-endpoints.rs:34:13 | LL | 0..=128 => {} | ^^^ this value does not fit into the type `i8` whose range is `-128..=127` error: literal out of range for `i8` - --> $DIR/validate-range-endpoints.rs:37:9 + --> $DIR/validate-range-endpoints.rs:36:9 | LL | -129..0 => {} | ^^^^ this value does not fit into the type `i8` whose range is `-128..=127` error: literal out of range for `i8` - --> $DIR/validate-range-endpoints.rs:39:9 + --> $DIR/validate-range-endpoints.rs:38:9 | LL | -10000..=-20 => {} | ^^^^^^ this value does not fit into the type `i8` whose range is `-128..=127` error[E0004]: non-exhaustive patterns: `i8::MIN..=-17_i8` and `1_i8..=i8::MAX` not covered - --> $DIR/validate-range-endpoints.rs:50:11 + --> $DIR/validate-range-endpoints.rs:49:11 | LL | match 0i8 { | ^^^ patterns `i8::MIN..=-17_i8` and `1_i8..=i8::MAX` not covered @@ -66,7 +66,7 @@ LL + i8::MIN..=-17_i8 | 1_i8..=i8::MAX => todo!() | error[E0004]: non-exhaustive patterns: `i8::MIN..=-17_i8` not covered - --> $DIR/validate-range-endpoints.rs:54:11 + --> $DIR/validate-range-endpoints.rs:53:11 | LL | match 0i8 { | ^^^ pattern `i8::MIN..=-17_i8` not covered diff --git a/tests/ui/methods/method-lookup-order.rs b/tests/ui/methods/method-lookup-order.rs index 08ad6483d089e..f794e5a72415e 100644 --- a/tests/ui/methods/method-lookup-order.rs +++ b/tests/ui/methods/method-lookup-order.rs @@ -18,6 +18,9 @@ //@ revisions: b00001 b00010 b00011 b00100 b00101 b00110 b00111 b01000 b01001 b01100 b01101 b10000 b10001 b10010 b10011 b10101 b10111 b11000 b11001 b11101 +//@ compile-flags: --check-cfg=cfg(inherent_mut,bar_for_foo,mutbar_for_foo) +//@ compile-flags: --check-cfg=cfg(valbar_for_et_foo,valbar_for_etmut_foo) + //@[b00001]compile-flags: --cfg inherent_mut //@[b00010]compile-flags: --cfg bar_for_foo //@[b00011]compile-flags: --cfg inherent_mut --cfg bar_for_foo diff --git a/tests/ui/mir/mir_match_test.rs b/tests/ui/mir/mir_match_test.rs index 0da8522f2181a..ad54a91646ab0 100644 --- a/tests/ui/mir/mir_match_test.rs +++ b/tests/ui/mir/mir_match_test.rs @@ -1,4 +1,3 @@ -#![feature(exclusive_range_pattern)] #![allow(overlapping_range_endpoints)] #![allow(non_contiguous_range_endpoints)] diff --git a/tests/ui/parser/attribute/attr-unquoted-ident.fixed b/tests/ui/parser/attribute/attr-unquoted-ident.fixed index 636508b5615aa..bc861ef69fb7c 100644 --- a/tests/ui/parser/attribute/attr-unquoted-ident.fixed +++ b/tests/ui/parser/attribute/attr-unquoted-ident.fixed @@ -1,6 +1,8 @@ //@ compile-flags: -Zdeduplicate-diagnostics=yes //@ run-rustfix +#![allow(unexpected_cfgs)] + fn main() { #[cfg(key="foo")] //~^ ERROR expected unsuffixed literal, found `foo` diff --git a/tests/ui/parser/attribute/attr-unquoted-ident.rs b/tests/ui/parser/attribute/attr-unquoted-ident.rs index 9b9a9f7840352..8bdb8605ebb4f 100644 --- a/tests/ui/parser/attribute/attr-unquoted-ident.rs +++ b/tests/ui/parser/attribute/attr-unquoted-ident.rs @@ -1,6 +1,8 @@ //@ compile-flags: -Zdeduplicate-diagnostics=yes //@ run-rustfix +#![allow(unexpected_cfgs)] + fn main() { #[cfg(key=foo)] //~^ ERROR expected unsuffixed literal, found `foo` diff --git a/tests/ui/parser/attribute/attr-unquoted-ident.stderr b/tests/ui/parser/attribute/attr-unquoted-ident.stderr index bc028f39be61c..99484a51110f1 100644 --- a/tests/ui/parser/attribute/attr-unquoted-ident.stderr +++ b/tests/ui/parser/attribute/attr-unquoted-ident.stderr @@ -1,5 +1,5 @@ error: expected unsuffixed literal, found `foo` - --> $DIR/attr-unquoted-ident.rs:5:15 + --> $DIR/attr-unquoted-ident.rs:7:15 | LL | #[cfg(key=foo)] | ^^^ @@ -10,7 +10,7 @@ LL | #[cfg(key="foo")] | + + error: expected unsuffixed literal, found `foo` - --> $DIR/attr-unquoted-ident.rs:11:15 + --> $DIR/attr-unquoted-ident.rs:13:15 | LL | #[cfg(key=foo bar baz)] | ^^^ diff --git a/tests/ui/parser/issues/issue-63115-range-pat-interpolated.rs b/tests/ui/parser/issues/issue-63115-range-pat-interpolated.rs index d1a5f32b95464..9a6bd4442e563 100644 --- a/tests/ui/parser/issues/issue-63115-range-pat-interpolated.rs +++ b/tests/ui/parser/issues/issue-63115-range-pat-interpolated.rs @@ -1,7 +1,5 @@ //@ check-pass -#![feature(exclusive_range_pattern)] - #![allow(ellipsis_inclusive_range_patterns)] fn main() { diff --git a/tests/ui/parser/recover/recover-range-pats.rs b/tests/ui/parser/recover/recover-range-pats.rs index 3dc525cd6e104..42cd69fd9594d 100644 --- a/tests/ui/parser/recover/recover-range-pats.rs +++ b/tests/ui/parser/recover/recover-range-pats.rs @@ -3,7 +3,6 @@ // 1. Things parse as they should. // 2. Or at least we have parser recovery if they don't. -#![feature(exclusive_range_pattern)] #![deny(ellipsis_inclusive_range_patterns)] fn main() {} diff --git a/tests/ui/parser/recover/recover-range-pats.stderr b/tests/ui/parser/recover/recover-range-pats.stderr index 2c0baf7e5f80b..e0ea8ec24dcf2 100644 --- a/tests/ui/parser/recover/recover-range-pats.stderr +++ b/tests/ui/parser/recover/recover-range-pats.stderr @@ -1,47 +1,47 @@ error: float literals must have an integer part - --> $DIR/recover-range-pats.rs:21:12 + --> $DIR/recover-range-pats.rs:20:12 | LL | if let .0..Y = 0 {} | ^^ help: must have an integer part: `0.0` error: float literals must have an integer part - --> $DIR/recover-range-pats.rs:23:16 + --> $DIR/recover-range-pats.rs:22:16 | LL | if let X.. .0 = 0 {} | ^^ help: must have an integer part: `0.0` error: float literals must have an integer part - --> $DIR/recover-range-pats.rs:34:12 + --> $DIR/recover-range-pats.rs:33:12 | LL | if let .0..=Y = 0 {} | ^^ help: must have an integer part: `0.0` error: float literals must have an integer part - --> $DIR/recover-range-pats.rs:36:16 + --> $DIR/recover-range-pats.rs:35:16 | LL | if let X..=.0 = 0 {} | ^^ help: must have an integer part: `0.0` error: float literals must have an integer part - --> $DIR/recover-range-pats.rs:59:12 + --> $DIR/recover-range-pats.rs:58:12 | LL | if let .0...Y = 0 {} | ^^ help: must have an integer part: `0.0` error: float literals must have an integer part - --> $DIR/recover-range-pats.rs:63:17 + --> $DIR/recover-range-pats.rs:62:17 | LL | if let X... .0 = 0 {} | ^^ help: must have an integer part: `0.0` error: float literals must have an integer part - --> $DIR/recover-range-pats.rs:74:12 + --> $DIR/recover-range-pats.rs:73:12 | LL | if let .0.. = 0 {} | ^^ help: must have an integer part: `0.0` error[E0586]: inclusive range with no end - --> $DIR/recover-range-pats.rs:80:13 + --> $DIR/recover-range-pats.rs:79:13 | LL | if let 0..= = 0 {} | ^^^ help: use `..` instead @@ -49,7 +49,7 @@ LL | if let 0..= = 0 {} = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) error[E0586]: inclusive range with no end - --> $DIR/recover-range-pats.rs:81:13 + --> $DIR/recover-range-pats.rs:80:13 | LL | if let X..= = 0 {} | ^^^ help: use `..` instead @@ -57,7 +57,7 @@ LL | if let X..= = 0 {} = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) error[E0586]: inclusive range with no end - --> $DIR/recover-range-pats.rs:82:16 + --> $DIR/recover-range-pats.rs:81:16 | LL | if let true..= = 0 {} | ^^^ help: use `..` instead @@ -65,13 +65,13 @@ LL | if let true..= = 0 {} = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) error: float literals must have an integer part - --> $DIR/recover-range-pats.rs:84:12 + --> $DIR/recover-range-pats.rs:83:12 | LL | if let .0..= = 0 {} | ^^ help: must have an integer part: `0.0` error[E0586]: inclusive range with no end - --> $DIR/recover-range-pats.rs:84:14 + --> $DIR/recover-range-pats.rs:83:14 | LL | if let .0..= = 0 {} | ^^^ help: use `..` instead @@ -79,7 +79,7 @@ LL | if let .0..= = 0 {} = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) error[E0586]: inclusive range with no end - --> $DIR/recover-range-pats.rs:90:13 + --> $DIR/recover-range-pats.rs:89:13 | LL | if let 0... = 0 {} | ^^^ help: use `..` instead @@ -87,7 +87,7 @@ LL | if let 0... = 0 {} = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) error[E0586]: inclusive range with no end - --> $DIR/recover-range-pats.rs:91:13 + --> $DIR/recover-range-pats.rs:90:13 | LL | if let X... = 0 {} | ^^^ help: use `..` instead @@ -95,7 +95,7 @@ LL | if let X... = 0 {} = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) error[E0586]: inclusive range with no end - --> $DIR/recover-range-pats.rs:92:16 + --> $DIR/recover-range-pats.rs:91:16 | LL | if let true... = 0 {} | ^^^ help: use `..` instead @@ -103,13 +103,13 @@ LL | if let true... = 0 {} = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) error: float literals must have an integer part - --> $DIR/recover-range-pats.rs:94:12 + --> $DIR/recover-range-pats.rs:93:12 | LL | if let .0... = 0 {} | ^^ help: must have an integer part: `0.0` error[E0586]: inclusive range with no end - --> $DIR/recover-range-pats.rs:94:14 + --> $DIR/recover-range-pats.rs:93:14 | LL | if let .0... = 0 {} | ^^^ help: use `..` instead @@ -117,49 +117,49 @@ LL | if let .0... = 0 {} = note: inclusive ranges must be bounded at the end (`..=b` or `a..=b`) error: float literals must have an integer part - --> $DIR/recover-range-pats.rs:104:15 + --> $DIR/recover-range-pats.rs:103:15 | LL | if let .. .0 = 0 {} | ^^ help: must have an integer part: `0.0` error: float literals must have an integer part - --> $DIR/recover-range-pats.rs:114:15 + --> $DIR/recover-range-pats.rs:113:15 | LL | if let ..=.0 = 0 {} | ^^ help: must have an integer part: `0.0` error: range-to patterns with `...` are not allowed - --> $DIR/recover-range-pats.rs:120:12 + --> $DIR/recover-range-pats.rs:119:12 | LL | if let ...3 = 0 {} | ^^^ help: use `..=` instead error: range-to patterns with `...` are not allowed - --> $DIR/recover-range-pats.rs:122:12 + --> $DIR/recover-range-pats.rs:121:12 | LL | if let ...Y = 0 {} | ^^^ help: use `..=` instead error: range-to patterns with `...` are not allowed - --> $DIR/recover-range-pats.rs:124:12 + --> $DIR/recover-range-pats.rs:123:12 | LL | if let ...true = 0 {} | ^^^ help: use `..=` instead error: float literals must have an integer part - --> $DIR/recover-range-pats.rs:127:15 + --> $DIR/recover-range-pats.rs:126:15 | LL | if let ....3 = 0 {} | ^^ help: must have an integer part: `0.3` error: range-to patterns with `...` are not allowed - --> $DIR/recover-range-pats.rs:127:12 + --> $DIR/recover-range-pats.rs:126:12 | LL | if let ....3 = 0 {} | ^^^ help: use `..=` instead error: range-to patterns with `...` are not allowed - --> $DIR/recover-range-pats.rs:153:17 + --> $DIR/recover-range-pats.rs:152:17 | LL | let ...$e; | ^^^ help: use `..=` instead @@ -170,7 +170,7 @@ LL | mac!(0); = note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0586]: inclusive range with no end - --> $DIR/recover-range-pats.rs:160:19 + --> $DIR/recover-range-pats.rs:159:19 | LL | let $e...; | ^^^ help: use `..` instead @@ -182,7 +182,7 @@ LL | mac!(0); = note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0586]: inclusive range with no end - --> $DIR/recover-range-pats.rs:162:19 + --> $DIR/recover-range-pats.rs:161:19 | LL | let $e..=; | ^^^ help: use `..` instead @@ -194,7 +194,7 @@ LL | mac!(0); = note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info) error: `...` range patterns are deprecated - --> $DIR/recover-range-pats.rs:41:13 + --> $DIR/recover-range-pats.rs:40:13 | LL | if let 0...3 = 0 {} | ^^^ help: use `..=` for an inclusive range @@ -202,13 +202,13 @@ LL | if let 0...3 = 0 {} = warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2021! = note: for more information, see note: the lint level is defined here - --> $DIR/recover-range-pats.rs:7:9 + --> $DIR/recover-range-pats.rs:6:9 | LL | #![deny(ellipsis_inclusive_range_patterns)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: `...` range patterns are deprecated - --> $DIR/recover-range-pats.rs:44:13 + --> $DIR/recover-range-pats.rs:43:13 | LL | if let 0...Y = 0 {} | ^^^ help: use `..=` for an inclusive range @@ -217,7 +217,7 @@ LL | if let 0...Y = 0 {} = note: for more information, see error: `...` range patterns are deprecated - --> $DIR/recover-range-pats.rs:47:13 + --> $DIR/recover-range-pats.rs:46:13 | LL | if let X...3 = 0 {} | ^^^ help: use `..=` for an inclusive range @@ -226,7 +226,7 @@ LL | if let X...3 = 0 {} = note: for more information, see error: `...` range patterns are deprecated - --> $DIR/recover-range-pats.rs:50:13 + --> $DIR/recover-range-pats.rs:49:13 | LL | if let X...Y = 0 {} | ^^^ help: use `..=` for an inclusive range @@ -235,7 +235,7 @@ LL | if let X...Y = 0 {} = note: for more information, see error: `...` range patterns are deprecated - --> $DIR/recover-range-pats.rs:53:16 + --> $DIR/recover-range-pats.rs:52:16 | LL | if let true...Y = 0 {} | ^^^ help: use `..=` for an inclusive range @@ -244,7 +244,7 @@ LL | if let true...Y = 0 {} = note: for more information, see error: `...` range patterns are deprecated - --> $DIR/recover-range-pats.rs:56:13 + --> $DIR/recover-range-pats.rs:55:13 | LL | if let X...true = 0 {} | ^^^ help: use `..=` for an inclusive range @@ -253,7 +253,7 @@ LL | if let X...true = 0 {} = note: for more information, see error: `...` range patterns are deprecated - --> $DIR/recover-range-pats.rs:59:14 + --> $DIR/recover-range-pats.rs:58:14 | LL | if let .0...Y = 0 {} | ^^^ help: use `..=` for an inclusive range @@ -262,7 +262,7 @@ LL | if let .0...Y = 0 {} = note: for more information, see error: `...` range patterns are deprecated - --> $DIR/recover-range-pats.rs:63:13 + --> $DIR/recover-range-pats.rs:62:13 | LL | if let X... .0 = 0 {} | ^^^ help: use `..=` for an inclusive range @@ -271,7 +271,7 @@ LL | if let X... .0 = 0 {} = note: for more information, see error: `...` range patterns are deprecated - --> $DIR/recover-range-pats.rs:138:20 + --> $DIR/recover-range-pats.rs:137:20 | LL | let $e1...$e2; | ^^^ help: use `..=` for an inclusive range @@ -284,7 +284,7 @@ LL | mac2!(0, 1); = note: this error originates in the macro `mac2` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/recover-range-pats.rs:19:12 + --> $DIR/recover-range-pats.rs:18:12 | LL | if let true..Y = 0 {} | ^^^^ - this is of type `u8` @@ -292,7 +292,7 @@ LL | if let true..Y = 0 {} | this is of type `bool` but it should be `char` or numeric error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/recover-range-pats.rs:20:15 + --> $DIR/recover-range-pats.rs:19:15 | LL | if let X..true = 0 {} | - ^^^^ this is of type `bool` but it should be `char` or numeric @@ -300,7 +300,7 @@ LL | if let X..true = 0 {} | this is of type `u8` error[E0308]: mismatched types - --> $DIR/recover-range-pats.rs:21:12 + --> $DIR/recover-range-pats.rs:20:12 | LL | if let .0..Y = 0 {} | ^^ - - this expression has type `{integer}` @@ -309,7 +309,7 @@ LL | if let .0..Y = 0 {} | expected integer, found floating-point number error[E0308]: mismatched types - --> $DIR/recover-range-pats.rs:23:16 + --> $DIR/recover-range-pats.rs:22:16 | LL | if let X.. .0 = 0 {} | - ^^ - this expression has type `u8` @@ -321,7 +321,7 @@ LL | if let X.. .0 = 0 {} found type `{float}` error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/recover-range-pats.rs:32:12 + --> $DIR/recover-range-pats.rs:31:12 | LL | if let true..=Y = 0 {} | ^^^^ - this is of type `u8` @@ -329,7 +329,7 @@ LL | if let true..=Y = 0 {} | this is of type `bool` but it should be `char` or numeric error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/recover-range-pats.rs:33:16 + --> $DIR/recover-range-pats.rs:32:16 | LL | if let X..=true = 0 {} | - ^^^^ this is of type `bool` but it should be `char` or numeric @@ -337,7 +337,7 @@ LL | if let X..=true = 0 {} | this is of type `u8` error[E0308]: mismatched types - --> $DIR/recover-range-pats.rs:34:12 + --> $DIR/recover-range-pats.rs:33:12 | LL | if let .0..=Y = 0 {} | ^^ - - this expression has type `{integer}` @@ -346,7 +346,7 @@ LL | if let .0..=Y = 0 {} | expected integer, found floating-point number error[E0308]: mismatched types - --> $DIR/recover-range-pats.rs:36:16 + --> $DIR/recover-range-pats.rs:35:16 | LL | if let X..=.0 = 0 {} | - ^^ - this expression has type `u8` @@ -358,7 +358,7 @@ LL | if let X..=.0 = 0 {} found type `{float}` error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/recover-range-pats.rs:53:12 + --> $DIR/recover-range-pats.rs:52:12 | LL | if let true...Y = 0 {} | ^^^^ - this is of type `u8` @@ -366,7 +366,7 @@ LL | if let true...Y = 0 {} | this is of type `bool` but it should be `char` or numeric error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/recover-range-pats.rs:56:16 + --> $DIR/recover-range-pats.rs:55:16 | LL | if let X...true = 0 {} | - ^^^^ this is of type `bool` but it should be `char` or numeric @@ -374,7 +374,7 @@ LL | if let X...true = 0 {} | this is of type `u8` error[E0308]: mismatched types - --> $DIR/recover-range-pats.rs:59:12 + --> $DIR/recover-range-pats.rs:58:12 | LL | if let .0...Y = 0 {} | ^^ - - this expression has type `{integer}` @@ -383,7 +383,7 @@ LL | if let .0...Y = 0 {} | expected integer, found floating-point number error[E0308]: mismatched types - --> $DIR/recover-range-pats.rs:63:17 + --> $DIR/recover-range-pats.rs:62:17 | LL | if let X... .0 = 0 {} | - ^^ - this expression has type `u8` @@ -395,13 +395,13 @@ LL | if let X... .0 = 0 {} found type `{float}` error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/recover-range-pats.rs:72:12 + --> $DIR/recover-range-pats.rs:71:12 | LL | if let true.. = 0 {} | ^^^^ this is of type `bool` but it should be `char` or numeric error[E0308]: mismatched types - --> $DIR/recover-range-pats.rs:74:12 + --> $DIR/recover-range-pats.rs:73:12 | LL | if let .0.. = 0 {} | ^^ - this expression has type `{integer}` @@ -409,13 +409,13 @@ LL | if let .0.. = 0 {} | expected integer, found floating-point number error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/recover-range-pats.rs:82:12 + --> $DIR/recover-range-pats.rs:81:12 | LL | if let true..= = 0 {} | ^^^^ this is of type `bool` but it should be `char` or numeric error[E0308]: mismatched types - --> $DIR/recover-range-pats.rs:84:12 + --> $DIR/recover-range-pats.rs:83:12 | LL | if let .0..= = 0 {} | ^^ - this expression has type `{integer}` @@ -423,13 +423,13 @@ LL | if let .0..= = 0 {} | expected integer, found floating-point number error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/recover-range-pats.rs:92:12 + --> $DIR/recover-range-pats.rs:91:12 | LL | if let true... = 0 {} | ^^^^ this is of type `bool` but it should be `char` or numeric error[E0308]: mismatched types - --> $DIR/recover-range-pats.rs:94:12 + --> $DIR/recover-range-pats.rs:93:12 | LL | if let .0... = 0 {} | ^^ - this expression has type `{integer}` @@ -437,13 +437,13 @@ LL | if let .0... = 0 {} | expected integer, found floating-point number error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/recover-range-pats.rs:102:14 + --> $DIR/recover-range-pats.rs:101:14 | LL | if let ..true = 0 {} | ^^^^ this is of type `bool` but it should be `char` or numeric error[E0308]: mismatched types - --> $DIR/recover-range-pats.rs:104:15 + --> $DIR/recover-range-pats.rs:103:15 | LL | if let .. .0 = 0 {} | ^^ - this expression has type `{integer}` @@ -451,13 +451,13 @@ LL | if let .. .0 = 0 {} | expected integer, found floating-point number error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/recover-range-pats.rs:112:15 + --> $DIR/recover-range-pats.rs:111:15 | LL | if let ..=true = 0 {} | ^^^^ this is of type `bool` but it should be `char` or numeric error[E0308]: mismatched types - --> $DIR/recover-range-pats.rs:114:15 + --> $DIR/recover-range-pats.rs:113:15 | LL | if let ..=.0 = 0 {} | ^^ - this expression has type `{integer}` @@ -465,13 +465,13 @@ LL | if let ..=.0 = 0 {} | expected integer, found floating-point number error[E0029]: only `char` and numeric types are allowed in range patterns - --> $DIR/recover-range-pats.rs:124:15 + --> $DIR/recover-range-pats.rs:123:15 | LL | if let ...true = 0 {} | ^^^^ this is of type `bool` but it should be `char` or numeric error[E0308]: mismatched types - --> $DIR/recover-range-pats.rs:127:15 + --> $DIR/recover-range-pats.rs:126:15 | LL | if let ....3 = 0 {} | ^^ - this expression has type `{integer}` @@ -479,7 +479,7 @@ LL | if let ....3 = 0 {} | expected integer, found floating-point number error[E0005]: refutable pattern in local binding - --> $DIR/recover-range-pats.rs:136:17 + --> $DIR/recover-range-pats.rs:135:17 | LL | let $e1..$e2; | ^^^^^^^^ patterns `i32::MIN..=-1_i32` and `1_i32..=i32::MAX` not covered @@ -493,7 +493,7 @@ LL | mac2!(0, 1); = note: this error originates in the macro `mac2` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0005]: refutable pattern in local binding - --> $DIR/recover-range-pats.rs:138:17 + --> $DIR/recover-range-pats.rs:137:17 | LL | let $e1...$e2; | ^^^^^^^^^ patterns `i32::MIN..=-1_i32` and `2_i32..=i32::MAX` not covered @@ -507,7 +507,7 @@ LL | mac2!(0, 1); = note: this error originates in the macro `mac2` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0005]: refutable pattern in local binding - --> $DIR/recover-range-pats.rs:142:17 + --> $DIR/recover-range-pats.rs:141:17 | LL | let $e1..=$e2; | ^^^^^^^^^ patterns `i32::MIN..=-1_i32` and `2_i32..=i32::MAX` not covered @@ -521,7 +521,7 @@ LL | mac2!(0, 1); = note: this error originates in the macro `mac2` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0005]: refutable pattern in local binding - --> $DIR/recover-range-pats.rs:151:17 + --> $DIR/recover-range-pats.rs:150:17 | LL | let ..$e; | ^^^^ pattern `0_i32..=i32::MAX` not covered @@ -535,7 +535,7 @@ LL | mac!(0); = note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0005]: refutable pattern in local binding - --> $DIR/recover-range-pats.rs:153:17 + --> $DIR/recover-range-pats.rs:152:17 | LL | let ...$e; | ^^^^^ pattern `1_i32..=i32::MAX` not covered @@ -549,7 +549,7 @@ LL | mac!(0); = note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0005]: refutable pattern in local binding - --> $DIR/recover-range-pats.rs:156:17 + --> $DIR/recover-range-pats.rs:155:17 | LL | let ..=$e; | ^^^^^ pattern `1_i32..=i32::MAX` not covered @@ -563,7 +563,7 @@ LL | mac!(0); = note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0005]: refutable pattern in local binding - --> $DIR/recover-range-pats.rs:158:17 + --> $DIR/recover-range-pats.rs:157:17 | LL | let $e..; | ^^^^ pattern `i32::MIN..=-1_i32` not covered @@ -577,7 +577,7 @@ LL | mac!(0); = note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0005]: refutable pattern in local binding - --> $DIR/recover-range-pats.rs:160:17 + --> $DIR/recover-range-pats.rs:159:17 | LL | let $e...; | ^^^^^ pattern `i32::MIN..=-1_i32` not covered @@ -591,7 +591,7 @@ LL | mac!(0); = note: this error originates in the macro `mac` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0005]: refutable pattern in local binding - --> $DIR/recover-range-pats.rs:162:17 + --> $DIR/recover-range-pats.rs:161:17 | LL | let $e..=; | ^^^^^ pattern `i32::MIN..=-1_i32` not covered diff --git a/tests/ui/pattern/range-pattern-meant-to-be-slice-rest-pattern.rs b/tests/ui/pattern/range-pattern-meant-to-be-slice-rest-pattern.rs index 1eba7aeb4d64a..fe7655c2c4e1c 100644 --- a/tests/ui/pattern/range-pattern-meant-to-be-slice-rest-pattern.rs +++ b/tests/ui/pattern/range-pattern-meant-to-be-slice-rest-pattern.rs @@ -11,7 +11,6 @@ fn main() { [_, ..tail] => println!("{tail}"), //~^ ERROR cannot find value `tail` in this scope //~| ERROR cannot find value `tail` in this scope - //~| ERROR exclusive range pattern syntax is experimental } match &[7, 8, 9][..] { [] => {} diff --git a/tests/ui/pattern/range-pattern-meant-to-be-slice-rest-pattern.stderr b/tests/ui/pattern/range-pattern-meant-to-be-slice-rest-pattern.stderr index 3a19517c85bd2..37c02eb6ada9c 100644 --- a/tests/ui/pattern/range-pattern-meant-to-be-slice-rest-pattern.stderr +++ b/tests/ui/pattern/range-pattern-meant-to-be-slice-rest-pattern.stderr @@ -1,5 +1,5 @@ error: range-to patterns with `...` are not allowed - --> $DIR/range-pattern-meant-to-be-slice-rest-pattern.rs:18:13 + --> $DIR/range-pattern-meant-to-be-slice-rest-pattern.rs:17:13 | LL | [_, ...tail] => println!("{tail}"), | ^^^ help: use `..=` instead @@ -39,7 +39,7 @@ LL | [_, ..tail] => println!("{tail}"), | ^^^^ not found in this scope error[E0425]: cannot find value `tail` in this scope - --> $DIR/range-pattern-meant-to-be-slice-rest-pattern.rs:18:16 + --> $DIR/range-pattern-meant-to-be-slice-rest-pattern.rs:17:16 | LL | [_, ...tail] => println!("{tail}"), | ^^^^ not found in this scope @@ -50,7 +50,7 @@ LL | [_, tail @ ..] => println!("{tail}"), | ~~~~~~~~~ error[E0425]: cannot find value `tail` in this scope - --> $DIR/range-pattern-meant-to-be-slice-rest-pattern.rs:18:36 + --> $DIR/range-pattern-meant-to-be-slice-rest-pattern.rs:17:36 | LL | [_, ...tail] => println!("{tail}"), | ^^^^ not found in this scope @@ -65,18 +65,7 @@ LL | [1, rest..] => println!("{rest}"), = help: add `#![feature(half_open_range_patterns_in_slices)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0658]: exclusive range pattern syntax is experimental - --> $DIR/range-pattern-meant-to-be-slice-rest-pattern.rs:11:13 - | -LL | [_, ..tail] => println!("{tail}"), - | ^^^^^^ - | - = note: see issue #37854 for more information - = help: add `#![feature(exclusive_range_pattern)]` to the crate attributes to enable - = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date - = help: use an inclusive range pattern, like N..=M - -error: aborting due to 9 previous errors +error: aborting due to 8 previous errors Some errors have detailed explanations: E0425, E0658. For more information about an error, try `rustc --explain E0425`. diff --git a/tests/ui/pattern/usefulness/floats.rs b/tests/ui/pattern/usefulness/floats.rs index 63ce26adab2a4..b3d49ba8e15e5 100644 --- a/tests/ui/pattern/usefulness/floats.rs +++ b/tests/ui/pattern/usefulness/floats.rs @@ -1,4 +1,3 @@ -#![feature(exclusive_range_pattern)] #![deny(unreachable_patterns)] fn main() { diff --git a/tests/ui/pattern/usefulness/floats.stderr b/tests/ui/pattern/usefulness/floats.stderr index d99f05f52842d..04f2fe3cd94f4 100644 --- a/tests/ui/pattern/usefulness/floats.stderr +++ b/tests/ui/pattern/usefulness/floats.stderr @@ -1,5 +1,5 @@ error[E0004]: non-exhaustive patterns: `_` not covered - --> $DIR/floats.rs:10:11 + --> $DIR/floats.rs:9:11 | LL | match 0.0 { | ^^^ pattern `_` not covered @@ -12,49 +12,49 @@ LL + _ => todo!() | error: unreachable pattern - --> $DIR/floats.rs:18:9 + --> $DIR/floats.rs:17:9 | LL | 0.01f64 => {} | ^^^^^^^ | note: the lint level is defined here - --> $DIR/floats.rs:2:9 + --> $DIR/floats.rs:1:9 | LL | #![deny(unreachable_patterns)] | ^^^^^^^^^^^^^^^^^^^^ error: unreachable pattern - --> $DIR/floats.rs:19:9 + --> $DIR/floats.rs:18:9 | LL | 0.02f64 => {} | ^^^^^^^ error: unreachable pattern - --> $DIR/floats.rs:20:9 + --> $DIR/floats.rs:19:9 | LL | 6.5f64 => {} | ^^^^^^ error: unreachable pattern - --> $DIR/floats.rs:22:9 + --> $DIR/floats.rs:21:9 | LL | 1.0f64..=4.0f64 => {} | ^^^^^^^^^^^^^^^ error: unreachable pattern - --> $DIR/floats.rs:34:9 + --> $DIR/floats.rs:33:9 | LL | 0.01f32 => {} | ^^^^^^^ error: unreachable pattern - --> $DIR/floats.rs:35:9 + --> $DIR/floats.rs:34:9 | LL | 0.02f32 => {} | ^^^^^^^ error: unreachable pattern - --> $DIR/floats.rs:36:9 + --> $DIR/floats.rs:35:9 | LL | 6.5f32 => {} | ^^^^^^ diff --git a/tests/ui/pattern/usefulness/guards.rs b/tests/ui/pattern/usefulness/guards.rs index b15440cf608bd..94ee8ee14adf1 100644 --- a/tests/ui/pattern/usefulness/guards.rs +++ b/tests/ui/pattern/usefulness/guards.rs @@ -1,4 +1,3 @@ -#![feature(exclusive_range_pattern)] #![deny(unreachable_patterns)] enum Q { R(Option) } diff --git a/tests/ui/pattern/usefulness/guards.stderr b/tests/ui/pattern/usefulness/guards.stderr index ad9046fe24828..82ed2a93c55f5 100644 --- a/tests/ui/pattern/usefulness/guards.stderr +++ b/tests/ui/pattern/usefulness/guards.stderr @@ -1,5 +1,5 @@ error[E0004]: non-exhaustive patterns: `128_u8..=u8::MAX` not covered - --> $DIR/guards.rs:12:11 + --> $DIR/guards.rs:11:11 | LL | match 0u8 { | ^^^ pattern `128_u8..=u8::MAX` not covered diff --git a/tests/ui/pattern/usefulness/integer-ranges/exhaustiveness.rs b/tests/ui/pattern/usefulness/integer-ranges/exhaustiveness.rs index 07156d9a08a34..026175e3abf72 100644 --- a/tests/ui/pattern/usefulness/integer-ranges/exhaustiveness.rs +++ b/tests/ui/pattern/usefulness/integer-ranges/exhaustiveness.rs @@ -1,4 +1,3 @@ -#![feature(exclusive_range_pattern)] #![allow(overlapping_range_endpoints)] #![allow(non_contiguous_range_endpoints)] #![deny(unreachable_patterns)] diff --git a/tests/ui/pattern/usefulness/integer-ranges/exhaustiveness.stderr b/tests/ui/pattern/usefulness/integer-ranges/exhaustiveness.stderr index 68976c1b0576f..cc250b79274c6 100644 --- a/tests/ui/pattern/usefulness/integer-ranges/exhaustiveness.stderr +++ b/tests/ui/pattern/usefulness/integer-ranges/exhaustiveness.stderr @@ -1,5 +1,5 @@ error[E0004]: non-exhaustive patterns: `u8::MAX` not covered - --> $DIR/exhaustiveness.rs:48:8 + --> $DIR/exhaustiveness.rs:47:8 | LL | m!(0u8, 0..255); | ^^^ pattern `u8::MAX` not covered @@ -11,7 +11,7 @@ LL | match $s { $($t)+ => {}, u8::MAX => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `u8::MAX` not covered - --> $DIR/exhaustiveness.rs:49:8 + --> $DIR/exhaustiveness.rs:48:8 | LL | m!(0u8, 0..=254); | ^^^ pattern `u8::MAX` not covered @@ -23,7 +23,7 @@ LL | match $s { $($t)+ => {}, u8::MAX => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `0_u8` not covered - --> $DIR/exhaustiveness.rs:50:8 + --> $DIR/exhaustiveness.rs:49:8 | LL | m!(0u8, 1..=255); | ^^^ pattern `0_u8` not covered @@ -35,7 +35,7 @@ LL | match $s { $($t)+ => {}, 0_u8 => todo!() } | +++++++++++++++++ error[E0004]: non-exhaustive patterns: `42_u8` not covered - --> $DIR/exhaustiveness.rs:51:8 + --> $DIR/exhaustiveness.rs:50:8 | LL | m!(0u8, 0..42 | 43..=255); | ^^^ pattern `42_u8` not covered @@ -47,7 +47,7 @@ LL | match $s { $($t)+ => {}, 42_u8 => todo!() } | ++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i8::MAX` not covered - --> $DIR/exhaustiveness.rs:52:8 + --> $DIR/exhaustiveness.rs:51:8 | LL | m!(0i8, -128..127); | ^^^ pattern `i8::MAX` not covered @@ -59,7 +59,7 @@ LL | match $s { $($t)+ => {}, i8::MAX => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i8::MAX` not covered - --> $DIR/exhaustiveness.rs:53:8 + --> $DIR/exhaustiveness.rs:52:8 | LL | m!(0i8, -128..=126); | ^^^ pattern `i8::MAX` not covered @@ -71,7 +71,7 @@ LL | match $s { $($t)+ => {}, i8::MAX => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `i8::MIN` not covered - --> $DIR/exhaustiveness.rs:54:8 + --> $DIR/exhaustiveness.rs:53:8 | LL | m!(0i8, -127..=127); | ^^^ pattern `i8::MIN` not covered @@ -83,7 +83,7 @@ LL | match $s { $($t)+ => {}, i8::MIN => todo!() } | ++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `0_i8` not covered - --> $DIR/exhaustiveness.rs:55:11 + --> $DIR/exhaustiveness.rs:54:11 | LL | match 0i8 { | ^^^ pattern `0_i8` not covered @@ -96,7 +96,7 @@ LL + 0_i8 => todo!() | error[E0004]: non-exhaustive patterns: `u128::MAX` not covered - --> $DIR/exhaustiveness.rs:60:8 + --> $DIR/exhaustiveness.rs:59:8 | LL | m!(0u128, 0..=ALMOST_MAX); | ^^^^^ pattern `u128::MAX` not covered @@ -108,7 +108,7 @@ LL | match $s { $($t)+ => {}, u128::MAX => todo!() } | ++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `5_u128..` not covered - --> $DIR/exhaustiveness.rs:61:8 + --> $DIR/exhaustiveness.rs:60:8 | LL | m!(0u128, 0..=4); | ^^^^^ pattern `5_u128..` not covered @@ -120,7 +120,7 @@ LL | match $s { $($t)+ => {}, 5_u128.. => todo!() } | +++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `0_u128` not covered - --> $DIR/exhaustiveness.rs:62:8 + --> $DIR/exhaustiveness.rs:61:8 | LL | m!(0u128, 1..=u128::MAX); | ^^^^^ pattern `0_u128` not covered @@ -132,7 +132,7 @@ LL | match $s { $($t)+ => {}, 0_u128 => todo!() } | +++++++++++++++++++ error[E0004]: non-exhaustive patterns: `(126_u8..=127_u8, false)` not covered - --> $DIR/exhaustiveness.rs:70:11 + --> $DIR/exhaustiveness.rs:69:11 | LL | match (0u8, true) { | ^^^^^^^^^^^ pattern `(126_u8..=127_u8, false)` not covered diff --git a/tests/ui/pattern/usefulness/integer-ranges/gap_between_ranges.rs b/tests/ui/pattern/usefulness/integer-ranges/gap_between_ranges.rs index 78849d7e14325..2e2519d1b6d8f 100644 --- a/tests/ui/pattern/usefulness/integer-ranges/gap_between_ranges.rs +++ b/tests/ui/pattern/usefulness/integer-ranges/gap_between_ranges.rs @@ -1,4 +1,3 @@ -#![feature(exclusive_range_pattern)] #![deny(non_contiguous_range_endpoints)] macro_rules! m { diff --git a/tests/ui/pattern/usefulness/integer-ranges/gap_between_ranges.stderr b/tests/ui/pattern/usefulness/integer-ranges/gap_between_ranges.stderr index e5c2d788ba4ef..8a029073f0574 100644 --- a/tests/ui/pattern/usefulness/integer-ranges/gap_between_ranges.stderr +++ b/tests/ui/pattern/usefulness/integer-ranges/gap_between_ranges.stderr @@ -1,5 +1,5 @@ error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:16:9 + --> $DIR/gap_between_ranges.rs:15:9 | LL | 20..30 => {} | ^^^^^^ @@ -10,13 +10,13 @@ LL | 31..=40 => {} | ------- this could appear to continue range `20_u8..30_u8`, but `30_u8` isn't matched by either of them | note: the lint level is defined here - --> $DIR/gap_between_ranges.rs:2:9 + --> $DIR/gap_between_ranges.rs:1:9 | LL | #![deny(non_contiguous_range_endpoints)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:21:9 + --> $DIR/gap_between_ranges.rs:20:9 | LL | 20..30 => {} | ^^^^^^ @@ -27,7 +27,7 @@ LL | 31 => {} | -- this could appear to continue range `20_u8..30_u8`, but `30_u8` isn't matched by either of them error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:26:13 + --> $DIR/gap_between_ranges.rs:25:13 | LL | m!(0u8, 20..30, 31..=40); | ^^^^^^ ------- this could appear to continue range `20_u8..30_u8`, but `30_u8` isn't matched by either of them @@ -36,7 +36,7 @@ LL | m!(0u8, 20..30, 31..=40); | help: use an inclusive range instead: `20_u8..=30_u8` error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:27:22 + --> $DIR/gap_between_ranges.rs:26:22 | LL | m!(0u8, 31..=40, 20..30); | ------- ^^^^^^ @@ -46,7 +46,7 @@ LL | m!(0u8, 31..=40, 20..30); | this could appear to continue range `20_u8..30_u8`, but `30_u8` isn't matched by either of them warning: multiple patterns overlap on their endpoints - --> $DIR/gap_between_ranges.rs:28:21 + --> $DIR/gap_between_ranges.rs:27:21 | LL | m!(0u8, 20..30, 29..=40); | ------ ^^^^^^^ ... with this range @@ -57,7 +57,7 @@ LL | m!(0u8, 20..30, 29..=40); = note: `#[warn(overlapping_range_endpoints)]` on by default error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:30:13 + --> $DIR/gap_between_ranges.rs:29:13 | LL | m!(0u8, 20..30, 31..=40); | ^^^^^^ ------- this could appear to continue range `20_u8..30_u8`, but `30_u8` isn't matched by either of them @@ -66,7 +66,7 @@ LL | m!(0u8, 20..30, 31..=40); | help: use an inclusive range instead: `20_u8..=30_u8` error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:32:13 + --> $DIR/gap_between_ranges.rs:31:13 | LL | m!(0u8, 20..30, 31..=32); | ^^^^^^ ------- this could appear to continue range `20_u8..30_u8`, but `30_u8` isn't matched by either of them @@ -75,7 +75,7 @@ LL | m!(0u8, 20..30, 31..=32); | help: use an inclusive range instead: `20_u8..=30_u8` error: exclusive range missing `u8::MAX` - --> $DIR/gap_between_ranges.rs:42:9 + --> $DIR/gap_between_ranges.rs:41:9 | LL | 0..255 => {} | ^^^^^^ @@ -84,7 +84,7 @@ LL | 0..255 => {} | help: use an inclusive range instead: `0_u8..=u8::MAX` error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:71:9 + --> $DIR/gap_between_ranges.rs:70:9 | LL | 0..10 => {} | ^^^^^ @@ -97,7 +97,7 @@ LL | 11..30 => {} | ------ this could appear to continue range `0_u8..10_u8`, but `10_u8` isn't matched by either of them error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:77:9 + --> $DIR/gap_between_ranges.rs:76:9 | LL | 0..10 => {} | ^^^^^ @@ -108,7 +108,7 @@ LL | 11..20 => {} | ------ this could appear to continue range `0_u8..10_u8`, but `10_u8` isn't matched by either of them error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:78:9 + --> $DIR/gap_between_ranges.rs:77:9 | LL | 11..20 => {} | ^^^^^^ @@ -119,7 +119,7 @@ LL | 21..30 => {} | ------ this could appear to continue range `11_u8..20_u8`, but `20_u8` isn't matched by either of them error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:83:9 + --> $DIR/gap_between_ranges.rs:82:9 | LL | 00..20 => {} | ^^^^^^ @@ -133,7 +133,7 @@ LL | 21..40 => {} | ------ this could appear to continue range `0_u8..20_u8`, but `20_u8` isn't matched by either of them error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:84:9 + --> $DIR/gap_between_ranges.rs:83:9 | LL | 10..20 => {} | ^^^^^^ @@ -146,7 +146,7 @@ LL | 21..40 => {} | ------ this could appear to continue range `10_u8..20_u8`, but `20_u8` isn't matched by either of them error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:92:10 + --> $DIR/gap_between_ranges.rs:91:10 | LL | (0..10, true) => {} | ^^^^^ @@ -157,7 +157,7 @@ LL | (11..20, true) => {} | ------ this could appear to continue range `0_u8..10_u8`, but `10_u8` isn't matched by either of them error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:97:16 + --> $DIR/gap_between_ranges.rs:96:16 | LL | (true, 0..10) => {} | ^^^^^ @@ -168,7 +168,7 @@ LL | (true, 11..20) => {} | ------ this could appear to continue range `0_u8..10_u8`, but `10_u8` isn't matched by either of them error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:103:10 + --> $DIR/gap_between_ranges.rs:102:10 | LL | (0..10, true) => {} | ^^^^^ @@ -179,7 +179,7 @@ LL | (11..20, false) => {} | ------ this could appear to continue range `0_u8..10_u8`, but `10_u8` isn't matched by either of them error: multiple ranges are one apart - --> $DIR/gap_between_ranges.rs:113:14 + --> $DIR/gap_between_ranges.rs:112:14 | LL | Some(0..10) => {} | ^^^^^ diff --git a/tests/ui/pattern/usefulness/integer-ranges/overlapping_range_endpoints.rs b/tests/ui/pattern/usefulness/integer-ranges/overlapping_range_endpoints.rs index 7e56880a87f70..a5b7a90161635 100644 --- a/tests/ui/pattern/usefulness/integer-ranges/overlapping_range_endpoints.rs +++ b/tests/ui/pattern/usefulness/integer-ranges/overlapping_range_endpoints.rs @@ -1,4 +1,3 @@ -#![feature(exclusive_range_pattern)] #![deny(overlapping_range_endpoints)] macro_rules! m { diff --git a/tests/ui/pattern/usefulness/integer-ranges/overlapping_range_endpoints.stderr b/tests/ui/pattern/usefulness/integer-ranges/overlapping_range_endpoints.stderr index aa37bd9bc9c9c..6634532d5edd9 100644 --- a/tests/ui/pattern/usefulness/integer-ranges/overlapping_range_endpoints.stderr +++ b/tests/ui/pattern/usefulness/integer-ranges/overlapping_range_endpoints.stderr @@ -1,5 +1,5 @@ error: multiple patterns overlap on their endpoints - --> $DIR/overlapping_range_endpoints.rs:15:22 + --> $DIR/overlapping_range_endpoints.rs:14:22 | LL | m!(0u8, 20..=30, 30..=40); | ------- ^^^^^^^ ... with this range @@ -8,13 +8,13 @@ LL | m!(0u8, 20..=30, 30..=40); | = note: you likely meant to write mutually exclusive ranges note: the lint level is defined here - --> $DIR/overlapping_range_endpoints.rs:2:9 + --> $DIR/overlapping_range_endpoints.rs:1:9 | LL | #![deny(overlapping_range_endpoints)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: multiple patterns overlap on their endpoints - --> $DIR/overlapping_range_endpoints.rs:16:22 + --> $DIR/overlapping_range_endpoints.rs:15:22 | LL | m!(0u8, 30..=40, 20..=30); | ------- ^^^^^^^ ... with this range @@ -24,7 +24,7 @@ LL | m!(0u8, 30..=40, 20..=30); = note: you likely meant to write mutually exclusive ranges error: multiple patterns overlap on their endpoints - --> $DIR/overlapping_range_endpoints.rs:19:21 + --> $DIR/overlapping_range_endpoints.rs:18:21 | LL | m!(0u8, 20..30, 29..=40); | ------ ^^^^^^^ ... with this range @@ -34,7 +34,7 @@ LL | m!(0u8, 20..30, 29..=40); = note: you likely meant to write mutually exclusive ranges error: multiple patterns overlap on their endpoints - --> $DIR/overlapping_range_endpoints.rs:23:22 + --> $DIR/overlapping_range_endpoints.rs:22:22 | LL | m!(0u8, 20..=30, 30..=31); | ------- ^^^^^^^ ... with this range @@ -44,7 +44,7 @@ LL | m!(0u8, 20..=30, 30..=31); = note: you likely meant to write mutually exclusive ranges error: multiple patterns overlap on their endpoints - --> $DIR/overlapping_range_endpoints.rs:27:22 + --> $DIR/overlapping_range_endpoints.rs:26:22 | LL | m!(0u8, 20..=30, 19..=20); | ------- ^^^^^^^ ... with this range @@ -54,7 +54,7 @@ LL | m!(0u8, 20..=30, 19..=20); = note: you likely meant to write mutually exclusive ranges error: multiple patterns overlap on their endpoints - --> $DIR/overlapping_range_endpoints.rs:39:9 + --> $DIR/overlapping_range_endpoints.rs:38:9 | LL | 0..=10 => {} | ------ this range overlaps on `10_u8`... @@ -65,7 +65,7 @@ LL | 10..=20 => {} = note: you likely meant to write mutually exclusive ranges error: multiple patterns overlap on their endpoints - --> $DIR/overlapping_range_endpoints.rs:39:9 + --> $DIR/overlapping_range_endpoints.rs:38:9 | LL | 20..=30 => {} | ------- this range overlaps on `20_u8`... @@ -75,7 +75,7 @@ LL | 10..=20 => {} = note: you likely meant to write mutually exclusive ranges error: multiple patterns overlap on their endpoints - --> $DIR/overlapping_range_endpoints.rs:46:10 + --> $DIR/overlapping_range_endpoints.rs:45:10 | LL | (0..=10, true) => {} | ------ this range overlaps on `10_u8`... @@ -85,7 +85,7 @@ LL | (10..20, true) => {} = note: you likely meant to write mutually exclusive ranges error: multiple patterns overlap on their endpoints - --> $DIR/overlapping_range_endpoints.rs:52:16 + --> $DIR/overlapping_range_endpoints.rs:51:16 | LL | (true, 0..=10) => {} | ------ this range overlaps on `10_u8`... @@ -95,7 +95,7 @@ LL | (true, 10..20) => {} = note: you likely meant to write mutually exclusive ranges error: multiple patterns overlap on their endpoints - --> $DIR/overlapping_range_endpoints.rs:58:14 + --> $DIR/overlapping_range_endpoints.rs:57:14 | LL | Some(0..=10) => {} | ------ this range overlaps on `10_u8`... diff --git a/tests/ui/pattern/usefulness/integer-ranges/pointer-sized-int.deny.stderr b/tests/ui/pattern/usefulness/integer-ranges/pointer-sized-int.deny.stderr index 416523213c098..914c6ed60c839 100644 --- a/tests/ui/pattern/usefulness/integer-ranges/pointer-sized-int.deny.stderr +++ b/tests/ui/pattern/usefulness/integer-ranges/pointer-sized-int.deny.stderr @@ -1,5 +1,5 @@ error[E0004]: non-exhaustive patterns: `usize::MAX..` not covered - --> $DIR/pointer-sized-int.rs:13:11 + --> $DIR/pointer-sized-int.rs:12:11 | LL | match 0usize { | ^^^^^^ pattern `usize::MAX..` not covered @@ -13,7 +13,7 @@ LL + usize::MAX.. => todo!() | error[E0004]: non-exhaustive patterns: `..isize::MIN` and `isize::MAX..` not covered - --> $DIR/pointer-sized-int.rs:18:11 + --> $DIR/pointer-sized-int.rs:17:11 | LL | match 0isize { | ^^^^^^ patterns `..isize::MIN` and `isize::MAX..` not covered @@ -27,7 +27,7 @@ LL + ..isize::MIN | isize::MAX.. => todo!() | error[E0004]: non-exhaustive patterns: `usize::MAX..` not covered - --> $DIR/pointer-sized-int.rs:23:8 + --> $DIR/pointer-sized-int.rs:22:8 | LL | m!(0usize, 0..=usize::MAX); | ^^^^^^ pattern `usize::MAX..` not covered @@ -40,7 +40,7 @@ LL | match $s { $($t)+ => {}, usize::MAX.. => todo!() } | +++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `usize::MAX..` not covered - --> $DIR/pointer-sized-int.rs:25:8 + --> $DIR/pointer-sized-int.rs:24:8 | LL | m!(0usize, 0..5 | 5..=usize::MAX); | ^^^^^^ pattern `usize::MAX..` not covered @@ -53,7 +53,7 @@ LL | match $s { $($t)+ => {}, usize::MAX.. => todo!() } | +++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `usize::MAX..` not covered - --> $DIR/pointer-sized-int.rs:27:8 + --> $DIR/pointer-sized-int.rs:26:8 | LL | m!(0usize, 0..usize::MAX | usize::MAX); | ^^^^^^ pattern `usize::MAX..` not covered @@ -66,7 +66,7 @@ LL | match $s { $($t)+ => {}, usize::MAX.. => todo!() } | +++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `(usize::MAX.., _)` not covered - --> $DIR/pointer-sized-int.rs:29:8 + --> $DIR/pointer-sized-int.rs:28:8 | LL | m!((0usize, true), (0..5, true) | (5..=usize::MAX, true) | (0..=usize::MAX, false)); | ^^^^^^^^^^^^^^ pattern `(usize::MAX.., _)` not covered @@ -79,7 +79,7 @@ LL | match $s { $($t)+ => {}, (usize::MAX.., _) => todo!() } | ++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `..isize::MIN` and `isize::MAX..` not covered - --> $DIR/pointer-sized-int.rs:38:8 + --> $DIR/pointer-sized-int.rs:37:8 | LL | m!(0isize, isize::MIN..=isize::MAX); | ^^^^^^ patterns `..isize::MIN` and `isize::MAX..` not covered @@ -92,7 +92,7 @@ LL | match $s { $($t)+ => {}, ..isize::MIN | isize::MAX.. => todo!() } | ++++++++++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `..isize::MIN` and `isize::MAX..` not covered - --> $DIR/pointer-sized-int.rs:40:8 + --> $DIR/pointer-sized-int.rs:39:8 | LL | m!(0isize, isize::MIN..5 | 5..=isize::MAX); | ^^^^^^ patterns `..isize::MIN` and `isize::MAX..` not covered @@ -105,7 +105,7 @@ LL | match $s { $($t)+ => {}, ..isize::MIN | isize::MAX.. => todo!() } | ++++++++++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `..isize::MIN` and `isize::MAX..` not covered - --> $DIR/pointer-sized-int.rs:42:8 + --> $DIR/pointer-sized-int.rs:41:8 | LL | m!(0isize, isize::MIN..=-1 | 0 | 1..=isize::MAX); | ^^^^^^ patterns `..isize::MIN` and `isize::MAX..` not covered @@ -118,7 +118,7 @@ LL | match $s { $($t)+ => {}, ..isize::MIN | isize::MAX.. => todo!() } | ++++++++++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `..isize::MIN` and `isize::MAX..` not covered - --> $DIR/pointer-sized-int.rs:44:8 + --> $DIR/pointer-sized-int.rs:43:8 | LL | m!(0isize, isize::MIN..isize::MAX | isize::MAX); | ^^^^^^ patterns `..isize::MIN` and `isize::MAX..` not covered @@ -131,7 +131,7 @@ LL | match $s { $($t)+ => {}, ..isize::MIN | isize::MAX.. => todo!() } | ++++++++++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: `(..isize::MIN, _)` and `(isize::MAX.., _)` not covered - --> $DIR/pointer-sized-int.rs:47:9 + --> $DIR/pointer-sized-int.rs:46:9 | LL | (0isize, true), | ^^^^^^^^^^^^^^ patterns `(..isize::MIN, _)` and `(isize::MAX.., _)` not covered @@ -144,7 +144,7 @@ LL | match $s { $($t)+ => {}, (..isize::MIN, _) | (isize::MAX.., _) => t | ++++++++++++++++++++++++++++++++++++++++++++++++++ error[E0004]: non-exhaustive patterns: type `usize` is non-empty - --> $DIR/pointer-sized-int.rs:58:11 + --> $DIR/pointer-sized-int.rs:57:11 | LL | match 7usize {} | ^^^^^^ diff --git a/tests/ui/pattern/usefulness/integer-ranges/pointer-sized-int.rs b/tests/ui/pattern/usefulness/integer-ranges/pointer-sized-int.rs index 40f086dcc71c8..0d6056e228f25 100644 --- a/tests/ui/pattern/usefulness/integer-ranges/pointer-sized-int.rs +++ b/tests/ui/pattern/usefulness/integer-ranges/pointer-sized-int.rs @@ -1,5 +1,4 @@ //@ revisions: deny -#![feature(exclusive_range_pattern)] #![allow(overlapping_range_endpoints)] macro_rules! m { diff --git a/tests/ui/pattern/usefulness/integer-ranges/reachability.rs b/tests/ui/pattern/usefulness/integer-ranges/reachability.rs index 13b84e2c44bc1..a72588b623c1f 100644 --- a/tests/ui/pattern/usefulness/integer-ranges/reachability.rs +++ b/tests/ui/pattern/usefulness/integer-ranges/reachability.rs @@ -1,4 +1,3 @@ -#![feature(exclusive_range_pattern)] #![allow(overlapping_range_endpoints)] #![allow(non_contiguous_range_endpoints)] #![deny(unreachable_patterns)] diff --git a/tests/ui/pattern/usefulness/integer-ranges/reachability.stderr b/tests/ui/pattern/usefulness/integer-ranges/reachability.stderr index 0f52dfd83b9cb..c5b028d2038c3 100644 --- a/tests/ui/pattern/usefulness/integer-ranges/reachability.stderr +++ b/tests/ui/pattern/usefulness/integer-ranges/reachability.stderr @@ -1,137 +1,137 @@ error: unreachable pattern - --> $DIR/reachability.rs:19:17 + --> $DIR/reachability.rs:18:17 | LL | m!(0u8, 42, 42); | ^^ | note: the lint level is defined here - --> $DIR/reachability.rs:4:9 + --> $DIR/reachability.rs:3:9 | LL | #![deny(unreachable_patterns)] | ^^^^^^^^^^^^^^^^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:23:22 + --> $DIR/reachability.rs:22:22 | LL | m!(0u8, 20..=30, 20); | ^^ error: unreachable pattern - --> $DIR/reachability.rs:24:22 + --> $DIR/reachability.rs:23:22 | LL | m!(0u8, 20..=30, 21); | ^^ error: unreachable pattern - --> $DIR/reachability.rs:25:22 + --> $DIR/reachability.rs:24:22 | LL | m!(0u8, 20..=30, 25); | ^^ error: unreachable pattern - --> $DIR/reachability.rs:26:22 + --> $DIR/reachability.rs:25:22 | LL | m!(0u8, 20..=30, 29); | ^^ error: unreachable pattern - --> $DIR/reachability.rs:27:22 + --> $DIR/reachability.rs:26:22 | LL | m!(0u8, 20..=30, 30); | ^^ error: unreachable pattern - --> $DIR/reachability.rs:30:21 + --> $DIR/reachability.rs:29:21 | LL | m!(0u8, 20..30, 20); | ^^ error: unreachable pattern - --> $DIR/reachability.rs:31:21 + --> $DIR/reachability.rs:30:21 | LL | m!(0u8, 20..30, 21); | ^^ error: unreachable pattern - --> $DIR/reachability.rs:32:21 + --> $DIR/reachability.rs:31:21 | LL | m!(0u8, 20..30, 25); | ^^ error: unreachable pattern - --> $DIR/reachability.rs:33:21 + --> $DIR/reachability.rs:32:21 | LL | m!(0u8, 20..30, 29); | ^^ error: unreachable pattern - --> $DIR/reachability.rs:37:22 + --> $DIR/reachability.rs:36:22 | LL | m!(0u8, 20..=30, 20..=30); | ^^^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:38:22 + --> $DIR/reachability.rs:37:22 | LL | m!(0u8, 20.. 30, 20.. 30); | ^^^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:39:22 + --> $DIR/reachability.rs:38:22 | LL | m!(0u8, 20..=30, 20.. 30); | ^^^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:41:22 + --> $DIR/reachability.rs:40:22 | LL | m!(0u8, 20..=30, 21..=30); | ^^^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:42:22 + --> $DIR/reachability.rs:41:22 | LL | m!(0u8, 20..=30, 20..=29); | ^^^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:44:24 + --> $DIR/reachability.rs:43:24 | LL | m!('a', 'A'..='z', 'a'..='z'); | ^^^^^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:51:9 + --> $DIR/reachability.rs:50:9 | LL | 5..=8 => {}, | ^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:57:9 + --> $DIR/reachability.rs:56:9 | LL | 5..15 => {}, | ^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:64:9 + --> $DIR/reachability.rs:63:9 | LL | 5..25 => {}, | ^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:72:9 + --> $DIR/reachability.rs:71:9 | LL | 5..25 => {}, | ^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:78:9 + --> $DIR/reachability.rs:77:9 | LL | 5..15 => {}, | ^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:85:9 + --> $DIR/reachability.rs:84:9 | LL | _ => {}, | - matches any value @@ -139,19 +139,19 @@ LL | '\u{D7FF}'..='\u{E000}' => {}, | ^^^^^^^^^^^^^^^^^^^^^^^ unreachable pattern error: unreachable pattern - --> $DIR/reachability.rs:90:9 + --> $DIR/reachability.rs:89:9 | LL | '\u{D7FF}'..='\u{E000}' => {}, | ^^^^^^^^^^^^^^^^^^^^^^^ error: unreachable pattern - --> $DIR/reachability.rs:106:9 + --> $DIR/reachability.rs:105:9 | LL | &FOO => {} | ^^^^ error: unreachable pattern - --> $DIR/reachability.rs:107:9 + --> $DIR/reachability.rs:106:9 | LL | BAR => {} | ^^^ diff --git a/tests/ui/process/println-with-broken-pipe.rs b/tests/ui/process/println-with-broken-pipe.rs index 1df8c765cbdec..798db3c0f8ca4 100644 --- a/tests/ui/process/println-with-broken-pipe.rs +++ b/tests/ui/process/println-with-broken-pipe.rs @@ -6,16 +6,14 @@ //@ ignore-horizon //@ ignore-android //@ normalize-stderr-test ".rs:\d+:\d+" -> ".rs:LL:CC" +//@ compile-flags: -Zon-broken-pipe=error // Test what the error message looks like when `println!()` panics because of // `std::io::ErrorKind::BrokenPipe` -#![feature(unix_sigpipe)] - use std::env; use std::process::{Command, Stdio}; -#[unix_sigpipe = "sig_ign"] fn main() { let mut args = env::args(); let me = args.next().unwrap(); diff --git a/tests/ui/range/range-pattern-out-of-bounds-issue-68972.rs b/tests/ui/range/range-pattern-out-of-bounds-issue-68972.rs index 206f05d0d3caf..50203d3cf4f22 100644 --- a/tests/ui/range/range-pattern-out-of-bounds-issue-68972.rs +++ b/tests/ui/range/range-pattern-out-of-bounds-issue-68972.rs @@ -1,4 +1,3 @@ -#![feature(exclusive_range_pattern)] #![allow(unreachable_patterns)] fn main() { match 0u8 { diff --git a/tests/ui/range/range-pattern-out-of-bounds-issue-68972.stderr b/tests/ui/range/range-pattern-out-of-bounds-issue-68972.stderr index 21f1fdba886c5..38ce1a8a2402f 100644 --- a/tests/ui/range/range-pattern-out-of-bounds-issue-68972.stderr +++ b/tests/ui/range/range-pattern-out-of-bounds-issue-68972.stderr @@ -1,11 +1,11 @@ error: literal out of range for `u8` - --> $DIR/range-pattern-out-of-bounds-issue-68972.rs:5:14 + --> $DIR/range-pattern-out-of-bounds-issue-68972.rs:4:14 | LL | 251..257 => {} | ^^^ this value does not fit into the type `u8` whose range is `0..=255` error: literal out of range for `u8` - --> $DIR/range-pattern-out-of-bounds-issue-68972.rs:7:15 + --> $DIR/range-pattern-out-of-bounds-issue-68972.rs:6:15 | LL | 251..=256 => {} | ^^^ this value does not fit into the type `u8` whose range is `0..=255` diff --git a/tests/ui/regions/regions-refcell.rs b/tests/ui/regions/regions-refcell.rs index 29eb5161a6c37..c27ffe6b6a8c0 100644 --- a/tests/ui/regions/regions-refcell.rs +++ b/tests/ui/regions/regions-refcell.rs @@ -3,6 +3,7 @@ // attempting to bootstrap librustc with new destructor lifetime // semantics. +#![allow(unexpected_cfgs)] // for the cfg-as-descriptions use std::collections::HashMap; use std::cell::RefCell; diff --git a/tests/ui/resolve/suggest-import-without-clobbering-attrs.fixed b/tests/ui/resolve/suggest-import-without-clobbering-attrs.fixed index d05c0f058069c..607c9af492713 100644 --- a/tests/ui/resolve/suggest-import-without-clobbering-attrs.fixed +++ b/tests/ui/resolve/suggest-import-without-clobbering-attrs.fixed @@ -1,8 +1,8 @@ //@ run-rustfix -//@ compile-flags: --cfg=whatever -Aunused +//@ compile-flags: -Aunused use y::z; -#[cfg(whatever)] +#[cfg(all())] use y::Whatever; mod y { diff --git a/tests/ui/resolve/suggest-import-without-clobbering-attrs.rs b/tests/ui/resolve/suggest-import-without-clobbering-attrs.rs index 0be2e558e42cd..6cc53fb108658 100644 --- a/tests/ui/resolve/suggest-import-without-clobbering-attrs.rs +++ b/tests/ui/resolve/suggest-import-without-clobbering-attrs.rs @@ -1,7 +1,7 @@ //@ run-rustfix -//@ compile-flags: --cfg=whatever -Aunused +//@ compile-flags: -Aunused -#[cfg(whatever)] +#[cfg(all())] use y::Whatever; mod y { diff --git a/tests/ui/rfcs/rfc-1445-restrict-constants-in-patterns/issue-6804-nan-match.rs b/tests/ui/rfcs/rfc-1445-restrict-constants-in-patterns/issue-6804-nan-match.rs index d43db576b3848..6d6a336e6885b 100644 --- a/tests/ui/rfcs/rfc-1445-restrict-constants-in-patterns/issue-6804-nan-match.rs +++ b/tests/ui/rfcs/rfc-1445-restrict-constants-in-patterns/issue-6804-nan-match.rs @@ -1,5 +1,4 @@ // Matching against NaN should result in an error -#![feature(exclusive_range_pattern)] #![allow(unused)] const NAN: f64 = f64::NAN; diff --git a/tests/ui/rfcs/rfc-1445-restrict-constants-in-patterns/issue-6804-nan-match.stderr b/tests/ui/rfcs/rfc-1445-restrict-constants-in-patterns/issue-6804-nan-match.stderr index 167ada783c24c..baca1d75048ee 100644 --- a/tests/ui/rfcs/rfc-1445-restrict-constants-in-patterns/issue-6804-nan-match.stderr +++ b/tests/ui/rfcs/rfc-1445-restrict-constants-in-patterns/issue-6804-nan-match.stderr @@ -1,5 +1,5 @@ error: cannot use NaN in patterns - --> $DIR/issue-6804-nan-match.rs:15:9 + --> $DIR/issue-6804-nan-match.rs:14:9 | LL | NAN => {}, | ^^^ @@ -8,7 +8,7 @@ LL | NAN => {}, = help: try using the `is_nan` method instead error: cannot use NaN in patterns - --> $DIR/issue-6804-nan-match.rs:20:10 + --> $DIR/issue-6804-nan-match.rs:19:10 | LL | [NAN, _] => {}, | ^^^ @@ -17,7 +17,7 @@ LL | [NAN, _] => {}, = help: try using the `is_nan` method instead error: cannot use NaN in patterns - --> $DIR/issue-6804-nan-match.rs:25:9 + --> $DIR/issue-6804-nan-match.rs:24:9 | LL | C => {}, | ^ @@ -26,7 +26,7 @@ LL | C => {}, = help: try using the `is_nan` method instead error: cannot use NaN in patterns - --> $DIR/issue-6804-nan-match.rs:31:9 + --> $DIR/issue-6804-nan-match.rs:30:9 | LL | NAN..=1.0 => {}, | ^^^ @@ -35,13 +35,13 @@ LL | NAN..=1.0 => {}, = help: try using the `is_nan` method instead error[E0030]: lower range bound must be less than or equal to upper - --> $DIR/issue-6804-nan-match.rs:31:9 + --> $DIR/issue-6804-nan-match.rs:30:9 | LL | NAN..=1.0 => {}, | ^^^^^^^^^ lower bound larger than upper bound error: cannot use NaN in patterns - --> $DIR/issue-6804-nan-match.rs:33:16 + --> $DIR/issue-6804-nan-match.rs:32:16 | LL | -1.0..=NAN => {}, | ^^^ @@ -50,13 +50,13 @@ LL | -1.0..=NAN => {}, = help: try using the `is_nan` method instead error[E0030]: lower range bound must be less than or equal to upper - --> $DIR/issue-6804-nan-match.rs:33:9 + --> $DIR/issue-6804-nan-match.rs:32:9 | LL | -1.0..=NAN => {}, | ^^^^^^^^^^ lower bound larger than upper bound error: cannot use NaN in patterns - --> $DIR/issue-6804-nan-match.rs:35:9 + --> $DIR/issue-6804-nan-match.rs:34:9 | LL | NAN.. => {}, | ^^^ @@ -65,13 +65,13 @@ LL | NAN.. => {}, = help: try using the `is_nan` method instead error[E0030]: lower range bound must be less than or equal to upper - --> $DIR/issue-6804-nan-match.rs:35:9 + --> $DIR/issue-6804-nan-match.rs:34:9 | LL | NAN.. => {}, | ^^^^^ lower bound larger than upper bound error: cannot use NaN in patterns - --> $DIR/issue-6804-nan-match.rs:37:11 + --> $DIR/issue-6804-nan-match.rs:36:11 | LL | ..NAN => {}, | ^^^ @@ -80,7 +80,7 @@ LL | ..NAN => {}, = help: try using the `is_nan` method instead error[E0579]: lower range bound must be less than upper - --> $DIR/issue-6804-nan-match.rs:37:9 + --> $DIR/issue-6804-nan-match.rs:36:9 | LL | ..NAN => {}, | ^^^^^ diff --git a/tests/ui/rfcs/rfc-2565-param-attrs/param-attrs-allowed.rs b/tests/ui/rfcs/rfc-2565-param-attrs/param-attrs-allowed.rs index e35f743d96aad..4b8d2406784a7 100644 --- a/tests/ui/rfcs/rfc-2565-param-attrs/param-attrs-allowed.rs +++ b/tests/ui/rfcs/rfc-2565-param-attrs/param-attrs-allowed.rs @@ -1,5 +1,5 @@ //@ check-pass -//@ compile-flags: --cfg something +//@ compile-flags: --cfg something --check-cfg=cfg(nothing,something) #![deny(unused_mut)] diff --git a/tests/ui/rfcs/rfc-2565-param-attrs/param-attrs-cfg.rs b/tests/ui/rfcs/rfc-2565-param-attrs/param-attrs-cfg.rs index babeaf67eb2e0..e7a5d59958b58 100644 --- a/tests/ui/rfcs/rfc-2565-param-attrs/param-attrs-cfg.rs +++ b/tests/ui/rfcs/rfc-2565-param-attrs/param-attrs-cfg.rs @@ -1,4 +1,4 @@ -//@ compile-flags: --cfg something +//@ compile-flags: --cfg something --check-cfg=cfg(nothing,something) //@ edition:2018 #![feature(async_closure)] diff --git a/tests/ui/attributes/unix_sigpipe/auxiliary/assert-inherit-sig_dfl.rs b/tests/ui/runtime/on-broken-pipe/auxiliary/assert-inherit-sig_dfl.rs similarity index 72% rename from tests/ui/attributes/unix_sigpipe/auxiliary/assert-inherit-sig_dfl.rs rename to tests/ui/runtime/on-broken-pipe/auxiliary/assert-inherit-sig_dfl.rs index 7f95fa7ebbece..b179e48452447 100644 --- a/tests/ui/attributes/unix_sigpipe/auxiliary/assert-inherit-sig_dfl.rs +++ b/tests/ui/runtime/on-broken-pipe/auxiliary/assert-inherit-sig_dfl.rs @@ -1,8 +1,6 @@ //@ aux-crate: sigpipe_utils=sigpipe-utils.rs +//@ compile-flags: -Zon-broken-pipe=inherit -#![feature(unix_sigpipe)] - -#[unix_sigpipe = "inherit"] fn main() { sigpipe_utils::assert_sigpipe_handler(sigpipe_utils::SignalHandler::Default); } diff --git a/tests/ui/attributes/unix_sigpipe/auxiliary/assert-inherit-sig_ign.rs b/tests/ui/runtime/on-broken-pipe/auxiliary/assert-inherit-sig_ign.rs similarity index 72% rename from tests/ui/attributes/unix_sigpipe/auxiliary/assert-inherit-sig_ign.rs rename to tests/ui/runtime/on-broken-pipe/auxiliary/assert-inherit-sig_ign.rs index d96e8b8ef8436..5ea435521ec4e 100644 --- a/tests/ui/attributes/unix_sigpipe/auxiliary/assert-inherit-sig_ign.rs +++ b/tests/ui/runtime/on-broken-pipe/auxiliary/assert-inherit-sig_ign.rs @@ -1,8 +1,6 @@ //@ aux-crate: sigpipe_utils=sigpipe-utils.rs +//@ compile-flags: -Zon-broken-pipe=inherit -#![feature(unix_sigpipe)] - -#[unix_sigpipe = "inherit"] fn main() { sigpipe_utils::assert_sigpipe_handler(sigpipe_utils::SignalHandler::Ignore); } diff --git a/tests/ui/attributes/unix_sigpipe/auxiliary/assert-sigpipe-disposition.rs b/tests/ui/runtime/on-broken-pipe/auxiliary/assert-sigpipe-disposition.rs similarity index 100% rename from tests/ui/attributes/unix_sigpipe/auxiliary/assert-sigpipe-disposition.rs rename to tests/ui/runtime/on-broken-pipe/auxiliary/assert-sigpipe-disposition.rs diff --git a/tests/ui/attributes/unix_sigpipe/auxiliary/sigpipe-utils.rs b/tests/ui/runtime/on-broken-pipe/auxiliary/sigpipe-utils.rs similarity index 100% rename from tests/ui/attributes/unix_sigpipe/auxiliary/sigpipe-utils.rs rename to tests/ui/runtime/on-broken-pipe/auxiliary/sigpipe-utils.rs diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-and-child-processes.rs b/tests/ui/runtime/on-broken-pipe/child-processes.rs similarity index 55% rename from tests/ui/attributes/unix_sigpipe/unix_sigpipe-and-child-processes.rs rename to tests/ui/runtime/on-broken-pipe/child-processes.rs index 9d1bd9f9607ec..0da2347481b19 100644 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-and-child-processes.rs +++ b/tests/ui/runtime/on-broken-pipe/child-processes.rs @@ -1,25 +1,20 @@ -//@ revisions: default sig_dfl sig_ign inherit +//@ revisions: default error kill inherit //@ ignore-cross-compile because aux-bin does not yet support it //@ only-unix because SIGPIPE is a unix thing //@ run-pass //@ aux-bin:assert-sigpipe-disposition.rs //@ aux-crate:sigpipe_utils=sigpipe-utils.rs +//@ [kill] compile-flags: -Zunstable-options -Zon-broken-pipe=kill +//@ [error] compile-flags: -Zunstable-options -Zon-broken-pipe=error +//@ [inherit] compile-flags: -Zunstable-options -Zon-broken-pipe=inherit // Checks the signal disposition of `SIGPIPE` in child processes, and in our own -// process for robustness. Without any `unix_sigpipe` attribute, `SIG_IGN` is -// the default. But there is a difference in how `SIGPIPE` is treated in child -// processes with and without the attribute. Search for -// `unix_sigpipe_attr_specified()` in the code base to learn more. - -#![cfg_attr(any(sig_dfl, sig_ign, inherit), feature(unix_sigpipe))] +// process for robustness. extern crate sigpipe_utils; use sigpipe_utils::*; -#[cfg_attr(sig_dfl, unix_sigpipe = "sig_dfl")] -#[cfg_attr(sig_ign, unix_sigpipe = "sig_ign")] -#[cfg_attr(inherit, unix_sigpipe = "inherit")] fn main() { // By default we get SIG_IGN but the child gets SIG_DFL through an explicit // reset before exec: @@ -27,18 +22,18 @@ fn main() { #[cfg(default)] let (we_expect, child_expects) = (SignalHandler::Ignore, "SIG_DFL"); - // With #[unix_sigpipe = "sig_dfl"] we get SIG_DFL and the child does too - // without any special code running before exec. - #[cfg(sig_dfl)] + // We get SIG_DFL and the child does too without any special code running + // before exec. + #[cfg(kill)] let (we_expect, child_expects) = (SignalHandler::Default, "SIG_DFL"); - // With #[unix_sigpipe = "sig_ign"] we get SIG_IGN and the child does too - // without any special code running before exec. - #[cfg(sig_ign)] + // We get SIG_IGN and the child does too without any special code running + // before exec. + #[cfg(error)] let (we_expect, child_expects) = (SignalHandler::Ignore, "SIG_IGN"); - // With #[unix_sigpipe = "inherit"] we get SIG_DFL and the child does too - // without any special code running before exec. + // We get SIG_DFL and the child does too without any special code running + // before exec. #[cfg(inherit)] let (we_expect, child_expects) = (SignalHandler::Default, "SIG_DFL"); diff --git a/tests/ui/runtime/on-broken-pipe/default.rs b/tests/ui/runtime/on-broken-pipe/default.rs new file mode 100644 index 0000000000000..c10d1cfacc0c3 --- /dev/null +++ b/tests/ui/runtime/on-broken-pipe/default.rs @@ -0,0 +1,4 @@ +//@ compile-flags: -Zon-broken-pipe=default +//@ check-fail + +fn main() {} diff --git a/tests/ui/runtime/on-broken-pipe/default.stderr b/tests/ui/runtime/on-broken-pipe/default.stderr new file mode 100644 index 0000000000000..b90d7566cbb21 --- /dev/null +++ b/tests/ui/runtime/on-broken-pipe/default.stderr @@ -0,0 +1,2 @@ +error: incorrect value `default` for unstable option `on-broken-pipe` - either `kill`, `error`, or `inherit` was expected + diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-not-used.rs b/tests/ui/runtime/on-broken-pipe/error.rs similarity index 50% rename from tests/ui/attributes/unix_sigpipe/unix_sigpipe-not-used.rs rename to tests/ui/runtime/on-broken-pipe/error.rs index b0044f5e91999..ab2036c2f415e 100644 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-not-used.rs +++ b/tests/ui/runtime/on-broken-pipe/error.rs @@ -1,12 +1,10 @@ -//@ revisions: with_feature without_feature //@ run-pass //@ aux-build:sigpipe-utils.rs - -#![cfg_attr(with_feature, feature(unix_sigpipe))] +//@ compile-flags: -Zon-broken-pipe=error fn main() { extern crate sigpipe_utils; - // SIGPIPE shall be ignored since #[unix_sigpipe = "..."] is not used + // `-Zon-broken-pipe=error` is active, so we expect SIGPIPE to be ignored. sigpipe_utils::assert_sigpipe_handler(sigpipe_utils::SignalHandler::Ignore); } diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-inherit.rs b/tests/ui/runtime/on-broken-pipe/inherit.rs similarity index 73% rename from tests/ui/attributes/unix_sigpipe/unix_sigpipe-inherit.rs rename to tests/ui/runtime/on-broken-pipe/inherit.rs index 3e63349edb747..64909b7352815 100644 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-inherit.rs +++ b/tests/ui/runtime/on-broken-pipe/inherit.rs @@ -3,20 +3,20 @@ //@ aux-bin: assert-inherit-sig_dfl.rs //@ aux-bin: assert-inherit-sig_ign.rs //@ run-pass +//@ compile-flags: -Zon-broken-pipe=kill -#![feature(rustc_private, unix_sigpipe)] +#![feature(rustc_private)] extern crate libc; // By default the Rust runtime resets SIGPIPE to SIG_DFL before exec'ing child -// processes so opt-out of that with `#[unix_sigpipe = "sig_dfl"]`. See +// processes so opt-out of that with `-Zon-broken-pipe=kill`. See // https://github.com/rust-lang/rust/blob/bf4de3a874753bbee3323081c8b0c133444fed2d/library/std/src/sys/pal/unix/process/process_unix.rs#L359-L384 -#[unix_sigpipe = "sig_dfl"] fn main() { - // First expect SIG_DFL in a child process with #[unix_sigpipe = "inherit"]. + // First expect SIG_DFL in a child process with -`Zon-broken-pipe=inherit`. assert_inherit_sigpipe_disposition("auxiliary/bin/assert-inherit-sig_dfl"); - // With SIG_IGN we expect #[unix_sigpipe = "inherit"] to also get SIG_IGN. + // With SIG_IGN we expect `-Zon-broken-pipe=inherit` to also get SIG_IGN. unsafe { libc::signal(libc::SIGPIPE, libc::SIG_IGN); } diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-sig_dfl.rs b/tests/ui/runtime/on-broken-pipe/kill.rs similarity index 60% rename from tests/ui/attributes/unix_sigpipe/unix_sigpipe-sig_dfl.rs rename to tests/ui/runtime/on-broken-pipe/kill.rs index 30f2a9b143062..5dace6f1c6ffc 100644 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-sig_dfl.rs +++ b/tests/ui/runtime/on-broken-pipe/kill.rs @@ -1,13 +1,11 @@ //@ run-pass //@ aux-build:sigpipe-utils.rs +//@ compile-flags: -Zon-broken-pipe=kill -#![feature(unix_sigpipe)] - -#[unix_sigpipe = "sig_dfl"] fn main() { extern crate sigpipe_utils; - // #[unix_sigpipe = "sig_dfl"] is active, so SIGPIPE shall NOT be ignored, instead + // `-Zon-broken-pipe=kill` is active, so SIGPIPE shall NOT be ignored, instead // the default handler shall be installed sigpipe_utils::assert_sigpipe_handler(sigpipe_utils::SignalHandler::Default); } diff --git a/tests/ui/runtime/on-broken-pipe/no-flag-arg.rs b/tests/ui/runtime/on-broken-pipe/no-flag-arg.rs new file mode 100644 index 0000000000000..2273291bfa778 --- /dev/null +++ b/tests/ui/runtime/on-broken-pipe/no-flag-arg.rs @@ -0,0 +1,4 @@ +//@ compile-flags: -Zon-broken-pipe +//@ check-fail + +fn main() {} diff --git a/tests/ui/runtime/on-broken-pipe/no-flag-arg.stderr b/tests/ui/runtime/on-broken-pipe/no-flag-arg.stderr new file mode 100644 index 0000000000000..3d3e12d303ca2 --- /dev/null +++ b/tests/ui/runtime/on-broken-pipe/no-flag-arg.stderr @@ -0,0 +1,2 @@ +error: unstable option `on-broken-pipe` requires either `kill`, `error`, or `inherit` (Z on-broken-pipe=) + diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-sig_ign.rs b/tests/ui/runtime/on-broken-pipe/not-used.rs similarity index 50% rename from tests/ui/attributes/unix_sigpipe/unix_sigpipe-sig_ign.rs rename to tests/ui/runtime/on-broken-pipe/not-used.rs index ccd6c67866018..e31236f2b3df8 100644 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-sig_ign.rs +++ b/tests/ui/runtime/on-broken-pipe/not-used.rs @@ -1,13 +1,9 @@ //@ run-pass //@ aux-build:sigpipe-utils.rs -#![feature(unix_sigpipe)] - -#[unix_sigpipe = "sig_ign"] fn main() { extern crate sigpipe_utils; - // #[unix_sigpipe = "sig_ign"] is active, so the legacy behavior of ignoring - // SIGPIPE shall be in effect + // SIGPIPE shall be ignored since `-Zon-broken-pipe` is not used sigpipe_utils::assert_sigpipe_handler(sigpipe_utils::SignalHandler::Ignore); } diff --git a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-rustc_main.rs b/tests/ui/runtime/on-broken-pipe/with-rustc_main.rs similarity index 69% rename from tests/ui/attributes/unix_sigpipe/unix_sigpipe-rustc_main.rs rename to tests/ui/runtime/on-broken-pipe/with-rustc_main.rs index 02a3f48f3b395..c1731200038b4 100644 --- a/tests/ui/attributes/unix_sigpipe/unix_sigpipe-rustc_main.rs +++ b/tests/ui/runtime/on-broken-pipe/with-rustc_main.rs @@ -1,15 +1,14 @@ //@ run-pass //@ aux-build:sigpipe-utils.rs +//@ compile-flags: -Zon-broken-pipe=kill -#![feature(unix_sigpipe)] #![feature(rustc_attrs)] -#[unix_sigpipe = "sig_dfl"] #[rustc_main] fn rustc_main() { extern crate sigpipe_utils; - // #[unix_sigpipe = "sig_dfl"] is active, so SIGPIPE handler shall be + // `-Zon-broken-pipe=kill` is active, so SIGPIPE handler shall be // SIG_DFL. Note that we have a #[rustc_main], but it should still work. sigpipe_utils::assert_sigpipe_handler(sigpipe_utils::SignalHandler::Default); } diff --git a/tests/ui/runtime/on-broken-pipe/wrong-flag-arg.rs b/tests/ui/runtime/on-broken-pipe/wrong-flag-arg.rs new file mode 100644 index 0000000000000..14d0ac56b5a3d --- /dev/null +++ b/tests/ui/runtime/on-broken-pipe/wrong-flag-arg.rs @@ -0,0 +1,4 @@ +//@ compile-flags: -Zon-broken-pipe=wrong +//@ check-fail + +fn main() {} diff --git a/tests/ui/runtime/on-broken-pipe/wrong-flag-arg.stderr b/tests/ui/runtime/on-broken-pipe/wrong-flag-arg.stderr new file mode 100644 index 0000000000000..3635418c845c2 --- /dev/null +++ b/tests/ui/runtime/on-broken-pipe/wrong-flag-arg.stderr @@ -0,0 +1,2 @@ +error: incorrect value `wrong` for unstable option `on-broken-pipe` - either `kill`, `error`, or `inherit` was expected + diff --git a/tests/ui/rust-2018/issue-54400-unused-extern-crate-attr-span.fixed b/tests/ui/rust-2018/issue-54400-unused-extern-crate-attr-span.fixed index f4506dd929ea4..878d1dc72ccb1 100644 --- a/tests/ui/rust-2018/issue-54400-unused-extern-crate-attr-span.fixed +++ b/tests/ui/rust-2018/issue-54400-unused-extern-crate-attr-span.fixed @@ -4,7 +4,7 @@ //@ edition:2018 #![deny(rust_2018_idioms)] -#![allow(dead_code)] +#![allow(dead_code, unexpected_cfgs)] // The suggestion span should include the attribute. diff --git a/tests/ui/rust-2018/issue-54400-unused-extern-crate-attr-span.rs b/tests/ui/rust-2018/issue-54400-unused-extern-crate-attr-span.rs index 4f1cb71dc5185..573942bd09552 100644 --- a/tests/ui/rust-2018/issue-54400-unused-extern-crate-attr-span.rs +++ b/tests/ui/rust-2018/issue-54400-unused-extern-crate-attr-span.rs @@ -4,7 +4,7 @@ //@ edition:2018 #![deny(rust_2018_idioms)] -#![allow(dead_code)] +#![allow(dead_code, unexpected_cfgs)] // The suggestion span should include the attribute. diff --git a/tests/ui/shell-argfiles/shell-argfiles-via-argfile.rs b/tests/ui/shell-argfiles/shell-argfiles-via-argfile.rs index b907fd3bbc758..2c07542bd75e5 100644 --- a/tests/ui/shell-argfiles/shell-argfiles-via-argfile.rs +++ b/tests/ui/shell-argfiles/shell-argfiles-via-argfile.rs @@ -1,6 +1,7 @@ // Check to see if we can get parameters from an @argsfile file // //@ build-pass +//@ no-auto-check-cfg //@ compile-flags: @{{src-base}}/shell-argfiles/shell-argfiles-via-argfile.args @shell:{{src-base}}/shell-argfiles/shell-argfiles-via-argfile-shell.args #[cfg(not(shell_args_set))] diff --git a/tests/ui/shell-argfiles/shell-argfiles.args b/tests/ui/shell-argfiles/shell-argfiles.args index e5bb4b807ec4d..6c596b0bbc05e 100644 --- a/tests/ui/shell-argfiles/shell-argfiles.args +++ b/tests/ui/shell-argfiles/shell-argfiles.args @@ -1,3 +1,4 @@ --cfg unquoted_set '--cfg' 'single_quoted_set' "--cfg" "double_quoted_set" +--check-cfg 'cfg(cmdline_set, unquoted_set, single_quoted_set, double_quoted_set)' diff --git a/tests/ui/span/suggestion-raw-68962.rs b/tests/ui/span/suggestion-raw-68962.rs new file mode 100644 index 0000000000000..0b581308f6628 --- /dev/null +++ b/tests/ui/span/suggestion-raw-68962.rs @@ -0,0 +1,11 @@ +fn r#fn() {} + +fn main() { + let r#final = 1; + + // Should correctly suggest variable defined using raw identifier. + fina; //~ ERROR cannot find value + + // Should correctly suggest function defined using raw identifier. + f(); //~ ERROR cannot find function +} diff --git a/tests/ui/span/suggestion-raw-68962.stderr b/tests/ui/span/suggestion-raw-68962.stderr new file mode 100644 index 0000000000000..2e25f5cbdf58d --- /dev/null +++ b/tests/ui/span/suggestion-raw-68962.stderr @@ -0,0 +1,18 @@ +error[E0425]: cannot find value `fina` in this scope + --> $DIR/suggestion-raw-68962.rs:7:5 + | +LL | fina; + | ^^^^ help: a local variable with a similar name exists: `r#final` + +error[E0425]: cannot find function `f` in this scope + --> $DIR/suggestion-raw-68962.rs:10:5 + | +LL | fn r#fn() {} + | --------- similarly named function `r#fn` defined here +... +LL | f(); + | ^ help: a function with a similar name exists: `r#fn` + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0425`. diff --git a/tests/ui/sse2.rs b/tests/ui/sse2.rs index 60570c566dea2..9ed6f6fefbdc0 100644 --- a/tests/ui/sse2.rs +++ b/tests/ui/sse2.rs @@ -2,6 +2,7 @@ #![allow(stable_features)] #![feature(cfg_target_feature)] +#![feature(lint_reasons)] use std::env; @@ -20,6 +21,7 @@ fn main() { "SSE2 was not detected as available on an x86 platform"); } // check a negative case too -- certainly not enabled by default - assert!(cfg!(not(target_feature = "ferris_wheel")), - "🎡 shouldn't be detected as available by default on any platform"); + #[expect(unexpected_cfgs)] + { assert!(cfg!(not(target_feature = "ferris_wheel")), + "🎡 shouldn't be detected as available by default on any platform") }; } diff --git a/tests/ui/stats/hir-stats.stderr b/tests/ui/stats/hir-stats.stderr index 1a67c9438449b..a3d0d47d40756 100644 --- a/tests/ui/stats/hir-stats.stderr +++ b/tests/ui/stats/hir-stats.stderr @@ -129,6 +129,9 @@ hir-stats Body 72 ( 0.8%) 3 24 hir-stats InlineAsm 72 ( 0.8%) 1 72 hir-stats ImplItemRef 72 ( 0.8%) 2 36 hir-stats Arm 80 ( 0.9%) 2 40 +hir-stats GenericArg 96 ( 1.1%) 4 24 +hir-stats - Type 24 ( 0.3%) 1 +hir-stats - Lifetime 72 ( 0.8%) 3 hir-stats FieldDef 96 ( 1.1%) 2 48 hir-stats Stmt 96 ( 1.1%) 3 32 hir-stats - Let 32 ( 0.4%) 1 @@ -136,43 +139,40 @@ hir-stats - Semi 32 ( 0.4%) 1 hir-stats - Expr 32 ( 0.4%) 1 hir-stats FnDecl 120 ( 1.3%) 3 40 hir-stats Attribute 128 ( 1.4%) 4 32 -hir-stats GenericArg 128 ( 1.4%) 4 32 -hir-stats - Type 32 ( 0.4%) 1 -hir-stats - Lifetime 96 ( 1.1%) 3 +hir-stats Variant 144 ( 1.6%) 2 72 hir-stats GenericArgs 144 ( 1.6%) 3 48 -hir-stats Variant 176 ( 1.9%) 2 88 hir-stats GenericBound 192 ( 2.1%) 4 48 hir-stats - Trait 192 ( 2.1%) 4 hir-stats WherePredicate 192 ( 2.1%) 3 64 hir-stats - BoundPredicate 192 ( 2.1%) 3 hir-stats Block 288 ( 3.2%) 6 48 +hir-stats GenericParam 360 ( 4.0%) 5 72 hir-stats Pat 360 ( 4.0%) 5 72 hir-stats - Wild 72 ( 0.8%) 1 hir-stats - Struct 72 ( 0.8%) 1 hir-stats - Binding 216 ( 2.4%) 3 -hir-stats GenericParam 400 ( 4.4%) 5 80 hir-stats Generics 560 ( 6.2%) 10 56 -hir-stats Ty 720 ( 7.9%) 15 48 +hir-stats Ty 720 ( 8.0%) 15 48 hir-stats - Ptr 48 ( 0.5%) 1 hir-stats - Ref 48 ( 0.5%) 1 hir-stats - Path 624 ( 6.9%) 13 -hir-stats Expr 768 ( 8.4%) 12 64 +hir-stats Expr 768 ( 8.5%) 12 64 hir-stats - Path 64 ( 0.7%) 1 hir-stats - Struct 64 ( 0.7%) 1 hir-stats - Match 64 ( 0.7%) 1 hir-stats - InlineAsm 64 ( 0.7%) 1 hir-stats - Lit 128 ( 1.4%) 2 -hir-stats - Block 384 ( 4.2%) 6 -hir-stats Item 968 (10.6%) 11 88 +hir-stats - Block 384 ( 4.3%) 6 +hir-stats Item 968 (10.8%) 11 88 hir-stats - Trait 88 ( 1.0%) 1 hir-stats - Enum 88 ( 1.0%) 1 hir-stats - ExternCrate 88 ( 1.0%) 1 hir-stats - ForeignMod 88 ( 1.0%) 1 hir-stats - Impl 88 ( 1.0%) 1 -hir-stats - Fn 176 ( 1.9%) 2 +hir-stats - Fn 176 ( 2.0%) 2 hir-stats - Use 352 ( 3.9%) 4 -hir-stats Path 1_240 (13.6%) 31 40 -hir-stats PathSegment 1_920 (21.1%) 40 48 +hir-stats Path 1_240 (13.8%) 31 40 +hir-stats PathSegment 1_920 (21.4%) 40 48 hir-stats ---------------------------------------------------------------- -hir-stats Total 9_096 +hir-stats Total 8_992 hir-stats diff --git a/tests/ui/target-feature/no-llvm-leaks.rs b/tests/ui/target-feature/no-llvm-leaks.rs index b4a391e184e82..73cec0a4496a7 100644 --- a/tests/ui/target-feature/no-llvm-leaks.rs +++ b/tests/ui/target-feature/no-llvm-leaks.rs @@ -6,7 +6,7 @@ //@ build-pass #![no_core] #![crate_type = "rlib"] -#![feature(intrinsics, rustc_attrs, no_core, lang_items, staged_api)] +#![feature(intrinsics, rustc_attrs, no_core, lang_items, staged_api, lint_reasons)] #![stable(feature = "test", since = "1.0.0")] // Supporting minimal rust core code @@ -43,22 +43,30 @@ macro_rules! assert { #[cfg(target_arch = "aarch64")] fn check_aarch64() { - // This checks that the rustc feature name is used, not the LLVM feature. + // These checks that the rustc feature name is used, not the LLVM feature. + assert!(cfg!(target_feature = "neon")); - assert!(cfg!(not(target_feature = "fp-armv8"))); + // #[expect(unexpected_cfgs)] except that 32-bit arm actually use fp-armv8 + { assert!(cfg!(not(target_feature = "fp-armv8"))); } + assert!(cfg!(target_feature = "fhm")); - assert!(cfg!(not(target_feature = "fp16fml"))); + #[expect(unexpected_cfgs)] + { assert!(cfg!(not(target_feature = "fp16fml"))); } + assert!(cfg!(target_feature = "fp16")); - assert!(cfg!(not(target_feature = "fullfp16"))); + #[expect(unexpected_cfgs)] + { assert!(cfg!(not(target_feature = "fullfp16"))); } } #[cfg(target_arch = "x86_64")] fn check_x86_64() { // This checks that the rustc feature name is used, not the LLVM feature. assert!(cfg!(target_feature = "rdrand")); - assert!(cfg!(not(target_feature = "rdrnd"))); + #[expect(unexpected_cfgs)] + { assert!(cfg!(not(target_feature = "rdrnd"))); } // Likewise: We enable LLVM's crc32 feature with SSE4.2, but Rust says it's just SSE4.2 assert!(cfg!(target_feature = "sse4.2")); - assert!(cfg!(not(target_feature = "crc32"))); + #[expect(unexpected_cfgs)] + { assert!(cfg!(not(target_feature = "crc32"))); } } diff --git a/tests/ui/traits/next-solver/auto-with-drop_tracking_mir.fail.stderr b/tests/ui/traits/next-solver/auto-with-drop_tracking_mir.fail.stderr index ac05dfb2d46f2..562d7ccf9fec0 100644 --- a/tests/ui/traits/next-solver/auto-with-drop_tracking_mir.fail.stderr +++ b/tests/ui/traits/next-solver/auto-with-drop_tracking_mir.fail.stderr @@ -1,18 +1,26 @@ -error[E0277]: `impl Future` cannot be sent between threads safely +error: future cannot be sent between threads safely --> $DIR/auto-with-drop_tracking_mir.rs:25:13 | LL | is_send(foo()); - | ------- ^^^^^ `impl Future` cannot be sent between threads safely - | | - | required by a bound introduced by this call + | ^^^^^ future returned by `foo` is not `Send` | - = help: the trait `Send` is not implemented for `impl Future` + = help: the trait `Sync` is not implemented for `impl Future`, which is required by `impl Future: Send` +note: future is not `Send` as this value is used across an await + --> $DIR/auto-with-drop_tracking_mir.rs:16:11 + | +LL | let x = &NotSync; + | - has type `&NotSync` which is not `Send` +LL | bar().await; + | ^^^^^ await occurs here, with `x` maybe used later note: required by a bound in `is_send` --> $DIR/auto-with-drop_tracking_mir.rs:24:24 | LL | fn is_send(_: impl Send) {} | ^^^^ required by this bound in `is_send` +help: consider dereferencing here + | +LL | is_send(*foo()); + | + error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/next-solver/auto-with-drop_tracking_mir.rs b/tests/ui/traits/next-solver/auto-with-drop_tracking_mir.rs index c82c17931194a..17741161b31bc 100644 --- a/tests/ui/traits/next-solver/auto-with-drop_tracking_mir.rs +++ b/tests/ui/traits/next-solver/auto-with-drop_tracking_mir.rs @@ -23,5 +23,5 @@ async fn bar() {} fn main() { fn is_send(_: impl Send) {} is_send(foo()); - //[fail]~^ ERROR `impl Future` cannot be sent between threads safely + //[fail]~^ ERROR future cannot be sent between threads safely } diff --git a/tests/ui/traits/next-solver/builtin-fn-must-return-sized.rs b/tests/ui/traits/next-solver/builtin-fn-must-return-sized.rs index ccb10bab6c1bc..f8926b24e3fab 100644 --- a/tests/ui/traits/next-solver/builtin-fn-must-return-sized.rs +++ b/tests/ui/traits/next-solver/builtin-fn-must-return-sized.rs @@ -13,5 +13,5 @@ fn foo, T: Tuple>(f: Option, t: T) { fn main() { foo:: str, _>(None, ()); - //~^ expected a `Fn<_>` closure, found `fn() -> str` + //~^ the size for values of type `str` cannot be known at compilation time } diff --git a/tests/ui/traits/next-solver/builtin-fn-must-return-sized.stderr b/tests/ui/traits/next-solver/builtin-fn-must-return-sized.stderr index 08047852f203a..b487ceef1d42e 100644 --- a/tests/ui/traits/next-solver/builtin-fn-must-return-sized.stderr +++ b/tests/ui/traits/next-solver/builtin-fn-must-return-sized.stderr @@ -1,10 +1,11 @@ -error[E0277]: expected a `Fn<_>` closure, found `fn() -> str` +error[E0277]: the size for values of type `str` cannot be known at compilation time --> $DIR/builtin-fn-must-return-sized.rs:15:11 | LL | foo:: str, _>(None, ()); - | ^^^^^^^^^^^ expected an `Fn<_>` closure, found `fn() -> str` + | ^^^^^^^^^^^ doesn't have a size known at compile-time | - = help: the trait `Fn<_>` is not implemented for `fn() -> str` + = help: within `fn() -> str`, the trait `Sized` is not implemented for `str`, which is required by `fn() -> str: Fn<_>` + = note: required because it appears within the type `fn() -> str` note: required by a bound in `foo` --> $DIR/builtin-fn-must-return-sized.rs:10:11 | diff --git a/tests/ui/traits/next-solver/coherence/coherence-fulfill-overflow.stderr b/tests/ui/traits/next-solver/coherence/coherence-fulfill-overflow.stderr index 57cba790b5537..6e68646fbe4f4 100644 --- a/tests/ui/traits/next-solver/coherence/coherence-fulfill-overflow.stderr +++ b/tests/ui/traits/next-solver/coherence/coherence-fulfill-overflow.stderr @@ -1,12 +1,12 @@ -error[E0119]: conflicting implementations of trait `Trait` for type `W>>>>>>>>>>>>>>>>>>>>` +error[E0119]: conflicting implementations of trait `Trait` for type `W>>>>>>>>>>>>>>>>>>>>>` --> $DIR/coherence-fulfill-overflow.rs:12:1 | LL | impl Trait for W {} | ------------------------------------- first implementation here LL | impl Trait for T {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `W>>>>>>>>>>>>>>>>>>>>` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ conflicting implementation for `W>>>>>>>>>>>>>>>>>>>>>` | - = note: overflow evaluating the requirement `W>>>>>>>>>>>>>>>>>>>>: TwoW` + = note: overflow evaluating the requirement `W>>>: TwoW` = help: consider increasing the recursion limit by adding a `#![recursion_limit = "20"]` attribute to your crate (`coherence_fulfill_overflow`) error: aborting due to 1 previous error diff --git a/tests/ui/traits/next-solver/cycles/coinduction/fixpoint-exponential-growth.stderr b/tests/ui/traits/next-solver/cycles/coinduction/fixpoint-exponential-growth.stderr index 8d7d8cee08ae3..df25150c21f8b 100644 --- a/tests/ui/traits/next-solver/cycles/coinduction/fixpoint-exponential-growth.stderr +++ b/tests/ui/traits/next-solver/cycles/coinduction/fixpoint-exponential-growth.stderr @@ -1,9 +1,16 @@ -error[E0275]: overflow evaluating the requirement `W<_>: Trait` +error[E0275]: overflow evaluating the requirement `_: Sized` --> $DIR/fixpoint-exponential-growth.rs:33:13 | LL | impls::>(); | ^^^^ | +note: required for `W<(W<_>, W<_>)>` to implement `Trait` + --> $DIR/fixpoint-exponential-growth.rs:23:12 + | +LL | impl Trait for W<(W, W)> + | - ^^^^^ ^^^^^^^^^^^^^^^ + | | + | unsatisfied trait bound introduced here note: required by a bound in `impls` --> $DIR/fixpoint-exponential-growth.rs:30:13 | diff --git a/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.rs b/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.rs index 7eea81ce03c66..8bb4ff469076c 100644 --- a/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.rs +++ b/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.rs @@ -61,7 +61,7 @@ where // entering the cycle from `A` fails, but would work if we were to use the cache // result of `B`. impls_trait::, _, _, _>(); - //~^ ERROR the trait bound `A: Trait<_, _, _>` is not satisfied + //~^ ERROR the trait bound `A: Trait` is not satisfied } fn main() { diff --git a/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.stderr b/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.stderr index d4932191791fd..cdb4ff4588f75 100644 --- a/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.stderr +++ b/tests/ui/traits/next-solver/cycles/coinduction/incompleteness-unstable-result.stderr @@ -1,15 +1,28 @@ -error[E0277]: the trait bound `A: Trait<_, _, _>` is not satisfied +error[E0277]: the trait bound `A: Trait` is not satisfied --> $DIR/incompleteness-unstable-result.rs:63:19 | LL | impls_trait::, _, _, _>(); - | ^^^^ the trait `Trait<_, _, _>` is not implemented for `A` + | ^^^^ the trait `Trait` is not implemented for `A`, which is required by `A: Trait<_, _, _>` | - = help: the trait `Trait` is implemented for `A` +note: required for `A` to implement `Trait` + --> $DIR/incompleteness-unstable-result.rs:32:50 + | +LL | impl Trait for A + | ^^^^^^^^^^^^^^ ^^^^ +... +LL | A: Trait, + | -------------- unsatisfied trait bound introduced here + = note: 8 redundant requirements hidden + = note: required for `A` to implement `Trait` note: required by a bound in `impls_trait` --> $DIR/incompleteness-unstable-result.rs:51:28 | LL | fn impls_trait, U: ?Sized, V: ?Sized, D: ?Sized>() {} | ^^^^^^^^^^^^^^ required by this bound in `impls_trait` +help: consider extending the `where` clause, but there might be an alternative better way to express this requirement + | +LL | X: IncompleteGuidance, A: Trait + | ~~~~~~~~~~~~~~~~~~~~~~~~~~ error: aborting due to 1 previous error diff --git a/tests/ui/traits/next-solver/cycles/double-cycle-inductive-coinductive.stderr b/tests/ui/traits/next-solver/cycles/double-cycle-inductive-coinductive.stderr index 7cedb4d36c98d..86c71ad92ff8a 100644 --- a/tests/ui/traits/next-solver/cycles/double-cycle-inductive-coinductive.stderr +++ b/tests/ui/traits/next-solver/cycles/double-cycle-inductive-coinductive.stderr @@ -1,21 +1,53 @@ -error[E0275]: overflow evaluating the requirement `(): Trait` +error[E0275]: overflow evaluating the requirement `(): Inductive` --> $DIR/double-cycle-inductive-coinductive.rs:32:19 | LL | impls_trait::<()>(); | ^^ | +note: required for `()` to implement `Trait` + --> $DIR/double-cycle-inductive-coinductive.rs:9:34 + | +LL | impl Trait for T {} + | --------- ^^^^^ ^ + | | + | unsatisfied trait bound introduced here +note: required for `()` to implement `Inductive` + --> $DIR/double-cycle-inductive-coinductive.rs:12:16 + | +LL | impl Inductive for T {} + | ----- ^^^^^^^^^ ^ + | | + | unsatisfied trait bound introduced here + = note: 7 redundant requirements hidden + = note: required for `()` to implement `Trait` note: required by a bound in `impls_trait` --> $DIR/double-cycle-inductive-coinductive.rs:17:19 | LL | fn impls_trait() {} | ^^^^^ required by this bound in `impls_trait` -error[E0275]: overflow evaluating the requirement `(): TraitRev` +error[E0275]: overflow evaluating the requirement `(): CoinductiveRev` --> $DIR/double-cycle-inductive-coinductive.rs:35:23 | LL | impls_trait_rev::<()>(); | ^^ | +note: required for `()` to implement `TraitRev` + --> $DIR/double-cycle-inductive-coinductive.rs:21:40 + | +LL | impl TraitRev for T {} + | -------------- ^^^^^^^^ ^ + | | + | unsatisfied trait bound introduced here +note: required for `()` to implement `CoinductiveRev` + --> $DIR/double-cycle-inductive-coinductive.rs:27:19 + | +LL | impl CoinductiveRev for T {} + | -------- ^^^^^^^^^^^^^^ ^ + | | + | unsatisfied trait bound introduced here + = note: 7 redundant requirements hidden + = note: required for `()` to implement `TraitRev` note: required by a bound in `impls_trait_rev` --> $DIR/double-cycle-inductive-coinductive.rs:29:23 | diff --git a/tests/ui/traits/next-solver/cycles/inductive-fixpoint-hang.stderr b/tests/ui/traits/next-solver/cycles/inductive-fixpoint-hang.stderr index a2a5c028cf8d5..ea46c0fea97b8 100644 --- a/tests/ui/traits/next-solver/cycles/inductive-fixpoint-hang.stderr +++ b/tests/ui/traits/next-solver/cycles/inductive-fixpoint-hang.stderr @@ -1,9 +1,19 @@ -error[E0275]: overflow evaluating the requirement `W<_>: Trait` +error[E0275]: overflow evaluating the requirement `W>: Trait` --> $DIR/inductive-fixpoint-hang.rs:31:19 | LL | impls_trait::>(); | ^^^^ | +note: required for `W>>` to implement `Trait` + --> $DIR/inductive-fixpoint-hang.rs:22:17 + | +LL | impl Trait for W> + | ^^^^^ ^^^^^^^ +LL | where +LL | W: Trait, + | ----- unsatisfied trait bound introduced here + = note: 8 redundant requirements hidden + = note: required for `W>>>>>>>>>>` to implement `Trait` note: required by a bound in `impls_trait` --> $DIR/inductive-fixpoint-hang.rs:28:19 | diff --git a/tests/ui/traits/next-solver/cycles/inductive-not-on-stack.rs b/tests/ui/traits/next-solver/cycles/inductive-not-on-stack.rs index 78683372580be..9d0ea51b1b25e 100644 --- a/tests/ui/traits/next-solver/cycles/inductive-not-on-stack.rs +++ b/tests/ui/traits/next-solver/cycles/inductive-not-on-stack.rs @@ -39,7 +39,7 @@ fn impls_ar() {} fn main() { impls_a::<()>(); - //~^ ERROR overflow evaluating the requirement `(): A` + //~^ ERROR overflow evaluating the requirement `(): B` impls_ar::<()>(); //~^ ERROR overflow evaluating the requirement `(): AR` diff --git a/tests/ui/traits/next-solver/cycles/inductive-not-on-stack.stderr b/tests/ui/traits/next-solver/cycles/inductive-not-on-stack.stderr index e9cc6bc6c81ad..fe02d3c407cab 100644 --- a/tests/ui/traits/next-solver/cycles/inductive-not-on-stack.stderr +++ b/tests/ui/traits/next-solver/cycles/inductive-not-on-stack.stderr @@ -1,9 +1,25 @@ -error[E0275]: overflow evaluating the requirement `(): A` +error[E0275]: overflow evaluating the requirement `(): B` --> $DIR/inductive-not-on-stack.rs:41:15 | LL | impls_a::<()>(); | ^^ | +note: required for `()` to implement `A` + --> $DIR/inductive-not-on-stack.rs:21:16 + | +LL | impl A for T {} + | - ^ ^ + | | + | unsatisfied trait bound introduced here +note: required for `()` to implement `B` + --> $DIR/inductive-not-on-stack.rs:22:12 + | +LL | impl B for T {} + | - ^ ^ + | | + | unsatisfied trait bound introduced here + = note: 7 redundant requirements hidden + = note: required for `()` to implement `A` note: required by a bound in `impls_a` --> $DIR/inductive-not-on-stack.rs:25:15 | @@ -16,6 +32,29 @@ error[E0275]: overflow evaluating the requirement `(): AR` LL | impls_ar::<()>(); | ^^ | +note: required for `()` to implement `BR` + --> $DIR/inductive-not-on-stack.rs:35:13 + | +LL | impl BR for T {} + | -- ^^ ^ + | | + | unsatisfied trait bound introduced here +note: required for `()` to implement `CR` + --> $DIR/inductive-not-on-stack.rs:36:13 + | +LL | impl CR for T {} + | -- ^^ ^ + | | + | unsatisfied trait bound introduced here +note: required for `()` to implement `AR` + --> $DIR/inductive-not-on-stack.rs:34:18 + | +LL | impl AR for T {} + | -- ^^ ^ + | | + | unsatisfied trait bound introduced here + = note: 6 redundant requirements hidden + = note: required for `()` to implement `AR` note: required by a bound in `impls_ar` --> $DIR/inductive-not-on-stack.rs:38:16 | diff --git a/tests/ui/traits/next-solver/cycles/mixed-cycles-1.rs b/tests/ui/traits/next-solver/cycles/mixed-cycles-1.rs index 6d75d24186430..b90a354be1b61 100644 --- a/tests/ui/traits/next-solver/cycles/mixed-cycles-1.rs +++ b/tests/ui/traits/next-solver/cycles/mixed-cycles-1.rs @@ -35,5 +35,5 @@ fn impls_a() {} fn main() { impls_a::<()>(); - //~^ ERROR overflow evaluating the requirement `(): A` + //~^ ERROR overflow evaluating the requirement `(): CInd` } diff --git a/tests/ui/traits/next-solver/cycles/mixed-cycles-1.stderr b/tests/ui/traits/next-solver/cycles/mixed-cycles-1.stderr index 17544eb1da528..03e61dbf99c22 100644 --- a/tests/ui/traits/next-solver/cycles/mixed-cycles-1.stderr +++ b/tests/ui/traits/next-solver/cycles/mixed-cycles-1.stderr @@ -1,9 +1,46 @@ -error[E0275]: overflow evaluating the requirement `(): A` +error[E0275]: overflow evaluating the requirement `(): CInd` --> $DIR/mixed-cycles-1.rs:37:15 | LL | impls_a::<()>(); | ^^ | +note: required for `()` to implement `B` + --> $DIR/mixed-cycles-1.rs:31:28 + | +LL | impl B for T {} + | ---- ^ ^ + | | + | unsatisfied trait bound introduced here +note: required for `()` to implement `C` + --> $DIR/mixed-cycles-1.rs:32:25 + | +LL | impl C for T {} + | - ^ ^ + | | + | unsatisfied trait bound introduced here +note: required for `()` to implement `CInd` + --> $DIR/mixed-cycles-1.rs:28:21 + | +LL | impl CInd for T {} + | - ^^^^ ^ + | | + | unsatisfied trait bound introduced here + = note: 4 redundant requirements hidden + = note: required for `()` to implement `B` +note: required for `()` to implement `BInd` + --> $DIR/mixed-cycles-1.rs:23:21 + | +LL | impl BInd for T {} + | - ^^^^ ^ + | | + | unsatisfied trait bound introduced here +note: required for `()` to implement `A` + --> $DIR/mixed-cycles-1.rs:30:28 + | +LL | impl A for T {} + | ---- ^ ^ + | | + | unsatisfied trait bound introduced here note: required by a bound in `impls_a` --> $DIR/mixed-cycles-1.rs:34:15 | diff --git a/tests/ui/traits/next-solver/cycles/mixed-cycles-2.rs b/tests/ui/traits/next-solver/cycles/mixed-cycles-2.rs index c939a6e5ef2f7..a3ffcaafb3758 100644 --- a/tests/ui/traits/next-solver/cycles/mixed-cycles-2.rs +++ b/tests/ui/traits/next-solver/cycles/mixed-cycles-2.rs @@ -28,5 +28,5 @@ fn impls_a() {} fn main() { impls_a::<()>(); - //~^ ERROR overflow evaluating the requirement `(): A` + //~^ ERROR overflow evaluating the requirement `(): BInd` } diff --git a/tests/ui/traits/next-solver/cycles/mixed-cycles-2.stderr b/tests/ui/traits/next-solver/cycles/mixed-cycles-2.stderr index a9be1016c7412..892426abe82e6 100644 --- a/tests/ui/traits/next-solver/cycles/mixed-cycles-2.stderr +++ b/tests/ui/traits/next-solver/cycles/mixed-cycles-2.stderr @@ -1,9 +1,32 @@ -error[E0275]: overflow evaluating the requirement `(): A` +error[E0275]: overflow evaluating the requirement `(): BInd` --> $DIR/mixed-cycles-2.rs:30:15 | LL | impls_a::<()>(); | ^^ | +note: required for `()` to implement `B` + --> $DIR/mixed-cycles-2.rs:25:24 + | +LL | impl B for T {} + | ---- ^ ^ + | | + | unsatisfied trait bound introduced here +note: required for `()` to implement `BInd` + --> $DIR/mixed-cycles-2.rs:22:21 + | +LL | impl BInd for T {} + | - ^^^^ ^ + | | + | unsatisfied trait bound introduced here + = note: 6 redundant requirements hidden + = note: required for `()` to implement `BInd` +note: required for `()` to implement `A` + --> $DIR/mixed-cycles-2.rs:24:28 + | +LL | impl A for T {} + | ---- ^ ^ + | | + | unsatisfied trait bound introduced here note: required by a bound in `impls_a` --> $DIR/mixed-cycles-2.rs:27:15 | diff --git a/tests/ui/traits/next-solver/diagnostics/point-at-failing-nested.rs b/tests/ui/traits/next-solver/diagnostics/point-at-failing-nested.rs new file mode 100644 index 0000000000000..840a4eb648c59 --- /dev/null +++ b/tests/ui/traits/next-solver/diagnostics/point-at-failing-nested.rs @@ -0,0 +1,24 @@ +//@ compile-flags: -Znext-solver + +trait Foo {} +trait Bar {} +trait Constrain { + type Output; +} + +impl Foo for T +where + T: Constrain, + U: Bar, +{ +} + +impl Constrain for () { + type Output = (); +} + +fn needs_foo() {} +fn main() { + needs_foo::<()>(); + //~^ the trait bound `(): Foo` is not satisfied +} diff --git a/tests/ui/traits/next-solver/diagnostics/point-at-failing-nested.stderr b/tests/ui/traits/next-solver/diagnostics/point-at-failing-nested.stderr new file mode 100644 index 0000000000000..6bf4e3cb53493 --- /dev/null +++ b/tests/ui/traits/next-solver/diagnostics/point-at-failing-nested.stderr @@ -0,0 +1,23 @@ +error[E0277]: the trait bound `(): Foo` is not satisfied + --> $DIR/point-at-failing-nested.rs:22:17 + | +LL | needs_foo::<()>(); + | ^^ the trait `Bar` is not implemented for `()`, which is required by `(): Foo` + | +note: required for `()` to implement `Foo` + --> $DIR/point-at-failing-nested.rs:9:12 + | +LL | impl Foo for T + | ^^^ ^ +... +LL | U: Bar, + | --- unsatisfied trait bound introduced here +note: required by a bound in `needs_foo` + --> $DIR/point-at-failing-nested.rs:20:17 + | +LL | fn needs_foo() {} + | ^^^ required by this bound in `needs_foo` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/next-solver/env-shadows-impls/param-candidate-shadows-project.rs b/tests/ui/traits/next-solver/env-shadows-impls/param-candidate-shadows-project.rs index ce7a380f07a6b..d11150ca55ae8 100644 --- a/tests/ui/traits/next-solver/env-shadows-impls/param-candidate-shadows-project.rs +++ b/tests/ui/traits/next-solver/env-shadows-impls/param-candidate-shadows-project.rs @@ -25,7 +25,7 @@ fn foo() { // // https://github.com/rust-lang/trait-system-refactor-initiative/issues/76 require_bar::(); - //~^ ERROR the trait bound `T: Bar` is not satisfied + //~^ ERROR type mismatch resolving `::Assoc == i32` } fn main() {} diff --git a/tests/ui/traits/next-solver/env-shadows-impls/param-candidate-shadows-project.stderr b/tests/ui/traits/next-solver/env-shadows-impls/param-candidate-shadows-project.stderr index 2785357e792de..3ef0afa38bff4 100644 --- a/tests/ui/traits/next-solver/env-shadows-impls/param-candidate-shadows-project.stderr +++ b/tests/ui/traits/next-solver/env-shadows-impls/param-candidate-shadows-project.stderr @@ -1,19 +1,25 @@ -error[E0277]: the trait bound `T: Bar` is not satisfied +error[E0271]: type mismatch resolving `::Assoc == i32` --> $DIR/param-candidate-shadows-project.rs:27:19 | LL | require_bar::(); - | ^ the trait `Bar` is not implemented for `T` + | ^ type mismatch resolving `::Assoc == i32` | +note: types differ + --> $DIR/param-candidate-shadows-project.rs:10:18 + | +LL | type Assoc = i32; + | ^^^ +note: required for `T` to implement `Bar` + --> $DIR/param-candidate-shadows-project.rs:13:9 + | +LL | impl Bar for T where T: Foo {} + | ^^^ ^ ----------- unsatisfied trait bound introduced here note: required by a bound in `require_bar` --> $DIR/param-candidate-shadows-project.rs:15:19 | LL | fn require_bar() {} | ^^^ required by this bound in `require_bar` -help: consider further restricting this bound - | -LL | fn foo() { - | +++++ error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0271`. diff --git a/tests/ui/traits/next-solver/more-object-bound.rs b/tests/ui/traits/next-solver/more-object-bound.rs index 511111af83f3d..3d3fdc926f658 100644 --- a/tests/ui/traits/next-solver/more-object-bound.rs +++ b/tests/ui/traits/next-solver/more-object-bound.rs @@ -10,7 +10,7 @@ trait Trait: SuperTrait::B> {} fn transmute(x: A) -> B { foo::>(x) - //~^ ERROR the trait bound `dyn Trait: Trait` is not satisfied + //~^ ERROR type mismatch resolving ` as SuperTrait>::A == B` } fn foo(x: T::A) -> B diff --git a/tests/ui/traits/next-solver/more-object-bound.stderr b/tests/ui/traits/next-solver/more-object-bound.stderr index 1b776d7198ea4..8cc2a51ee2b6c 100644 --- a/tests/ui/traits/next-solver/more-object-bound.stderr +++ b/tests/ui/traits/next-solver/more-object-bound.stderr @@ -1,9 +1,10 @@ -error[E0277]: the trait bound `dyn Trait: Trait` is not satisfied +error[E0271]: type mismatch resolving ` as SuperTrait>::A == B` --> $DIR/more-object-bound.rs:12:5 | LL | foo::>(x) - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Trait` is not implemented for `dyn Trait` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ | + = note: required because it appears within the type `dyn Trait` note: required by a bound in `foo` --> $DIR/more-object-bound.rs:18:8 | @@ -12,11 +13,7 @@ LL | fn foo(x: T::A) -> B LL | where LL | T: Trait, | ^^^^^^^^^^^^ required by this bound in `foo` -help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement - | -LL | fn transmute(x: A) -> B where dyn Trait: Trait { - | ++++++++++++++++++++++++++++++++++++ error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0277`. +For more information about this error, try `rustc --explain E0271`. diff --git a/tests/ui/traits/next-solver/normalize/two-projection-param-candidates-are-ambiguous.rs b/tests/ui/traits/next-solver/normalize/two-projection-param-candidates-are-ambiguous.rs index 40d68dbaffdf0..12ea1bf142ab8 100644 --- a/tests/ui/traits/next-solver/normalize/two-projection-param-candidates-are-ambiguous.rs +++ b/tests/ui/traits/next-solver/normalize/two-projection-param-candidates-are-ambiguous.rs @@ -24,7 +24,7 @@ fn needs_bar() {} fn foo + Foo>() { needs_bar::(); - //~^ ERROR type annotations needed: cannot satisfy `T: Bar` + //~^ ERROR type annotations needed: cannot satisfy `::Assoc == i32` } fn main() {} diff --git a/tests/ui/traits/next-solver/normalize/two-projection-param-candidates-are-ambiguous.stderr b/tests/ui/traits/next-solver/normalize/two-projection-param-candidates-are-ambiguous.stderr index dfff9f11b8756..21f3fbfeb872e 100644 --- a/tests/ui/traits/next-solver/normalize/two-projection-param-candidates-are-ambiguous.stderr +++ b/tests/ui/traits/next-solver/normalize/two-projection-param-candidates-are-ambiguous.stderr @@ -1,11 +1,14 @@ -error[E0283]: type annotations needed: cannot satisfy `T: Bar` +error[E0284]: type annotations needed: cannot satisfy `::Assoc == i32` --> $DIR/two-projection-param-candidates-are-ambiguous.rs:26:17 | LL | needs_bar::(); - | ^ + | ^ cannot satisfy `::Assoc == i32` | - = note: cannot satisfy `T: Bar` - = help: the trait `Bar` is implemented for `T` +note: required for `T` to implement `Bar` + --> $DIR/two-projection-param-candidates-are-ambiguous.rs:21:9 + | +LL | impl Bar for T where T: Foo {} + | ^^^ ^ ----------- unsatisfied trait bound introduced here note: required by a bound in `needs_bar` --> $DIR/two-projection-param-candidates-are-ambiguous.rs:23:17 | @@ -14,4 +17,4 @@ LL | fn needs_bar() {} error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0283`. +For more information about this error, try `rustc --explain E0284`. diff --git a/tests/ui/traits/next-solver/object-unsafety.rs b/tests/ui/traits/next-solver/object-unsafety.rs index 4222607b5bfe4..3aa1af4956e22 100644 --- a/tests/ui/traits/next-solver/object-unsafety.rs +++ b/tests/ui/traits/next-solver/object-unsafety.rs @@ -11,9 +11,9 @@ fn copy(from: &U::From) -> U::From { pub fn copy_any(t: &T) -> T { copy::>(t) //~^ ERROR the type `& as Setup>::From` is not well-formed - //~| ERROR the trait bound `dyn Setup: Setup` is not satisfied //~| ERROR mismatched types //~| ERROR the type ` as Setup>::From` is not well-formed + //~| ERROR the trait bound `T: Copy` is not satisfied // FIXME(-Znext-solver): These error messages are horrible and some of them // are even simple fallout from previous error. diff --git a/tests/ui/traits/next-solver/object-unsafety.stderr b/tests/ui/traits/next-solver/object-unsafety.stderr index a9cbb721511ca..7c9a6077fe7fd 100644 --- a/tests/ui/traits/next-solver/object-unsafety.stderr +++ b/tests/ui/traits/next-solver/object-unsafety.stderr @@ -1,18 +1,19 @@ -error[E0277]: the trait bound `dyn Setup: Setup` is not satisfied +error[E0277]: the trait bound `T: Copy` is not satisfied in `dyn Setup` --> $DIR/object-unsafety.rs:12:12 | LL | copy::>(t) - | ^^^^^^^^^^^^^^^^^ the trait `Setup` is not implemented for `dyn Setup` + | ^^^^^^^^^^^^^^^^^ within `dyn Setup`, the trait `Copy` is not implemented for `T`, which is required by `dyn Setup: Setup` | + = note: required because it appears within the type `dyn Setup` note: required by a bound in `copy` --> $DIR/object-unsafety.rs:7:12 | LL | fn copy(from: &U::From) -> U::From { | ^^^^^ required by this bound in `copy` -help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement +help: consider restricting type parameter `T` | -LL | pub fn copy_any(t: &T) -> T where dyn Setup: Setup { - | ++++++++++++++++++++++++++++++++ +LL | pub fn copy_any(t: &T) -> T { + | +++++++++++++++++++ error: the type `& as Setup>::From` is not well-formed --> $DIR/object-unsafety.rs:12:31 diff --git a/tests/ui/traits/next-solver/overflow/exponential-trait-goals.rs b/tests/ui/traits/next-solver/overflow/exponential-trait-goals.rs index 186d0e8be56e8..052d803765d3c 100644 --- a/tests/ui/traits/next-solver/overflow/exponential-trait-goals.rs +++ b/tests/ui/traits/next-solver/overflow/exponential-trait-goals.rs @@ -15,5 +15,5 @@ fn impls() {} fn main() { impls::>(); - //~^ ERROR overflow evaluating the requirement `W<_>: Trait` + //~^ ERROR overflow evaluating the requirement `_: Sized` } diff --git a/tests/ui/traits/next-solver/overflow/exponential-trait-goals.stderr b/tests/ui/traits/next-solver/overflow/exponential-trait-goals.stderr index b032ae3e740db..6583cae8bb9c1 100644 --- a/tests/ui/traits/next-solver/overflow/exponential-trait-goals.stderr +++ b/tests/ui/traits/next-solver/overflow/exponential-trait-goals.stderr @@ -1,9 +1,16 @@ -error[E0275]: overflow evaluating the requirement `W<_>: Trait` +error[E0275]: overflow evaluating the requirement `_: Sized` --> $DIR/exponential-trait-goals.rs:17:13 | LL | impls::>(); | ^^^^ | +note: required for `W<(W<_>, W<_>)>` to implement `Trait` + --> $DIR/exponential-trait-goals.rs:7:12 + | +LL | impl Trait for W<(W, W)> + | - ^^^^^ ^^^^^^^^^^^^^^^ + | | + | unsatisfied trait bound introduced here note: required by a bound in `impls` --> $DIR/exponential-trait-goals.rs:14:13 | diff --git a/tests/ui/traits/next-solver/overflow/global-cache.stderr b/tests/ui/traits/next-solver/overflow/global-cache.stderr index 67616619384c6..9e467721e83e3 100644 --- a/tests/ui/traits/next-solver/overflow/global-cache.stderr +++ b/tests/ui/traits/next-solver/overflow/global-cache.stderr @@ -5,6 +5,15 @@ LL | impls_trait::>>>>(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: consider increasing the recursion limit by adding a `#![recursion_limit = "18"]` attribute to your crate (`global_cache`) +note: required for `Inc>>>>>>>>>>` to implement `Trait` + --> $DIR/global-cache.rs:12:16 + | +LL | impl Trait for Inc {} + | ----- ^^^^^ ^^^^^^ + | | + | unsatisfied trait bound introduced here + = note: 5 redundant requirements hidden + = note: required for `Inc>>>>>>>>>>>>>>>` to implement `Trait` note: required by a bound in `impls_trait` --> $DIR/global-cache.rs:15:19 | diff --git a/tests/ui/typeck/issue-100285.rs b/tests/ui/typeck/issue-100285.rs index 460e0457105f5..bea4b2bc2bbe7 100644 --- a/tests/ui/typeck/issue-100285.rs +++ b/tests/ui/typeck/issue-100285.rs @@ -1,4 +1,4 @@ -fn foo(n: i32) -> i32 { //~ HELP otherwise consider changing the return type to account for that possibility +fn foo(n: i32) -> i32 { for i in 0..0 { //~ ERROR mismatched types [E0308] if n < 0 { return i; @@ -14,7 +14,7 @@ fn foo(n: i32) -> i32 { //~ HELP otherwise consider changing the return type to return 5; } - } //~ HELP return a value for the case when the loop has zero elements to iterate on + } //~ HELP consider returning a value here } fn main() {} diff --git a/tests/ui/typeck/issue-100285.stderr b/tests/ui/typeck/issue-100285.stderr index c0deb63af59ac..6f86fd18e0f68 100644 --- a/tests/ui/typeck/issue-100285.stderr +++ b/tests/ui/typeck/issue-100285.stderr @@ -12,47 +12,12 @@ LL | | LL | | } | |_____^ expected `i32`, found `()` | -note: the function expects a value to always be returned, but loops might run zero times - --> $DIR/issue-100285.rs:2:5 - | -LL | for i in 0..0 { - | ^^^^^^^^^^^^^ this might have zero elements to iterate on -LL | if n < 0 { -LL | return i; - | -------- if the loop doesn't execute, this value would never get returned -LL | } else if n < 10 { -LL | return 1; - | -------- if the loop doesn't execute, this value would never get returned -LL | } else if n < 20 { -LL | return 2; - | -------- if the loop doesn't execute, this value would never get returned - = note: if the loop doesn't execute, 3 other values would never get returned -help: return a value for the case when the loop has zero elements to iterate on + = note: `for` loops evaluate to unit type `()` +help: consider returning a value here | LL ~ } LL ~ /* `i32` value */ | -help: otherwise consider changing the return type to account for that possibility - | -LL ~ fn foo(n: i32) -> Option { -LL | for i in 0..0 { -LL | if n < 0 { -LL ~ return Some(i); -LL | } else if n < 10 { -LL ~ return Some(1); -LL | } else if n < 20 { -LL ~ return Some(2); -LL | } else if n < 30 { -LL ~ return Some(3); -LL | } else if n < 40 { -LL ~ return Some(4); -LL | } else { -LL ~ return Some(5); -LL | } -LL | -LL ~ } -LL ~ None - | error: aborting due to 1 previous error diff --git a/tests/ui/typeck/issue-98982.rs b/tests/ui/typeck/issue-98982.rs index f875d20fa4c53..3eff9fbe360b7 100644 --- a/tests/ui/typeck/issue-98982.rs +++ b/tests/ui/typeck/issue-98982.rs @@ -1,7 +1,7 @@ -fn foo() -> i32 { //~ HELP otherwise consider changing the return type to account for that possibility +fn foo() -> i32 { for i in 0..0 { //~ ERROR mismatched types [E0308] return i; - } //~ HELP return a value for the case when the loop has zero elements to iterate on + } //~ HELP consider returning a value here } fn main() {} diff --git a/tests/ui/typeck/issue-98982.stderr b/tests/ui/typeck/issue-98982.stderr index d8d5a86b157f2..3d40ff4d5afbe 100644 --- a/tests/ui/typeck/issue-98982.stderr +++ b/tests/ui/typeck/issue-98982.stderr @@ -8,26 +8,12 @@ LL | | return i; LL | | } | |_____^ expected `i32`, found `()` | -note: the function expects a value to always be returned, but loops might run zero times - --> $DIR/issue-98982.rs:2:5 - | -LL | for i in 0..0 { - | ^^^^^^^^^^^^^ this might have zero elements to iterate on -LL | return i; - | -------- if the loop doesn't execute, this value would never get returned -help: return a value for the case when the loop has zero elements to iterate on + = note: `for` loops evaluate to unit type `()` +help: consider returning a value here | LL ~ } LL ~ /* `i32` value */ | -help: otherwise consider changing the return type to account for that possibility - | -LL ~ fn foo() -> Option { -LL | for i in 0..0 { -LL ~ return Some(i); -LL ~ } -LL ~ None - | error: aborting due to 1 previous error diff --git a/triagebot.toml b/triagebot.toml index 499ba6e470cda..dd6a03faaaffd 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -106,12 +106,18 @@ resolved/implemented on Fuchsia. Could one of you weigh in? """ label = "O-fuchsia" -[ping.macos] +[ping.apple] +alias = ["macos", "ios", "tvos", "watchos", "visionos"] message = """\ -Hey MacOS Group! This issue or PR could use some MacOS-specific guidance. Could one -of you weigh in? Thanks <3 +Hey Apple notification group! This issue or PR could use some Apple-specific +guidance. Could one of you weigh in? Thanks <3 + +(In case it's useful, here are some [instructions] for tackling these sorts of +issues). + +[instructions]: https://rustc-dev-guide.rust-lang.org/notification-groups/apple.html """ -label = "O-macos" +label = "O-apple" [prioritize] label = "I-prioritize" @@ -227,7 +233,9 @@ trigger_files = [ [autolabel."O-macos"] trigger_files = [ - "library/std/src/os/macos" + "library/std/src/os/macos", + "library/std/src/sys/pal/unix/thread_parking/darwin.rs", + "compiler/rustc_target/src/spec/base/apple", ] [autolabel."O-netbsd"] @@ -1057,3 +1065,7 @@ project-exploit-mitigations = [ # Enable tracking of PR review assignment # Documentation at: https://forge.rust-lang.org/triagebot/pr-assignment-tracking.html [pr-tracking] + +# Enable issue transfers within the org +# Documentation at: https://forge.rust-lang.org/triagebot/transfer.html +[transfer]