From 833b9154ac7d41d7040129468d6794444533c03f Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Thu, 15 Dec 2022 13:20:27 -0300 Subject: [PATCH 01/12] Make encode_attrs use opt_local_def_id_to_hir_id so we can feed it with None for definitions that have no HIR --- compiler/rustc_metadata/src/rmeta/encoder.rs | 4 ++-- compiler/rustc_middle/src/hir/mod.rs | 6 +++--- compiler/rustc_middle/src/query/mod.rs | 7 +++---- compiler/rustc_middle/src/ty/context.rs | 4 ++++ 4 files changed, 12 insertions(+), 9 deletions(-) diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index e941dd45688..16029822d03 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1137,8 +1137,8 @@ fn encode_attrs(&mut self, def_id: LocalDefId) { is_doc_hidden: false, }; let attr_iter = tcx - .hir() - .attrs(tcx.hir().local_def_id_to_hir_id(def_id)) + .opt_local_def_id_to_hir_id(def_id) + .map_or(Default::default(), |hir_id| tcx.hir().attrs(hir_id)) .iter() .filter(|attr| analyze_attr(attr, &mut state)); diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index dc89f762b76..2e2ca6a2788 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -121,13 +121,13 @@ pub fn provide(providers: &mut Providers) { let node = owner.node(); Some(Owner { node, hash_without_bodies: owner.nodes.hash_without_bodies }) }; - providers.local_def_id_to_hir_id = |tcx, id| { + providers.opt_local_def_id_to_hir_id = |tcx, id| { let owner = tcx.hir_crate(()).owners[id].map(|_| ()); - match owner { + Some(match owner { MaybeOwner::Owner(_) => HirId::make_owner(id), MaybeOwner::Phantom => bug!("No HirId for {:?}", id), MaybeOwner::NonOwner(hir_id) => hir_id, - } + }) }; providers.hir_owner_nodes = |tcx, id| tcx.hir_crate(()).owners[id.def_id].map(|i| &i.nodes); providers.hir_owner_parent = |tcx, id| { diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 1ccad25fe08..8b846f10603 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -85,11 +85,10 @@ desc { |tcx| "getting HIR owner of `{}`", tcx.def_path_str(key.to_def_id()) } } - /// Gives access to the HIR ID for the given `LocalDefId` owner `key`. + /// Gives access to the HIR ID for the given `LocalDefId` owner `key` if any. /// - /// This can be conveniently accessed by methods on `tcx.hir()`. - /// Avoid calling this query directly. - query local_def_id_to_hir_id(key: LocalDefId) -> hir::HirId { + /// Definitions that were generated with no HIR, would be feeded to return `None`. + query opt_local_def_id_to_hir_id(key: LocalDefId) -> Option{ desc { |tcx| "getting HIR ID of `{}`", tcx.def_path_str(key.to_def_id()) } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 117f3decd1a..dc7e4ac900a 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -2428,6 +2428,10 @@ pub fn is_const_trait_impl_raw(self, def_id: DefId) -> bool { ) } + pub fn local_def_id_to_hir_id(self, local_def_id: LocalDefId) -> HirId { + self.opt_local_def_id_to_hir_id(local_def_id).unwrap() + } + pub fn trait_solver_next(self) -> bool { self.sess.opts.unstable_opts.trait_solver == rustc_session::config::TraitSolver::Next } From 0610df931449375a80bdd7ae03c2fd3116291c82 Mon Sep 17 00:00:00 2001 From: y21 <30553356+y21@users.noreply.github.com> Date: Mon, 13 Feb 2023 15:38:23 +0100 Subject: [PATCH 02/12] lint: don't suggest assume_init for uninhabited types --- compiler/rustc_lint/src/builtin.rs | 8 +++- compiler/rustc_lint/src/lints.rs | 13 +++++- .../validate_uninhabited_zsts.32bit.stderr | 10 +---- .../validate_uninhabited_zsts.64bit.stderr | 10 +---- tests/ui/lint/invalid_value.stderr | 40 ++++--------------- tests/ui/statics/uninhabited-static.stderr | 10 +---- 6 files changed, 32 insertions(+), 59 deletions(-) diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 11fb1f80a11..726042479e9 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2635,7 +2635,13 @@ fn ty_find_init_error<'tcx>( cx.emit_spanned_lint( INVALID_VALUE, expr.span, - BuiltinUnpermittedTypeInit { msg, ty: conjured_ty, label: expr.span, sub }, + BuiltinUnpermittedTypeInit { + msg, + ty: conjured_ty, + label: expr.span, + sub, + tcx: cx.tcx, + }, ); } } diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index 94a43ab0c46..aa6e230dc6d 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -8,7 +8,9 @@ }; use rustc_hir::def_id::DefId; use rustc_macros::{LintDiagnostic, Subdiagnostic}; -use rustc_middle::ty::{PolyExistentialTraitRef, Predicate, Ty, TyCtxt}; +use rustc_middle::ty::{ + inhabitedness::InhabitedPredicate, PolyExistentialTraitRef, Predicate, Ty, TyCtxt, +}; use rustc_session::parse::ParseSess; use rustc_span::{edition::Edition, sym, symbol::Ident, Span, Symbol}; @@ -419,6 +421,7 @@ pub struct BuiltinUnpermittedTypeInit<'a> { pub ty: Ty<'a>, pub label: Span, pub sub: BuiltinUnpermittedTypeInitSub, + pub tcx: TyCtxt<'a>, } impl<'a> DecorateLint<'a, ()> for BuiltinUnpermittedTypeInit<'_> { @@ -428,7 +431,13 @@ fn decorate_lint<'b>( ) -> &'b mut rustc_errors::DiagnosticBuilder<'a, ()> { diag.set_arg("ty", self.ty); diag.span_label(self.label, fluent::lint_builtin_unpermitted_type_init_label); - diag.span_label(self.label, fluent::lint_builtin_unpermitted_type_init_label_suggestion); + if let InhabitedPredicate::True = self.ty.inhabited_predicate(self.tcx) { + // Only suggest late `MaybeUninit::assume_init` initialization if the type is inhabited. + diag.span_label( + self.label, + fluent::lint_builtin_unpermitted_type_init_label_suggestion, + ); + } self.sub.add_to_diagnostic(diag); diag } diff --git a/tests/ui/consts/const-eval/validate_uninhabited_zsts.32bit.stderr b/tests/ui/consts/const-eval/validate_uninhabited_zsts.32bit.stderr index 9710bf476ec..69fb1a59d4f 100644 --- a/tests/ui/consts/const-eval/validate_uninhabited_zsts.32bit.stderr +++ b/tests/ui/consts/const-eval/validate_uninhabited_zsts.32bit.stderr @@ -2,10 +2,7 @@ warning: the type `!` does not permit zero-initialization --> $DIR/validate_uninhabited_zsts.rs:4:14 | LL | unsafe { std::mem::transmute(()) } - | ^^^^^^^^^^^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed | = note: the `!` type has no valid value = note: `#[warn(invalid_value)]` on by default @@ -40,10 +37,7 @@ warning: the type `empty::Empty` does not permit zero-initialization --> $DIR/validate_uninhabited_zsts.rs:21:42 | LL | const BAR: [empty::Empty; 3] = [unsafe { std::mem::transmute(()) }; 3]; - | ^^^^^^^^^^^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed | note: in this struct field --> $DIR/validate_uninhabited_zsts.rs:16:22 diff --git a/tests/ui/consts/const-eval/validate_uninhabited_zsts.64bit.stderr b/tests/ui/consts/const-eval/validate_uninhabited_zsts.64bit.stderr index 9710bf476ec..69fb1a59d4f 100644 --- a/tests/ui/consts/const-eval/validate_uninhabited_zsts.64bit.stderr +++ b/tests/ui/consts/const-eval/validate_uninhabited_zsts.64bit.stderr @@ -2,10 +2,7 @@ warning: the type `!` does not permit zero-initialization --> $DIR/validate_uninhabited_zsts.rs:4:14 | LL | unsafe { std::mem::transmute(()) } - | ^^^^^^^^^^^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed | = note: the `!` type has no valid value = note: `#[warn(invalid_value)]` on by default @@ -40,10 +37,7 @@ warning: the type `empty::Empty` does not permit zero-initialization --> $DIR/validate_uninhabited_zsts.rs:21:42 | LL | const BAR: [empty::Empty; 3] = [unsafe { std::mem::transmute(()) }; 3]; - | ^^^^^^^^^^^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed | note: in this struct field --> $DIR/validate_uninhabited_zsts.rs:16:22 diff --git a/tests/ui/lint/invalid_value.stderr b/tests/ui/lint/invalid_value.stderr index 48fd4169da7..57531b0968f 100644 --- a/tests/ui/lint/invalid_value.stderr +++ b/tests/ui/lint/invalid_value.stderr @@ -61,10 +61,7 @@ error: the type `!` does not permit zero-initialization --> $DIR/invalid_value.rs:65:23 | LL | let _val: ! = mem::zeroed(); - | ^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^ this code causes undefined behavior when executed | = note: the `!` type has no valid value @@ -72,10 +69,7 @@ error: the type `!` does not permit being left uninitialized --> $DIR/invalid_value.rs:66:23 | LL | let _val: ! = mem::uninitialized(); - | ^^^^^^^^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed | = note: the `!` type has no valid value @@ -83,10 +77,7 @@ error: the type `(i32, !)` does not permit zero-initialization --> $DIR/invalid_value.rs:68:30 | LL | let _val: (i32, !) = mem::zeroed(); - | ^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^ this code causes undefined behavior when executed | = note: the `!` type has no valid value @@ -94,10 +85,7 @@ error: the type `(i32, !)` does not permit being left uninitialized --> $DIR/invalid_value.rs:69:30 | LL | let _val: (i32, !) = mem::uninitialized(); - | ^^^^^^^^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed | = note: integers must be initialized @@ -105,10 +93,7 @@ error: the type `Void` does not permit zero-initialization --> $DIR/invalid_value.rs:71:26 | LL | let _val: Void = mem::zeroed(); - | ^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^ this code causes undefined behavior when executed | note: enums with no inhabited variants have no valid value --> $DIR/invalid_value.rs:12:1 @@ -120,10 +105,7 @@ error: the type `Void` does not permit being left uninitialized --> $DIR/invalid_value.rs:72:26 | LL | let _val: Void = mem::uninitialized(); - | ^^^^^^^^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed | note: enums with no inhabited variants have no valid value --> $DIR/invalid_value.rs:12:1 @@ -405,10 +387,7 @@ error: the type `TwoUninhabited` does not permit zero-initialization --> $DIR/invalid_value.rs:104:36 | LL | let _val: TwoUninhabited = mem::zeroed(); - | ^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^ this code causes undefined behavior when executed | note: enums with no inhabited variants have no valid value --> $DIR/invalid_value.rs:42:1 @@ -420,10 +399,7 @@ error: the type `TwoUninhabited` does not permit being left uninitialized --> $DIR/invalid_value.rs:105:36 | LL | let _val: TwoUninhabited = mem::uninitialized(); - | ^^^^^^^^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed | note: enums with no inhabited variants have no valid value --> $DIR/invalid_value.rs:42:1 diff --git a/tests/ui/statics/uninhabited-static.stderr b/tests/ui/statics/uninhabited-static.stderr index ef794bb36ac..437053a4476 100644 --- a/tests/ui/statics/uninhabited-static.stderr +++ b/tests/ui/statics/uninhabited-static.stderr @@ -53,10 +53,7 @@ warning: the type `Void` does not permit zero-initialization --> $DIR/uninhabited-static.rs:12:31 | LL | static VOID2: Void = unsafe { std::mem::transmute(()) }; - | ^^^^^^^^^^^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed | note: enums with no inhabited variants have no valid value --> $DIR/uninhabited-static.rs:4:1 @@ -75,10 +72,7 @@ warning: the type `Void` does not permit zero-initialization --> $DIR/uninhabited-static.rs:16:32 | LL | static NEVER2: Void = unsafe { std::mem::transmute(()) }; - | ^^^^^^^^^^^^^^^^^^^^^^^ - | | - | this code causes undefined behavior when executed - | help: use `MaybeUninit` instead, and only call `assume_init` after initialization is done + | ^^^^^^^^^^^^^^^^^^^^^^^ this code causes undefined behavior when executed | note: enums with no inhabited variants have no valid value --> $DIR/uninhabited-static.rs:4:1 From 4e703a277220a3f52b4772f298535df232b6cb7c Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Wed, 26 Oct 2022 16:38:32 -0300 Subject: [PATCH 03/12] Add associated_items_for_impl_trait_in_trait query --- compiler/rustc_hir/src/definitions.rs | 6 ++- .../src/rmeta/decoder/cstore_impl.rs | 2 + compiler/rustc_metadata/src/rmeta/encoder.rs | 9 +++++ compiler/rustc_metadata/src/rmeta/mod.rs | 1 + compiler/rustc_middle/src/hir/map/mod.rs | 7 ++++ compiler/rustc_middle/src/query/mod.rs | 7 ++++ .../src/typeid/typeid_itanium_cxx_abi.rs | 1 + compiler/rustc_symbol_mangling/src/v0.rs | 1 + compiler/rustc_ty_utils/src/assoc.rs | 38 ++++++++++++++++++- 9 files changed, 68 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_hir/src/definitions.rs b/compiler/rustc_hir/src/definitions.rs index cd3c620cbb7..8ceb176491b 100644 --- a/compiler/rustc_hir/src/definitions.rs +++ b/compiler/rustc_hir/src/definitions.rs @@ -280,6 +280,8 @@ pub enum DefPathData { AnonConst, /// An `impl Trait` type node. ImplTrait, + /// `impl Trait` generated associated type node. + ImplTraitAssocTy, } impl Definitions { @@ -403,7 +405,7 @@ pub fn get_opt_name(&self) -> Option { TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name), Impl | ForeignMod | CrateRoot | Use | GlobalAsm | ClosureExpr | Ctor | AnonConst - | ImplTrait => None, + | ImplTrait | ImplTraitAssocTy => None, } } @@ -422,7 +424,7 @@ pub fn name(&self) -> DefPathDataName { ClosureExpr => DefPathDataName::Anon { namespace: sym::closure }, Ctor => DefPathDataName::Anon { namespace: sym::constructor }, AnonConst => DefPathDataName::Anon { namespace: sym::constant }, - ImplTrait => DefPathDataName::Anon { namespace: sym::opaque }, + ImplTrait | ImplTraitAssocTy => DefPathDataName::Anon { namespace: sym::opaque }, } } } diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index 0bacf51e911..9ca8c1abc16 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -248,6 +248,8 @@ fn into_args(self) -> (DefId, SimplifiedType) { .process_decoded(tcx, || panic!("{def_id:?} does not have trait_impl_trait_tys"))) } + associated_items_for_impl_trait_in_trait => { table_defaulted_array } + visibility => { cdata.get_visibility(def_id.index) } adt_def => { cdata.get_adt_def(def_id.index, tcx) } adt_destructor => { diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 16029822d03..f0dafe73c00 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1129,6 +1129,11 @@ fn should_encode_trait_impl_trait_tys(tcx: TyCtxt<'_>, def_id: DefId) -> bool { }) } +// Return `false` to avoid encoding impl trait in trait, while we don't use the query. +fn should_encode_fn_impl_trait_in_trait<'tcx>(_tcx: TyCtxt<'tcx>, _def_id: DefId) -> bool { + false +} + impl<'a, 'tcx> EncodeContext<'a, 'tcx> { fn encode_attrs(&mut self, def_id: LocalDefId) { let tcx = self.tcx; @@ -1211,6 +1216,10 @@ fn encode_def_ids(&mut self) { { record!(self.tables.trait_impl_trait_tys[def_id] <- table); } + if should_encode_fn_impl_trait_in_trait(tcx, def_id) { + let table = tcx.associated_items_for_impl_trait_in_trait(def_id); + record_defaulted_array!(self.tables.associated_items_for_impl_trait_in_trait[def_id] <- table); + } } let inherent_impls = tcx.with_stable_hashing_context(|hcx| { diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 01691398ad0..a7ec2d790b7 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -354,6 +354,7 @@ fn encode(&self, buf: &mut FileEncoder) -> LazyTables { explicit_item_bounds: Table, Span)>>, inferred_outlives_of: Table, Span)>>, inherent_impls: Table>, + associated_items_for_impl_trait_in_trait: Table>, - optional: attributes: Table>, diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 2eafc356dc3..2df851a7857 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -849,6 +849,13 @@ pub fn expect_trait_item(self, id: LocalDefId) -> &'hir TraitItem<'hir> { } } + pub fn get_fn_output(self, def_id: LocalDefId) -> Option<&'hir FnRetTy<'hir>> { + match self.tcx.hir_owner(OwnerId { def_id }) { + Some(Owner { node, .. }) => node.fn_decl().map(|fn_decl| &fn_decl.output), + _ => None, + } + } + pub fn expect_variant(self, id: HirId) -> &'hir Variant<'hir> { match self.find(id) { Some(Node::Variant(variant)) => variant, diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 8b846f10603..b7858d9f86d 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -767,6 +767,13 @@ desc { |tcx| "comparing impl items against trait for `{}`", tcx.def_path_str(impl_id) } } + /// Given an `fn_def_id`, create and return the associated items for that function. + query associated_items_for_impl_trait_in_trait(fn_def_id: DefId) -> &'tcx [DefId] { + desc { |tcx| "creating associated items for impl trait in trait returned by `{}`", tcx.def_path_str(fn_def_id) } + cache_on_disk_if { fn_def_id.is_local() } + separate_provide_extern + } + /// Given an `impl_id`, return the trait it implements. /// Return `None` if this is an inherent impl. query impl_trait_ref(impl_id: DefId) -> Option>> { diff --git a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs index 949ef04dd4d..f4004784626 100644 --- a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs +++ b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs @@ -396,6 +396,7 @@ fn encode_ty_name(tcx: TyCtxt<'_>, def_id: DefId) -> String { hir::definitions::DefPathData::CrateRoot | hir::definitions::DefPathData::Use | hir::definitions::DefPathData::GlobalAsm + | hir::definitions::DefPathData::ImplTraitAssocTy | hir::definitions::DefPathData::MacroNs(..) | hir::definitions::DefPathData::LifetimeNs(..) => { bug!("encode_ty_name: unexpected `{:?}`", disambiguated_data.data); diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index c58b6a24ab5..d53f0cea6b5 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -791,6 +791,7 @@ fn path_append( | DefPathData::Use | DefPathData::GlobalAsm | DefPathData::Impl + | DefPathData::ImplTraitAssocTy | DefPathData::MacroNs(_) | DefPathData::LifetimeNs(_) => { bug!("symbol_names: unexpected DefPathData: {:?}", disambiguated_data.data) diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs index a6e0f13f698..a6c137d2f3e 100644 --- a/compiler/rustc_ty_utils/src/assoc.rs +++ b/compiler/rustc_ty_utils/src/assoc.rs @@ -1,13 +1,16 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; -use rustc_hir::def_id::DefId; -use rustc_middle::ty::{self, TyCtxt}; +use rustc_hir::def_id::{DefId, LocalDefId}; +use rustc_hir::definitions::DefPathData; +use rustc_hir::intravisit::{self, Visitor}; +use rustc_middle::ty::{self, DefIdTree, TyCtxt}; pub fn provide(providers: &mut ty::query::Providers) { *providers = ty::query::Providers { associated_item, associated_item_def_ids, associated_items, + associated_items_for_impl_trait_in_trait, impl_item_implementor_ids, ..*providers }; @@ -112,3 +115,34 @@ fn associated_item_from_impl_item_ref(impl_item_ref: &hir::ImplItemRef) -> ty::A fn_has_self_parameter: has_self, } } + +fn associated_items_for_impl_trait_in_trait(tcx: TyCtxt<'_>, fn_def_id: DefId) -> &'_ [DefId] { + struct RPITVisitor { + rpits: Vec, + } + + impl<'v> Visitor<'v> for RPITVisitor { + fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) { + if let hir::TyKind::OpaqueDef(item_id, _, _) = ty.kind { + self.rpits.push(item_id.owner_id.def_id) + } + intravisit::walk_ty(self, ty) + } + } + + let mut visitor = RPITVisitor { rpits: Vec::new() }; + + if let Some(output) = tcx.hir().get_fn_output(fn_def_id.expect_local()) { + visitor.visit_fn_ret_ty(output); + + let trait_def_id = tcx.parent(fn_def_id).expect_local(); + + tcx.arena.alloc_from_iter(visitor.rpits.iter().map(|_opaque_ty_def_id| { + let trait_assoc_ty = + tcx.at(output.span()).create_def(trait_def_id, DefPathData::ImplTraitAssocTy); + trait_assoc_ty.def_id().to_def_id() + })) + } else { + &[] + } +} From b7dd609d9c3a6a336091e502caee8a10948cc2c3 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 16 Dec 2022 17:15:34 -0300 Subject: [PATCH 04/12] Add associated_item_for_impl_trait_in_trait query --- compiler/rustc_middle/src/query/mod.rs | 8 ++++++++ compiler/rustc_ty_utils/src/assoc.rs | 24 ++++++++++++++++++------ 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index b7858d9f86d..859fed6ed26 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -774,6 +774,14 @@ separate_provide_extern } + /// Given an impl trait in trait `opaque_ty_def_id`, create and return the corresponding + /// associated item. + query associated_item_for_impl_trait_in_trait(opaque_ty_def_id: LocalDefId) -> LocalDefId { + desc { |tcx| "creates the associated item corresponding to the opaque type `{}`", tcx.def_path_str(opaque_ty_def_id.to_def_id()) } + cache_on_disk_if { true } + separate_provide_extern + } + /// Given an `impl_id`, return the trait it implements. /// Return `None` if this is an inherent impl. query impl_trait_ref(impl_id: DefId) -> Option>> { diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs index a6c137d2f3e..ef725c48da6 100644 --- a/compiler/rustc_ty_utils/src/assoc.rs +++ b/compiler/rustc_ty_utils/src/assoc.rs @@ -1,5 +1,6 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; +use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::definitions::DefPathData; use rustc_hir::intravisit::{self, Visitor}; @@ -11,6 +12,7 @@ pub fn provide(providers: &mut ty::query::Providers) { associated_item_def_ids, associated_items, associated_items_for_impl_trait_in_trait, + associated_item_for_impl_trait_in_trait, impl_item_implementor_ids, ..*providers }; @@ -135,14 +137,24 @@ fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) { if let Some(output) = tcx.hir().get_fn_output(fn_def_id.expect_local()) { visitor.visit_fn_ret_ty(output); - let trait_def_id = tcx.parent(fn_def_id).expect_local(); - - tcx.arena.alloc_from_iter(visitor.rpits.iter().map(|_opaque_ty_def_id| { - let trait_assoc_ty = - tcx.at(output.span()).create_def(trait_def_id, DefPathData::ImplTraitAssocTy); - trait_assoc_ty.def_id().to_def_id() + tcx.arena.alloc_from_iter(visitor.rpits.iter().map(|opaque_ty_def_id| { + tcx.associated_item_for_impl_trait_in_trait(opaque_ty_def_id).to_def_id() })) } else { &[] } } + +fn associated_item_for_impl_trait_in_trait( + tcx: TyCtxt<'_>, + opaque_ty_def_id: LocalDefId, +) -> LocalDefId { + let fn_def_id = tcx.impl_trait_in_trait_parent(opaque_ty_def_id.to_def_id()); + let trait_def_id = tcx.parent(fn_def_id); + assert_eq!(tcx.def_kind(trait_def_id), DefKind::Trait); + + let span = tcx.def_span(opaque_ty_def_id); + let trait_assoc_ty = + tcx.at(span).create_def(trait_def_id.expect_local(), DefPathData::ImplTraitAssocTy); + trait_assoc_ty.def_id() +} From 45b0d9da6b463c73cf1f816e9cbe9483ebc84a6d Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Thu, 16 Feb 2023 18:12:53 -0300 Subject: [PATCH 05/12] Make associated_items_for_impl_trait_in_trait handle impl traits on impls --- compiler/rustc_ty_utils/src/assoc.rs | 76 +++++++++++++++++++++------- 1 file changed, 59 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs index ef725c48da6..0c3322d48f0 100644 --- a/compiler/rustc_ty_utils/src/assoc.rs +++ b/compiler/rustc_ty_utils/src/assoc.rs @@ -119,29 +119,58 @@ fn associated_item_from_impl_item_ref(impl_item_ref: &hir::ImplItemRef) -> ty::A } fn associated_items_for_impl_trait_in_trait(tcx: TyCtxt<'_>, fn_def_id: DefId) -> &'_ [DefId] { - struct RPITVisitor { - rpits: Vec, - } + let parent_def_id = tcx.parent(fn_def_id); - impl<'v> Visitor<'v> for RPITVisitor { - fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) { - if let hir::TyKind::OpaqueDef(item_id, _, _) = ty.kind { - self.rpits.push(item_id.owner_id.def_id) + match tcx.def_kind(parent_def_id) { + DefKind::Trait => { + struct RPITVisitor { + rpits: Vec, + } + + impl<'v> Visitor<'v> for RPITVisitor { + fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) { + if let hir::TyKind::OpaqueDef(item_id, _, _) = ty.kind { + self.rpits.push(item_id.owner_id.def_id) + } + intravisit::walk_ty(self, ty) + } + } + + let mut visitor = RPITVisitor { rpits: Vec::new() }; + + if let Some(output) = tcx.hir().get_fn_output(fn_def_id.expect_local()) { + visitor.visit_fn_ret_ty(output); + + tcx.arena.alloc_from_iter(visitor.rpits.iter().map(|opaque_ty_def_id| { + tcx.associated_item_for_impl_trait_in_trait(opaque_ty_def_id).to_def_id() + })) + } else { + &[] } - intravisit::walk_ty(self, ty) } - } - let mut visitor = RPITVisitor { rpits: Vec::new() }; + DefKind::Impl { .. } => { + let Some(trait_fn_def_id) = tcx.associated_item(fn_def_id).trait_item_def_id else { return &[] }; - if let Some(output) = tcx.hir().get_fn_output(fn_def_id.expect_local()) { - visitor.visit_fn_ret_ty(output); + tcx.arena.alloc_from_iter( + tcx.associated_items_for_impl_trait_in_trait(trait_fn_def_id).iter().map( + move |trait_assoc_def_id| { + impl_associated_item_for_impl_trait_in_trait( + tcx, + trait_assoc_def_id.expect_local(), + fn_def_id.expect_local(), + ) + .to_def_id() + }, + ), + ) + } - tcx.arena.alloc_from_iter(visitor.rpits.iter().map(|opaque_ty_def_id| { - tcx.associated_item_for_impl_trait_in_trait(opaque_ty_def_id).to_def_id() - })) - } else { - &[] + def_kind => bug!( + "associated_items_for_impl_trait_in_trait: {:?} should be Trait or Impl but is {:?}", + parent_def_id, + def_kind + ), } } @@ -158,3 +187,16 @@ fn associated_item_for_impl_trait_in_trait( tcx.at(span).create_def(trait_def_id.expect_local(), DefPathData::ImplTraitAssocTy); trait_assoc_ty.def_id() } + +fn impl_associated_item_for_impl_trait_in_trait( + tcx: TyCtxt<'_>, + trait_assoc_def_id: LocalDefId, + impl_fn_def_id: LocalDefId, +) -> LocalDefId { + let impl_def_id = tcx.local_parent(impl_fn_def_id); + + let span = tcx.def_span(trait_assoc_def_id); + let impl_assoc_ty = tcx.at(span).create_def(impl_def_id, DefPathData::ImplTraitAssocTy); + + impl_assoc_ty.def_id() +} From 5e763b662470f8f35d537215928c83be9b537c0e Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Fri, 17 Feb 2023 16:03:45 -0300 Subject: [PATCH 06/12] Document associated_item methods --- compiler/rustc_middle/src/query/mod.rs | 7 ++++++- compiler/rustc_ty_utils/src/assoc.rs | 11 +++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 859fed6ed26..19b8568042a 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -767,7 +767,12 @@ desc { |tcx| "comparing impl items against trait for `{}`", tcx.def_path_str(impl_id) } } - /// Given an `fn_def_id`, create and return the associated items for that function. + /// Given `fn_def_id` of a trait or of an impl that implements a given trait: + /// if `fn_def_id` is the def id of a function defined inside a trait, then it creates and returns + /// the associated items that correspond to each impl trait in return position for that trait. + /// if `fn_def_id` is the def id of a function defined inside an impl that implements a trait, then it + /// creates and returns the associated items that correspond to each impl trait in return position + /// of the implemented trait. query associated_items_for_impl_trait_in_trait(fn_def_id: DefId) -> &'tcx [DefId] { desc { |tcx| "creating associated items for impl trait in trait returned by `{}`", tcx.def_path_str(fn_def_id) } cache_on_disk_if { fn_def_id.is_local() } diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs index 0c3322d48f0..5cf8060d635 100644 --- a/compiler/rustc_ty_utils/src/assoc.rs +++ b/compiler/rustc_ty_utils/src/assoc.rs @@ -118,6 +118,12 @@ fn associated_item_from_impl_item_ref(impl_item_ref: &hir::ImplItemRef) -> ty::A } } +/// Given an `fn_def_id` of a trait or of an impl that implements a given trait: +/// if `fn_def_id` is the def id of a function defined inside a trait, then it creates and returns +/// the associated items that correspond to each impl trait in return position for that trait. +/// if `fn_def_id` is the def id of a function defined inside an impl that implements a trait, then it +/// creates and returns the associated items that correspond to each impl trait in return position +/// of the implemented trait. fn associated_items_for_impl_trait_in_trait(tcx: TyCtxt<'_>, fn_def_id: DefId) -> &'_ [DefId] { let parent_def_id = tcx.parent(fn_def_id); @@ -174,6 +180,8 @@ fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) { } } +/// Given an `opaque_ty_def_id` corresponding to an impl trait in trait, create and return the +/// corresponding associated item. fn associated_item_for_impl_trait_in_trait( tcx: TyCtxt<'_>, opaque_ty_def_id: LocalDefId, @@ -188,6 +196,9 @@ fn associated_item_for_impl_trait_in_trait( trait_assoc_ty.def_id() } +/// Given an `trait_assoc_def_id` that corresponds to a previously synthethized impl trait in trait +/// into an associated type and an `impl_def_id` corresponding to an impl block, create and return +/// the corresponding associated item inside the impl block. fn impl_associated_item_for_impl_trait_in_trait( tcx: TyCtxt<'_>, trait_assoc_def_id: LocalDefId, From 76ac2705a5a25ebc9038f8574b38597ac9a2b302 Mon Sep 17 00:00:00 2001 From: Milo Moisson Date: Mon, 20 Feb 2023 16:40:46 +0100 Subject: [PATCH 07/12] docs: wrong naming convention in struct keyword doc --- library/std/src/keyword_docs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/keyword_docs.rs b/library/std/src/keyword_docs.rs index e35145c4ade..ea9d5bacc8b 100644 --- a/library/std/src/keyword_docs.rs +++ b/library/std/src/keyword_docs.rs @@ -1568,7 +1568,7 @@ mod static_keyword {} /// /// # Style conventions /// -/// Structs are always written in CamelCase, with few exceptions. While the trailing comma on a +/// Structs are always written in PascalCase, with few exceptions. While the trailing comma on a /// struct's list of fields can be omitted, it's usually kept for convenience in adding and /// removing fields down the line. /// From 18f5f0c4737e277fcab292363bebb7866430d90d Mon Sep 17 00:00:00 2001 From: Milo Moisson Date: Mon, 20 Feb 2023 23:44:21 +0100 Subject: [PATCH 08/12] use UpperCamelCase --- library/std/src/keyword_docs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/keyword_docs.rs b/library/std/src/keyword_docs.rs index ea9d5bacc8b..203c490fa29 100644 --- a/library/std/src/keyword_docs.rs +++ b/library/std/src/keyword_docs.rs @@ -1568,7 +1568,7 @@ mod static_keyword {} /// /// # Style conventions /// -/// Structs are always written in PascalCase, with few exceptions. While the trailing comma on a +/// Structs are always written in UpperCamelCase, with few exceptions. While the trailing comma on a /// struct's list of fields can be omitted, it's usually kept for convenience in adding and /// removing fields down the line. /// From ec9a4ce19e6f1a6c760633bcc8826d47cba27f22 Mon Sep 17 00:00:00 2001 From: Matt Harding Date: Thu, 16 Feb 2023 00:25:28 +0000 Subject: [PATCH 09/12] Explain the default panic hook better This changes the documentation of `std::panic::set_hook` and `take_hook` to better explain how the default panic hook works. In particular the fact that `take_hook` registers the default hook, rather than no hook at all, was missing from the docs. --- library/std/src/panicking.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/library/std/src/panicking.rs b/library/std/src/panicking.rs index b0db3112e22..e59f32af77d 100644 --- a/library/std/src/panicking.rs +++ b/library/std/src/panicking.rs @@ -95,13 +95,16 @@ fn default() -> Hook { static HOOK: RwLock = RwLock::new(Hook::Default); -/// Registers a custom panic hook, replacing any that was previously registered. +/// Registers a custom panic hook, replacing the previously registered hook. /// /// The panic hook is invoked when a thread panics, but before the panic runtime /// is invoked. As such, the hook will run with both the aborting and unwinding -/// runtimes. The default hook prints a message to standard error and generates -/// a backtrace if requested, but this behavior can be customized with the -/// `set_hook` and [`take_hook`] functions. +/// runtimes. +/// +/// The default hook, which is registered at startup, prints a message to standard error and +/// generates a backtrace if requested. This behavior can be customized using the `set_hook` function. +/// The current hook can be retrieved while reinstating the default hook with the [`take_hook`] +/// function. /// /// [`take_hook`]: ./fn.take_hook.html /// @@ -143,13 +146,14 @@ pub fn set_hook(hook: Box) + 'static + Sync + Send>) { drop(old); } -/// Unregisters the current panic hook, returning it. +/// Unregisters the current panic hook and returns it, registering the default hook +/// in its place. /// /// *See also the function [`set_hook`].* /// /// [`set_hook`]: ./fn.set_hook.html /// -/// If no custom hook is registered, the default hook will be returned. +/// If the default hook is registered it will be returned, but remain registered. /// /// # Panics /// From 4f2001aab7fcdf62e7576a879fac9eeb96c8279d Mon Sep 17 00:00:00 2001 From: Boxy Date: Mon, 20 Feb 2023 23:43:25 +0000 Subject: [PATCH 10/12] remove flag --- compiler/rustc_hir_typeck/src/method/probe.rs | 56 +-- compiler/rustc_interface/src/tests.rs | 1 - compiler/rustc_session/src/options.rs | 2 - tests/rustdoc-ui/z-help.stdout | 353 +++++++++--------- 4 files changed, 178 insertions(+), 234 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index eb6c0b7686b..e015d0c765c 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -1095,17 +1095,8 @@ fn pick(mut self) -> PickResult<'tcx> { } fn pick_core(&self) -> Option> { - let pick = self.pick_all_method(Some(&mut vec![])); - - // In this case unstable picking is done by `pick_method`. - if !self.tcx.sess.opts.unstable_opts.pick_stable_methods_before_any_unstable { - return pick; - } - - if pick.is_none() { - return self.pick_all_method(None); - } - pick + // Pick stable methods only first, and consider unstable candidates if not found. + self.pick_all_method(Some(&mut vec![])).or_else(|| self.pick_all_method(None)) } fn pick_all_method( @@ -1244,54 +1235,11 @@ fn pick_const_ptr_method( }) } - fn pick_method_with_unstable(&self, self_ty: Ty<'tcx>) -> Option> { - debug!("pick_method_with_unstable(self_ty={})", self.ty_to_string(self_ty)); - - let mut possibly_unsatisfied_predicates = Vec::new(); - - for (kind, candidates) in - &[("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)] - { - debug!("searching {} candidates", kind); - let res = self.consider_candidates( - self_ty, - candidates, - &mut possibly_unsatisfied_predicates, - Some(&mut vec![]), - ); - if res.is_some() { - return res; - } - } - - for (kind, candidates) in - &[("inherent", &self.inherent_candidates), ("extension", &self.extension_candidates)] - { - debug!("searching unstable {kind} candidates"); - let res = self.consider_candidates( - self_ty, - candidates, - &mut possibly_unsatisfied_predicates, - None, - ); - if res.is_some() { - return res; - } - } - - self.unsatisfied_predicates.borrow_mut().extend(possibly_unsatisfied_predicates); - None - } - fn pick_method( &self, self_ty: Ty<'tcx>, mut unstable_candidates: Option<&mut Vec<(Candidate<'tcx>, Symbol)>>, ) -> Option> { - if !self.tcx.sess.opts.unstable_opts.pick_stable_methods_before_any_unstable { - return self.pick_method_with_unstable(self_ty); - } - debug!("pick_method(self_ty={})", self.ty_to_string(self_ty)); let mut possibly_unsatisfied_predicates = Vec::new(); diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index ac32988d3ac..bfb1e822a26 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -776,7 +776,6 @@ macro_rules! tracked { tracked!(packed_bundled_libs, true); tracked!(panic_abort_tests, true); tracked!(panic_in_drop, PanicStrategy::Abort); - tracked!(pick_stable_methods_before_any_unstable, false); tracked!(plt, Some(true)); tracked!(polonius, true); tracked!(precise_enum_drop_elaboration, false); diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 0d5818bd39c..1f3eb8d4832 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -1567,8 +1567,6 @@ pub(crate) fn parse_proc_macro_execution_strategy( "parse only; do not compile, assemble, or link (default: no)"), perf_stats: bool = (false, parse_bool, [UNTRACKED], "print some performance-related statistics (default: no)"), - pick_stable_methods_before_any_unstable: bool = (true, parse_bool, [TRACKED], - "try to pick stable methods first before picking any unstable methods (default: yes)"), plt: Option = (None, parse_opt_bool, [TRACKED], "whether to use the PLT when calling into shared libraries; only has effect for PIC code on systems with ELF binaries diff --git a/tests/rustdoc-ui/z-help.stdout b/tests/rustdoc-ui/z-help.stdout index 8d0155151b8..58b2f92d150 100644 --- a/tests/rustdoc-ui/z-help.stdout +++ b/tests/rustdoc-ui/z-help.stdout @@ -1,76 +1,76 @@ - -Z allow-features=val -- only allow the listed language features to be enabled in code (comma separated) - -Z always-encode-mir=val -- encode MIR of all functions into the crate metadata (default: no) - -Z asm-comments=val -- generate comments into the assembly (may change behavior) (default: no) - -Z assert-incr-state=val -- assert that the incremental cache is in given state: either `loaded` or `not-loaded`. - -Z assume-incomplete-release=val -- make cfg(version) treat the current version as incomplete (default: no) - -Z binary-dep-depinfo=val -- include artifacts (sysroot, crate dependencies) used during compilation in dep-info (default: no) - -Z box-noalias=val -- emit noalias metadata for box (default: yes) - -Z branch-protection=val -- set options for branch target identification and pointer authentication on AArch64 - -Z cf-protection=val -- instrument control-flow architecture protection - -Z cgu-partitioning-strategy=val -- the codegen unit partitioning strategy to use - -Z codegen-backend=val -- the backend to use - -Z combine-cgu=val -- combine CGUs into a single one - -Z crate-attr=val -- inject the given attribute in the crate - -Z debug-info-for-profiling=val -- emit discriminators and other data necessary for AutoFDO - -Z debug-macros=val -- emit line numbers debug info inside macros (default: no) - -Z deduplicate-diagnostics=val -- deduplicate identical diagnostics (default: yes) - -Z dep-info-omit-d-target=val -- in dep-info output, omit targets for tracking dependencies of the dep-info files themselves (default: no) - -Z dep-tasks=val -- print tasks that execute and the color their dep node gets (requires debug build) (default: no) - -Z diagnostic-width=val -- set the current output width for diagnostic truncation - -Z dlltool=val -- import library generation tool (windows-gnu only) - -Z dont-buffer-diagnostics=val -- emit diagnostics rather than buffering (breaks NLL error downgrading, sorting) (default: no) - -Z drop-tracking=val -- enables drop tracking in generators (default: no) - -Z drop-tracking-mir=val -- enables drop tracking on MIR in generators (default: no) - -Z dual-proc-macros=val -- load proc macros for both target and host, but only link to the target (default: no) - -Z dump-dep-graph=val -- dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv) (default: no) - -Z dump-drop-tracking-cfg=val -- dump drop-tracking control-flow graph as a `.dot` file (default: no) - -Z dump-mir=val -- dump MIR state to file. + -Z allow-features=val -- only allow the listed language features to be enabled in code (comma separated) + -Z always-encode-mir=val -- encode MIR of all functions into the crate metadata (default: no) + -Z asm-comments=val -- generate comments into the assembly (may change behavior) (default: no) + -Z assert-incr-state=val -- assert that the incremental cache is in given state: either `loaded` or `not-loaded`. + -Z assume-incomplete-release=val -- make cfg(version) treat the current version as incomplete (default: no) + -Z binary-dep-depinfo=val -- include artifacts (sysroot, crate dependencies) used during compilation in dep-info (default: no) + -Z box-noalias=val -- emit noalias metadata for box (default: yes) + -Z branch-protection=val -- set options for branch target identification and pointer authentication on AArch64 + -Z cf-protection=val -- instrument control-flow architecture protection + -Z cgu-partitioning-strategy=val -- the codegen unit partitioning strategy to use + -Z codegen-backend=val -- the backend to use + -Z combine-cgu=val -- combine CGUs into a single one + -Z crate-attr=val -- inject the given attribute in the crate + -Z debug-info-for-profiling=val -- emit discriminators and other data necessary for AutoFDO + -Z debug-macros=val -- emit line numbers debug info inside macros (default: no) + -Z deduplicate-diagnostics=val -- deduplicate identical diagnostics (default: yes) + -Z dep-info-omit-d-target=val -- in dep-info output, omit targets for tracking dependencies of the dep-info files themselves (default: no) + -Z dep-tasks=val -- print tasks that execute and the color their dep node gets (requires debug build) (default: no) + -Z diagnostic-width=val -- set the current output width for diagnostic truncation + -Z dlltool=val -- import library generation tool (windows-gnu only) + -Z dont-buffer-diagnostics=val -- emit diagnostics rather than buffering (breaks NLL error downgrading, sorting) (default: no) + -Z drop-tracking=val -- enables drop tracking in generators (default: no) + -Z drop-tracking-mir=val -- enables drop tracking on MIR in generators (default: no) + -Z dual-proc-macros=val -- load proc macros for both target and host, but only link to the target (default: no) + -Z dump-dep-graph=val -- dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv) (default: no) + -Z dump-drop-tracking-cfg=val -- dump drop-tracking control-flow graph as a `.dot` file (default: no) + -Z dump-mir=val -- dump MIR state to file. `val` is used to select which passes and functions to dump. For example: `all` matches all passes and functions, `foo` matches all passes for functions whose name contains 'foo', `foo & ConstProp` only the 'ConstProp' pass for function names containing 'foo', `foo | bar` all passes for function names containing 'foo' or 'bar'. - -Z dump-mir-dataflow=val -- in addition to `.mir` files, create graphviz `.dot` files with dataflow results (default: no) - -Z dump-mir-dir=val -- the directory the MIR is dumped into (default: `mir_dump`) - -Z dump-mir-exclude-pass-number=val -- exclude the pass number when dumping MIR (used in tests) (default: no) - -Z dump-mir-graphviz=val -- in addition to `.mir` files, create graphviz `.dot` files (and with `-Z instrument-coverage`, also create a `.dot` file for the MIR-derived coverage graph) (default: no) - -Z dump-mir-spanview=val -- in addition to `.mir` files, create `.html` files to view spans for all `statement`s (including terminators), only `terminator` spans, or computed `block` spans (one span encompassing a block's terminator and all statements). If `-Z instrument-coverage` is also enabled, create an additional `.html` file showing the computed coverage spans. - -Z dump-mono-stats=val -- output statistics about monomorphization collection - -Z dump-mono-stats-format=val -- the format to use for -Z dump-mono-stats (`markdown` (default) or `json`) - -Z dwarf-version=val -- version of DWARF debug information to emit (default: 2 or 4, depending on platform) - -Z dylib-lto=val -- enables LTO for dylib crate type - -Z emit-stack-sizes=val -- emit a section containing stack size metadata (default: no) - -Z emit-thin-lto=val -- emit the bc module with thin LTO info (default: yes) - -Z export-executable-symbols=val -- export symbols from executables, as if they were dynamic libraries - -Z extra-const-ub-checks=val -- turns on more checks to detect const UB, which can be slow (default: no) - -Z fewer-names=val -- reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR) (default: no) - -Z force-unstable-if-unmarked=val -- force all crates to be `rustc_private` unstable (default: no) - -Z fuel=val -- set the optimization fuel quota for a crate - -Z function-sections=val -- whether each function should go in its own section - -Z future-incompat-test=val -- forces all lints to be future incompatible, used for internal testing (default: no) - -Z gcc-ld=val -- implementation of ld used by cc - -Z graphviz-dark-mode=val -- use dark-themed colors in graphviz output (default: no) - -Z graphviz-font=val -- use the given `fontname` in graphviz output; can be overridden by setting environment variable `RUSTC_GRAPHVIZ_FONT` (default: `Courier, monospace`) - -Z hir-stats=val -- print some statistics about AST and HIR (default: no) - -Z human-readable-cgu-names=val -- generate human-readable, predictable names for codegen units (default: no) - -Z identify-regions=val -- display unnamed regions as `'`, using a non-ident unique id (default: no) - -Z incremental-ignore-spans=val -- ignore spans during ICH computation -- used for testing (default: no) - -Z incremental-info=val -- print high-level information about incremental reuse (or the lack thereof) (default: no) - -Z incremental-relative-spans=val -- hash spans relative to their parent item for incr. comp. (default: no) - -Z incremental-verify-ich=val -- verify incr. comp. hashes of green query instances (default: no) - -Z inline-in-all-cgus=val -- control whether `#[inline]` functions are in all CGUs - -Z inline-llvm=val -- enable LLVM inlining (default: yes) - -Z inline-mir=val -- enable MIR inlining (default: no) - -Z inline-mir-hint-threshold=val -- inlining threshold for functions with inline hint (default: 100) - -Z inline-mir-threshold=val -- a default MIR inlining threshold (default: 50) - -Z input-stats=val -- gather statistics about the input (default: no) - -Z instrument-coverage=val -- instrument the generated code to support LLVM source-based code coverage reports (note, the compiler build config must include `profiler = true`); implies `-C symbol-mangling-version=v0`. Optional values are: + -Z dump-mir-dataflow=val -- in addition to `.mir` files, create graphviz `.dot` files with dataflow results (default: no) + -Z dump-mir-dir=val -- the directory the MIR is dumped into (default: `mir_dump`) + -Z dump-mir-exclude-pass-number=val -- exclude the pass number when dumping MIR (used in tests) (default: no) + -Z dump-mir-graphviz=val -- in addition to `.mir` files, create graphviz `.dot` files (and with `-Z instrument-coverage`, also create a `.dot` file for the MIR-derived coverage graph) (default: no) + -Z dump-mir-spanview=val -- in addition to `.mir` files, create `.html` files to view spans for all `statement`s (including terminators), only `terminator` spans, or computed `block` spans (one span encompassing a block's terminator and all statements). If `-Z instrument-coverage` is also enabled, create an additional `.html` file showing the computed coverage spans. + -Z dump-mono-stats=val -- output statistics about monomorphization collection + -Z dump-mono-stats-format=val -- the format to use for -Z dump-mono-stats (`markdown` (default) or `json`) + -Z dwarf-version=val -- version of DWARF debug information to emit (default: 2 or 4, depending on platform) + -Z dylib-lto=val -- enables LTO for dylib crate type + -Z emit-stack-sizes=val -- emit a section containing stack size metadata (default: no) + -Z emit-thin-lto=val -- emit the bc module with thin LTO info (default: yes) + -Z export-executable-symbols=val -- export symbols from executables, as if they were dynamic libraries + -Z extra-const-ub-checks=val -- turns on more checks to detect const UB, which can be slow (default: no) + -Z fewer-names=val -- reduce memory use by retaining fewer names within compilation artifacts (LLVM-IR) (default: no) + -Z force-unstable-if-unmarked=val -- force all crates to be `rustc_private` unstable (default: no) + -Z fuel=val -- set the optimization fuel quota for a crate + -Z function-sections=val -- whether each function should go in its own section + -Z future-incompat-test=val -- forces all lints to be future incompatible, used for internal testing (default: no) + -Z gcc-ld=val -- implementation of ld used by cc + -Z graphviz-dark-mode=val -- use dark-themed colors in graphviz output (default: no) + -Z graphviz-font=val -- use the given `fontname` in graphviz output; can be overridden by setting environment variable `RUSTC_GRAPHVIZ_FONT` (default: `Courier, monospace`) + -Z hir-stats=val -- print some statistics about AST and HIR (default: no) + -Z human-readable-cgu-names=val -- generate human-readable, predictable names for codegen units (default: no) + -Z identify-regions=val -- display unnamed regions as `'`, using a non-ident unique id (default: no) + -Z incremental-ignore-spans=val -- ignore spans during ICH computation -- used for testing (default: no) + -Z incremental-info=val -- print high-level information about incremental reuse (or the lack thereof) (default: no) + -Z incremental-relative-spans=val -- hash spans relative to their parent item for incr. comp. (default: no) + -Z incremental-verify-ich=val -- verify incr. comp. hashes of green query instances (default: no) + -Z inline-in-all-cgus=val -- control whether `#[inline]` functions are in all CGUs + -Z inline-llvm=val -- enable LLVM inlining (default: yes) + -Z inline-mir=val -- enable MIR inlining (default: no) + -Z inline-mir-hint-threshold=val -- inlining threshold for functions with inline hint (default: 100) + -Z inline-mir-threshold=val -- a default MIR inlining threshold (default: 50) + -Z input-stats=val -- gather statistics about the input (default: no) + -Z instrument-coverage=val -- instrument the generated code to support LLVM source-based code coverage reports (note, the compiler build config must include `profiler = true`); implies `-C symbol-mangling-version=v0`. Optional values are: `=all` (implicit value) `=except-unused-generics` `=except-unused-functions` `=off` (default) - -Z instrument-mcount=val -- insert function instrument code for mcount-based tracing (default: no) - -Z instrument-xray=val -- insert function instrument code for XRay-based tracing (default: no) + -Z instrument-mcount=val -- insert function instrument code for mcount-based tracing (default: no) + -Z instrument-xray=val -- insert function instrument code for XRay-based tracing (default: no) Optional extra settings: `=always` `=never` @@ -79,125 +79,124 @@ `=skip-entry` `=skip-exit` Multiple options can be combined with commas. - -Z keep-hygiene-data=val -- keep hygiene data after analysis (default: no) - -Z layout-seed=val -- seed layout randomization - -Z link-native-libraries=val -- link native libraries in the linker invocation (default: yes) - -Z link-only=val -- link the `.rlink` file generated by `-Z no-link` (default: no) - -Z llvm-plugins=val -- a list LLVM plugins to enable (space separated) - -Z llvm-time-trace=val -- generate JSON tracing data file from LLVM data (default: no) - -Z location-detail=val -- what location details should be tracked when using caller_location, either `none`, or a comma separated list of location details, for which valid options are `file`, `line`, and `column` (default: `file,line,column`) - -Z ls=val -- list the symbols defined by a library crate (default: no) - -Z macro-backtrace=val -- show macro backtraces (default: no) - -Z maximal-hir-to-mir-coverage=val -- save as much information as possible about the correspondence between MIR and HIR as source scopes (default: no) - -Z merge-functions=val -- control the operation of the MergeFunctions LLVM pass, taking the same values as the target option of the same name - -Z meta-stats=val -- gather metadata statistics (default: no) - -Z mir-emit-retag=val -- emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0 (default: no) - -Z mir-enable-passes=val -- use like `-Zmir-enable-passes=+DestProp,-InstCombine`. Forces the specified passes to be enabled, overriding all other checks. Passes that are not specified are enabled or disabled by other flags as usual. - -Z mir-opt-level=val -- MIR optimization level (0-4; default: 1 in non optimized builds and 2 in optimized builds) - -Z mir-pretty-relative-line-numbers=val -- use line numbers relative to the function in mir pretty printing - -Z move-size-limit=val -- the size at which the `large_assignments` lint starts to be emitted - -Z mutable-noalias=val -- emit noalias metadata for mutable references (default: yes) - -Z nll-facts=val -- dump facts from NLL analysis into side files (default: no) - -Z nll-facts-dir=val -- the directory the NLL facts are dumped into (default: `nll-facts`) - -Z no-analysis=val -- parse and expand the source, but run no analysis - -Z no-codegen=val -- run all passes except codegen; no output - -Z no-generate-arange-section=val -- omit DWARF address ranges that give faster lookups - -Z no-jump-tables=val -- disable the jump tables and lookup tables that can be generated from a switch case lowering - -Z no-leak-check=val -- disable the 'leak check' for subtyping; unsound, but useful for tests - -Z no-link=val -- compile without linking - -Z no-parallel-llvm=val -- run LLVM in non-parallel mode (while keeping codegen-units and ThinLTO) - -Z no-profiler-runtime=val -- prevent automatic injection of the profiler_builtins crate - -Z no-unique-section-names=val -- do not use unique names for text and data sections when -Z function-sections is used - -Z normalize-docs=val -- normalize associated items in rustdoc when generating documentation - -Z oom=val -- panic strategy for out-of-memory handling - -Z osx-rpath-install-name=val -- pass `-install_name @rpath/...` to the macOS linker (default: no) - -Z packed-bundled-libs=val -- change rlib format to store native libraries as archives - -Z panic-abort-tests=val -- support compiling tests with panic=abort (default: no) - -Z panic-in-drop=val -- panic strategy for panics in drops - -Z parse-only=val -- parse only; do not compile, assemble, or link (default: no) - -Z perf-stats=val -- print some performance-related statistics (default: no) - -Z pick-stable-methods-before-any-unstable=val -- try to pick stable methods first before picking any unstable methods (default: yes) - -Z plt=val -- whether to use the PLT when calling into shared libraries; + -Z keep-hygiene-data=val -- keep hygiene data after analysis (default: no) + -Z layout-seed=val -- seed layout randomization + -Z link-native-libraries=val -- link native libraries in the linker invocation (default: yes) + -Z link-only=val -- link the `.rlink` file generated by `-Z no-link` (default: no) + -Z llvm-plugins=val -- a list LLVM plugins to enable (space separated) + -Z llvm-time-trace=val -- generate JSON tracing data file from LLVM data (default: no) + -Z location-detail=val -- what location details should be tracked when using caller_location, either `none`, or a comma separated list of location details, for which valid options are `file`, `line`, and `column` (default: `file,line,column`) + -Z ls=val -- list the symbols defined by a library crate (default: no) + -Z macro-backtrace=val -- show macro backtraces (default: no) + -Z maximal-hir-to-mir-coverage=val -- save as much information as possible about the correspondence between MIR and HIR as source scopes (default: no) + -Z merge-functions=val -- control the operation of the MergeFunctions LLVM pass, taking the same values as the target option of the same name + -Z meta-stats=val -- gather metadata statistics (default: no) + -Z mir-emit-retag=val -- emit Retagging MIR statements, interpreted e.g., by miri; implies -Zmir-opt-level=0 (default: no) + -Z mir-enable-passes=val -- use like `-Zmir-enable-passes=+DestProp,-InstCombine`. Forces the specified passes to be enabled, overriding all other checks. Passes that are not specified are enabled or disabled by other flags as usual. + -Z mir-opt-level=val -- MIR optimization level (0-4; default: 1 in non optimized builds and 2 in optimized builds) + -Z mir-pretty-relative-line-numbers=val -- use line numbers relative to the function in mir pretty printing + -Z move-size-limit=val -- the size at which the `large_assignments` lint starts to be emitted + -Z mutable-noalias=val -- emit noalias metadata for mutable references (default: yes) + -Z nll-facts=val -- dump facts from NLL analysis into side files (default: no) + -Z nll-facts-dir=val -- the directory the NLL facts are dumped into (default: `nll-facts`) + -Z no-analysis=val -- parse and expand the source, but run no analysis + -Z no-codegen=val -- run all passes except codegen; no output + -Z no-generate-arange-section=val -- omit DWARF address ranges that give faster lookups + -Z no-jump-tables=val -- disable the jump tables and lookup tables that can be generated from a switch case lowering + -Z no-leak-check=val -- disable the 'leak check' for subtyping; unsound, but useful for tests + -Z no-link=val -- compile without linking + -Z no-parallel-llvm=val -- run LLVM in non-parallel mode (while keeping codegen-units and ThinLTO) + -Z no-profiler-runtime=val -- prevent automatic injection of the profiler_builtins crate + -Z no-unique-section-names=val -- do not use unique names for text and data sections when -Z function-sections is used + -Z normalize-docs=val -- normalize associated items in rustdoc when generating documentation + -Z oom=val -- panic strategy for out-of-memory handling + -Z osx-rpath-install-name=val -- pass `-install_name @rpath/...` to the macOS linker (default: no) + -Z packed-bundled-libs=val -- change rlib format to store native libraries as archives + -Z panic-abort-tests=val -- support compiling tests with panic=abort (default: no) + -Z panic-in-drop=val -- panic strategy for panics in drops + -Z parse-only=val -- parse only; do not compile, assemble, or link (default: no) + -Z perf-stats=val -- print some performance-related statistics (default: no) + -Z plt=val -- whether to use the PLT when calling into shared libraries; only has effect for PIC code on systems with ELF binaries (default: PLT is disabled if full relro is enabled) - -Z polonius=val -- enable polonius-based borrow-checker (default: no) - -Z polymorphize=val -- perform polymorphization analysis - -Z pre-link-arg=val -- a single extra argument to prepend the linker invocation (can be used several times) - -Z pre-link-args=val -- extra arguments to prepend to the linker invocation (space separated) - -Z precise-enum-drop-elaboration=val -- use a more precise version of drop elaboration for matches on enums (default: yes). This results in better codegen, but has caused miscompilations on some tier 2 platforms. See #77382 and #74551. - -Z print-fuel=val -- make rustc print the total optimization fuel used by a crate - -Z print-llvm-passes=val -- print the LLVM optimization passes being run (default: no) - -Z print-mono-items=val -- print the result of the monomorphization collection pass - -Z print-type-sizes=val -- print layout information for each type encountered (default: no) - -Z proc-macro-backtrace=val -- show backtraces for panics during proc-macro execution (default: no) - -Z proc-macro-execution-strategy=val -- how to run proc-macro code (default: same-thread) - -Z profile=val -- insert profiling code (default: no) - -Z profile-closures=val -- profile size of closures - -Z profile-emit=val -- file path to emit profiling data at runtime when using 'profile' (default based on relative source path) - -Z profile-sample-use=val -- use the given `.prof` file for sampled profile-guided optimization (also known as AutoFDO) - -Z profiler-runtime=val -- name of the profiler runtime crate to automatically inject (default: `profiler_builtins`) - -Z query-dep-graph=val -- enable queries of the dependency graph for regression testing (default: no) - -Z randomize-layout=val -- randomize the layout of types (default: no) - -Z relax-elf-relocations=val -- whether ELF relocations can be relaxed - -Z relro-level=val -- choose which RELRO level to use - -Z remap-cwd-prefix=val -- remap paths under the current working directory to this path prefix - -Z report-delayed-bugs=val -- immediately print bugs registered with `delay_span_bug` (default: no) - -Z sanitizer=val -- use a sanitizer - -Z sanitizer-memory-track-origins=val -- enable origins tracking in MemorySanitizer - -Z sanitizer-recover=val -- enable recovery for selected sanitizers - -Z saturating-float-casts=val -- make float->int casts UB-free: numbers outside the integer type's range are clipped to the max/min integer respectively, and NaN is mapped to 0 (default: yes) - -Z self-profile=val -- run the self profiler and output the raw event data - -Z self-profile-counter=val -- counter used by the self profiler (default: `wall-time`), one of: + -Z polonius=val -- enable polonius-based borrow-checker (default: no) + -Z polymorphize=val -- perform polymorphization analysis + -Z pre-link-arg=val -- a single extra argument to prepend the linker invocation (can be used several times) + -Z pre-link-args=val -- extra arguments to prepend to the linker invocation (space separated) + -Z precise-enum-drop-elaboration=val -- use a more precise version of drop elaboration for matches on enums (default: yes). This results in better codegen, but has caused miscompilations on some tier 2 platforms. See #77382 and #74551. + -Z print-fuel=val -- make rustc print the total optimization fuel used by a crate + -Z print-llvm-passes=val -- print the LLVM optimization passes being run (default: no) + -Z print-mono-items=val -- print the result of the monomorphization collection pass + -Z print-type-sizes=val -- print layout information for each type encountered (default: no) + -Z proc-macro-backtrace=val -- show backtraces for panics during proc-macro execution (default: no) + -Z proc-macro-execution-strategy=val -- how to run proc-macro code (default: same-thread) + -Z profile=val -- insert profiling code (default: no) + -Z profile-closures=val -- profile size of closures + -Z profile-emit=val -- file path to emit profiling data at runtime when using 'profile' (default based on relative source path) + -Z profile-sample-use=val -- use the given `.prof` file for sampled profile-guided optimization (also known as AutoFDO) + -Z profiler-runtime=val -- name of the profiler runtime crate to automatically inject (default: `profiler_builtins`) + -Z query-dep-graph=val -- enable queries of the dependency graph for regression testing (default: no) + -Z randomize-layout=val -- randomize the layout of types (default: no) + -Z relax-elf-relocations=val -- whether ELF relocations can be relaxed + -Z relro-level=val -- choose which RELRO level to use + -Z remap-cwd-prefix=val -- remap paths under the current working directory to this path prefix + -Z report-delayed-bugs=val -- immediately print bugs registered with `delay_span_bug` (default: no) + -Z sanitizer=val -- use a sanitizer + -Z sanitizer-memory-track-origins=val -- enable origins tracking in MemorySanitizer + -Z sanitizer-recover=val -- enable recovery for selected sanitizers + -Z saturating-float-casts=val -- make float->int casts UB-free: numbers outside the integer type's range are clipped to the max/min integer respectively, and NaN is mapped to 0 (default: yes) + -Z self-profile=val -- run the self profiler and output the raw event data + -Z self-profile-counter=val -- counter used by the self profiler (default: `wall-time`), one of: `wall-time` (monotonic clock, i.e. `std::time::Instant`) `instructions:u` (retired instructions, userspace-only) `instructions-minus-irqs:u` (subtracting hardware interrupt counts for extra accuracy) - -Z self-profile-events=val -- specify the events recorded by the self profiler; + -Z self-profile-events=val -- specify the events recorded by the self profiler; for example: `-Z self-profile-events=default,query-keys` all options: none, all, default, generic-activity, query-provider, query-cache-hit query-blocked, incr-cache-load, incr-result-hashing, query-keys, function-args, args, llvm, artifact-sizes - -Z share-generics=val -- make the current crate share its generic instantiations - -Z show-span=val -- show spans for compiler debugging (expr|pat|ty) - -Z simulate-remapped-rust-src-base=val -- simulate the effect of remap-debuginfo = true at bootstrapping by remapping path to rust's source base directory. only meant for testing purposes - -Z span-debug=val -- forward proc_macro::Span's `Debug` impl to `Span` - -Z span-free-formats=val -- exclude spans when debug-printing compiler state (default: no) - -Z split-dwarf-inlining=val -- provide minimal debug info in the object/executable to facilitate online symbolication/stack traces in the absence of .dwo/.dwp files when using Split DWARF - -Z split-dwarf-kind=val -- split dwarf variant (only if -Csplit-debuginfo is enabled and on relevant platform) + -Z share-generics=val -- make the current crate share its generic instantiations + -Z show-span=val -- show spans for compiler debugging (expr|pat|ty) + -Z simulate-remapped-rust-src-base=val -- simulate the effect of remap-debuginfo = true at bootstrapping by remapping path to rust's source base directory. only meant for testing purposes + -Z span-debug=val -- forward proc_macro::Span's `Debug` impl to `Span` + -Z span-free-formats=val -- exclude spans when debug-printing compiler state (default: no) + -Z split-dwarf-inlining=val -- provide minimal debug info in the object/executable to facilitate online symbolication/stack traces in the absence of .dwo/.dwp files when using Split DWARF + -Z split-dwarf-kind=val -- split dwarf variant (only if -Csplit-debuginfo is enabled and on relevant platform) (default: `split`) `split`: sections which do not require relocation are written into a DWARF object (`.dwo`) file which is ignored by the linker `single`: sections which do not require relocation are written into object file but ignored by the linker - -Z src-hash-algorithm=val -- hash algorithm of source files in debug info (`md5`, `sha1`, or `sha256`) - -Z stack-protector=val -- control stack smash protection strategy (`rustc --print stack-protector-strategies` for details) - -Z strict-init-checks=val -- control if mem::uninitialized and mem::zeroed panic on more UB - -Z strip=val -- tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`) - -Z symbol-mangling-version=val -- which mangling version to use for symbol names ('legacy' (default) or 'v0') - -Z teach=val -- show extended diagnostic help (default: no) - -Z temps-dir=val -- the directory the intermediate files are written to - -Z terminal-urls=val -- use the OSC 8 hyperlink terminal specification to print hyperlinks in the compiler output - -Z thinlto=val -- enable ThinLTO when possible - -Z thir-unsafeck=val -- use the THIR unsafety checker (default: no) - -Z threads=val -- use a thread pool with N threads - -Z time-llvm-passes=val -- measure time of each LLVM pass (default: no) - -Z time-passes=val -- measure time of each rustc pass (default: no) - -Z tiny-const-eval-limit=val -- sets a tiny, non-configurable limit for const eval; useful for compiler tests - -Z tls-model=val -- choose the TLS model to use (`rustc --print tls-models` for details) - -Z trace-macros=val -- for every macro invocation, print its name and arguments (default: no) - -Z track-diagnostics=val -- tracks where in rustc a diagnostic was emitted - -Z trait-solver=val -- specify the trait solver mode used by rustc (default: classic) - -Z translate-additional-ftl=val -- additional fluent translation to preferentially use (for testing translation) - -Z translate-directionality-markers=val -- emit directionality isolation markers in translated diagnostics - -Z translate-lang=val -- language identifier for diagnostic output - -Z translate-remapped-path-to-local-path=val -- translate remapped paths into local paths when possible (default: yes) - -Z trap-unreachable=val -- generate trap instructions for unreachable intrinsics (default: use target setting, usually yes) - -Z treat-err-as-bug=val -- treat error number `val` that occurs as bug - -Z trim-diagnostic-paths=val -- in diagnostics, use heuristics to shorten paths referring to items - -Z tune-cpu=val -- select processor to schedule for (`rustc --print target-cpus` for details) - -Z ui-testing=val -- emit compiler diagnostics in a form suitable for UI testing (default: no) - -Z uninit-const-chunk-threshold=val -- allow generating const initializers with mixed init/uninit chunks, and set the maximum number of chunks for which this is allowed (default: 16) - -Z unleash-the-miri-inside-of-you=val -- take the brakes off const evaluation. NOTE: this is unsound (default: no) - -Z unpretty=val -- present the input source, unstable (and less-pretty) variants; + -Z src-hash-algorithm=val -- hash algorithm of source files in debug info (`md5`, `sha1`, or `sha256`) + -Z stack-protector=val -- control stack smash protection strategy (`rustc --print stack-protector-strategies` for details) + -Z strict-init-checks=val -- control if mem::uninitialized and mem::zeroed panic on more UB + -Z strip=val -- tell the linker which information to strip (`none` (default), `debuginfo` or `symbols`) + -Z symbol-mangling-version=val -- which mangling version to use for symbol names ('legacy' (default) or 'v0') + -Z teach=val -- show extended diagnostic help (default: no) + -Z temps-dir=val -- the directory the intermediate files are written to + -Z terminal-urls=val -- use the OSC 8 hyperlink terminal specification to print hyperlinks in the compiler output + -Z thinlto=val -- enable ThinLTO when possible + -Z thir-unsafeck=val -- use the THIR unsafety checker (default: no) + -Z threads=val -- use a thread pool with N threads + -Z time-llvm-passes=val -- measure time of each LLVM pass (default: no) + -Z time-passes=val -- measure time of each rustc pass (default: no) + -Z tiny-const-eval-limit=val -- sets a tiny, non-configurable limit for const eval; useful for compiler tests + -Z tls-model=val -- choose the TLS model to use (`rustc --print tls-models` for details) + -Z trace-macros=val -- for every macro invocation, print its name and arguments (default: no) + -Z track-diagnostics=val -- tracks where in rustc a diagnostic was emitted + -Z trait-solver=val -- specify the trait solver mode used by rustc (default: classic) + -Z translate-additional-ftl=val -- additional fluent translation to preferentially use (for testing translation) + -Z translate-directionality-markers=val -- emit directionality isolation markers in translated diagnostics + -Z translate-lang=val -- language identifier for diagnostic output + -Z translate-remapped-path-to-local-path=val -- translate remapped paths into local paths when possible (default: yes) + -Z trap-unreachable=val -- generate trap instructions for unreachable intrinsics (default: use target setting, usually yes) + -Z treat-err-as-bug=val -- treat error number `val` that occurs as bug + -Z trim-diagnostic-paths=val -- in diagnostics, use heuristics to shorten paths referring to items + -Z tune-cpu=val -- select processor to schedule for (`rustc --print target-cpus` for details) + -Z ui-testing=val -- emit compiler diagnostics in a form suitable for UI testing (default: no) + -Z uninit-const-chunk-threshold=val -- allow generating const initializers with mixed init/uninit chunks, and set the maximum number of chunks for which this is allowed (default: 16) + -Z unleash-the-miri-inside-of-you=val -- take the brakes off const evaluation. NOTE: this is unsound (default: no) + -Z unpretty=val -- present the input source, unstable (and less-pretty) variants; `normal`, `identified`, `expanded`, `expanded,identified`, `expanded,hygiene` (with internal representations), @@ -207,11 +206,11 @@ `hir,typed` (HIR with types for each node), `hir-tree` (dump the raw HIR), `mir` (the MIR), or `mir-cfg` (graphviz formatted MIR) - -Z unsound-mir-opts=val -- enable unsound and buggy MIR optimizations (default: no) - -Z unstable-options=val -- adds unstable command line options to rustc interface (default: no) - -Z use-ctors-section=val -- use legacy .ctors section for initializers rather than .init_array - -Z validate-mir=val -- validate MIR after each transformation - -Z verbose=val -- in general, enable more debug printouts (default: no) - -Z verify-llvm-ir=val -- verify LLVM IR (default: no) - -Z virtual-function-elimination=val -- enables dead virtual function elimination optimization. Requires `-Clto[=[fat,yes]]` - -Z wasi-exec-model=val -- whether to build a wasi command or reactor + -Z unsound-mir-opts=val -- enable unsound and buggy MIR optimizations (default: no) + -Z unstable-options=val -- adds unstable command line options to rustc interface (default: no) + -Z use-ctors-section=val -- use legacy .ctors section for initializers rather than .init_array + -Z validate-mir=val -- validate MIR after each transformation + -Z verbose=val -- in general, enable more debug printouts (default: no) + -Z verify-llvm-ir=val -- verify LLVM IR (default: no) + -Z virtual-function-elimination=val -- enables dead virtual function elimination optimization. Requires `-Clto[=[fat,yes]]` + -Z wasi-exec-model=val -- whether to build a wasi command or reactor From 2895731e5ebf546820493c9eec2cf8108ac701ee Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 20 Feb 2023 23:57:16 +0000 Subject: [PATCH 11/12] Name placeholder in some region errors --- .../src/infer/error_reporting/mod.rs | 27 ++++++++++++------- ...ject-safety-supertrait-mentions-GAT.stderr | 5 ++++ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index bb7947e3141..dd6a76f754d 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -129,21 +129,16 @@ pub(super) fn note_and_explain_region<'tcx>( alt_span: Option, ) { let (description, span) = match *region { - ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => { - msg_span_from_free_region(tcx, region, alt_span) + ty::ReEarlyBound(_) | ty::ReFree(_) | ty::RePlaceholder(_) | ty::ReStatic => { + msg_span_from_named_region(tcx, region, alt_span) } - ty::RePlaceholder(_) => return, - ty::ReError(_) => return, - // FIXME(#13998) RePlaceholder should probably print like - // ReFree rather than dumping Debug output on the user. - // // We shouldn't really be having unification failures with ReVar // and ReLateBound though. ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => { - (format!("lifetime {:?}", region), alt_span) + (format!("lifetime `{region}`"), alt_span) } }; @@ -157,12 +152,12 @@ fn explain_free_region<'tcx>( region: ty::Region<'tcx>, suffix: &str, ) { - let (description, span) = msg_span_from_free_region(tcx, region, None); + let (description, span) = msg_span_from_named_region(tcx, region, None); label_msg_span(err, prefix, description, span, suffix); } -fn msg_span_from_free_region<'tcx>( +fn msg_span_from_named_region<'tcx>( tcx: TyCtxt<'tcx>, region: ty::Region<'tcx>, alt_span: Option, @@ -173,6 +168,18 @@ fn msg_span_from_free_region<'tcx>( (msg, Some(span)) } ty::ReStatic => ("the static lifetime".to_owned(), alt_span), + ty::RePlaceholder(ty::PlaceholderRegion { + name: ty::BoundRegionKind::BrNamed(def_id, name), + .. + }) => (format!("the lifetime `{name}` as defined here"), Some(tcx.def_span(def_id))), + ty::RePlaceholder(ty::PlaceholderRegion { + name: ty::BoundRegionKind::BrAnon(_, Some(span)), + .. + }) => (format!("the anonymous lifetime defined here"), Some(span)), + ty::RePlaceholder(ty::PlaceholderRegion { + name: ty::BoundRegionKind::BrAnon(_, None), + .. + }) => (format!("an anonymous lifetime"), None), _ => bug!("{:?}", region), } } diff --git a/tests/ui/object-safety/object-safety-supertrait-mentions-GAT.stderr b/tests/ui/object-safety/object-safety-supertrait-mentions-GAT.stderr index f05b0cd6538..40429fe756f 100644 --- a/tests/ui/object-safety/object-safety-supertrait-mentions-GAT.stderr +++ b/tests/ui/object-safety/object-safety-supertrait-mentions-GAT.stderr @@ -1,5 +1,10 @@ error[E0311]: the parameter type `Self` may not live long enough | +note: the parameter type `Self` must be valid for the lifetime `'a` as defined here... + --> $DIR/object-safety-supertrait-mentions-GAT.rs:9:26 + | +LL | trait SuperTrait: for<'a> GatTrait = T> { + | ^^ = help: consider adding an explicit lifetime bound `Self: 'a`... = note: ...so that the type `Self` will meet its required lifetime bounds... note: ...that is required by this bound From dfc4a580f2e03eea67d8739d1ac369a5ceef71b5 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 21 Feb 2023 02:01:26 +0000 Subject: [PATCH 12/12] Add a test for default trait method with RPITITs --- .../in-trait/default-method-constraint.rs | 17 +++++++++++++++++ .../in-trait/default-method-constraint.stderr | 11 +++++++++++ 2 files changed, 28 insertions(+) create mode 100644 tests/ui/impl-trait/in-trait/default-method-constraint.rs create mode 100644 tests/ui/impl-trait/in-trait/default-method-constraint.stderr diff --git a/tests/ui/impl-trait/in-trait/default-method-constraint.rs b/tests/ui/impl-trait/in-trait/default-method-constraint.rs new file mode 100644 index 00000000000..8c50cc29586 --- /dev/null +++ b/tests/ui/impl-trait/in-trait/default-method-constraint.rs @@ -0,0 +1,17 @@ +// check-pass + +// This didn't work in the previous default RPITIT method hack attempt + +#![feature(return_position_impl_trait_in_trait)] +//~^ WARN the feature `return_position_impl_trait_in_trait` is incomplete + +trait Foo { + fn bar(x: bool) -> impl Sized { + if x { + let _: u32 = Self::bar(!x); + } + Default::default() + } +} + +fn main() {} diff --git a/tests/ui/impl-trait/in-trait/default-method-constraint.stderr b/tests/ui/impl-trait/in-trait/default-method-constraint.stderr new file mode 100644 index 00000000000..5e18605aa4c --- /dev/null +++ b/tests/ui/impl-trait/in-trait/default-method-constraint.stderr @@ -0,0 +1,11 @@ +warning: the feature `return_position_impl_trait_in_trait` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/default-method-constraint.rs:5:12 + | +LL | #![feature(return_position_impl_trait_in_trait)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #91611 for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted +