From 8bd79fda87af6aa16b08b67c61a6db58f1e519ad Mon Sep 17 00:00:00 2001 From: clubby789 Date: Fri, 10 Feb 2023 21:40:12 +0000 Subject: Pass arguments to `x` subcommands with `--` --- src/bootstrap/check.rs | 3 ++- src/bootstrap/config.rs | 5 +++++ src/bootstrap/flags.rs | 11 +++++++++++ src/bootstrap/run.rs | 1 + src/bootstrap/test.rs | 1 + 5 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/bootstrap/check.rs b/src/bootstrap/check.rs index 4b8a58e87b6..76c7e695bf3 100644 --- a/src/bootstrap/check.rs +++ b/src/bootstrap/check.rs @@ -58,9 +58,10 @@ fn args(builder: &Builder<'_>) -> Vec { clippy_lint_warn.iter().for_each(|v| clippy_lint_levels.push(format!("-W{}", v))); clippy_lint_forbid.iter().for_each(|v| clippy_lint_levels.push(format!("-F{}", v))); args.extend(clippy_lint_levels); + args.extend(builder.config.free_args.clone()); args } else { - vec![] + builder.config.free_args.clone() } } diff --git a/src/bootstrap/config.rs b/src/bootstrap/config.rs index e5fad538969..cd027a4abb7 100644 --- a/src/bootstrap/config.rs +++ b/src/bootstrap/config.rs @@ -97,6 +97,10 @@ pub struct Config { pub cmd: Subcommand, pub incremental: bool, pub dry_run: DryRun, + /// Arguments appearing after `--` to be forwarded to tools, + /// e.g. `--fix-broken` or test arguments. + pub free_args: Vec, + /// `None` if we shouldn't download CI compiler artifacts, or the commit to download if we should. #[cfg(not(test))] download_rustc_commit: Option, @@ -866,6 +870,7 @@ impl Config { config.keep_stage = flags.keep_stage; config.keep_stage_std = flags.keep_stage_std; config.color = flags.color; + config.free_args = flags.free_args.clone().unwrap_or_default(); if let Some(value) = flags.deny_warnings { config.deny_warnings = value; } diff --git a/src/bootstrap/flags.rs b/src/bootstrap/flags.rs index 52c3dc0bf75..f196c6c82b0 100644 --- a/src/bootstrap/flags.rs +++ b/src/bootstrap/flags.rs @@ -80,6 +80,10 @@ pub struct Flags { pub llvm_profile_generate: bool, pub llvm_bolt_profile_generate: bool, pub llvm_bolt_profile_use: Option, + + /// Arguments appearing after `--` to be forwarded to tools, + /// e.g. `--fix-broken` or test arguments. + pub free_args: Option>, } #[derive(Debug)] @@ -156,6 +160,12 @@ impl Default for Subcommand { impl Flags { pub fn parse(args: &[String]) -> Flags { + let (args, free_args) = if let Some(pos) = args.iter().position(|s| s == "--") { + let (args, free) = args.split_at(pos); + (args, Some(free[1..].to_vec())) + } else { + (args, None) + }; let mut subcommand_help = String::from( "\ Usage: x.py [options] [...] @@ -706,6 +716,7 @@ Arguments: llvm_profile_generate: matches.opt_present("llvm-profile-generate"), llvm_bolt_profile_generate: matches.opt_present("llvm-bolt-profile-generate"), llvm_bolt_profile_use: matches.opt_str("llvm-bolt-profile-use"), + free_args, } } } diff --git a/src/bootstrap/run.rs b/src/bootstrap/run.rs index e0280854541..e14440f57a8 100644 --- a/src/bootstrap/run.rs +++ b/src/bootstrap/run.rs @@ -183,6 +183,7 @@ impl Step for Miri { // Forward arguments. miri.arg("--").arg("--target").arg(target.rustc_target_arg()); miri.args(builder.config.cmd.args()); + miri.args(&builder.config.free_args); // miri tests need to know about the stage sysroot miri.env("MIRI_SYSROOT", &miri_sysroot); diff --git a/src/bootstrap/test.rs b/src/bootstrap/test.rs index 8a0c532cfb0..b91efc32060 100644 --- a/src/bootstrap/test.rs +++ b/src/bootstrap/test.rs @@ -1584,6 +1584,7 @@ note: if you're sure you want to do this, please open an issue as to why. In the .collect(); test_args.append(&mut builder.config.cmd.test_args()); + test_args.extend(builder.config.free_args.iter().map(|s| s.as_str())); // On Windows, replace forward slashes in test-args by backslashes // so the correct filters are passed to libtest -- cgit 1.4.1-3-g733a5 From d90f7df67491fc90f51832ff3936b6dacc214321 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 15 Feb 2023 08:12:29 -0800 Subject: wasm: Register the `relaxed-simd` target feature This WebAssembly proposal is likely to reach stage 4 soon so this starts the support in Rust for the proposal by adding a target feature that can be enabled via attributes for the stdarch project to bind the intrinsics. --- compiler/rustc_codegen_ssa/src/target_features.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index 739963fffd1..a1de07dcc83 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -286,6 +286,7 @@ const WASM_ALLOWED_FEATURES: &[(&str, Option)] = &[ ("mutable-globals", Some(sym::wasm_target_feature)), ("nontrapping-fptoint", Some(sym::wasm_target_feature)), ("reference-types", Some(sym::wasm_target_feature)), + ("relaxed-simd", Some(sym::wasm_target_feature)), ("sign-ext", Some(sym::wasm_target_feature)), ("simd128", None), // tidy-alphabetical-end -- cgit 1.4.1-3-g733a5 From 262a344d7245f242586d5d5a0cc5c892f45891c4 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Sat, 4 Feb 2023 01:59:17 +0000 Subject: Add feature gate for non_lifetime_binders --- compiler/rustc_ast_passes/src/ast_validation.rs | 34 ------------- compiler/rustc_ast_passes/src/feature_gate.rs | 55 +++++++++++++++++++++- compiler/rustc_attr/src/builtin.rs | 2 +- compiler/rustc_feature/src/active.rs | 2 + compiler/rustc_session/src/errors.rs | 22 ++++++--- compiler/rustc_session/src/parse.rs | 6 +-- compiler/rustc_span/src/symbol.rs | 1 + tests/ui/bounds-lifetime.stderr | 11 ++++- tests/ui/closures/binder/disallow-const.stderr | 6 ++- tests/ui/closures/binder/disallow-ty.stderr | 6 ++- .../cfg-generic-params.stderr | 46 +++++++++++------- .../feature-gate-non_lifetime_binders.rs | 4 ++ .../feature-gate-non_lifetime_binders.stderr | 12 +++++ .../hrtb-wrong-kind.stderr | 11 ++++- .../ui/parser/recover-fn-ptr-with-generics.stderr | 12 ++--- 15 files changed, 155 insertions(+), 75 deletions(-) create mode 100644 tests/ui/feature-gates/feature-gate-non_lifetime_binders.rs create mode 100644 tests/ui/feature-gates/feature-gate-non_lifetime_binders.stderr diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 902b4b1a1ec..632c626b27e 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -294,27 +294,6 @@ impl<'a> AstValidator<'a> { } } - fn check_late_bound_lifetime_defs(&self, params: &[GenericParam]) { - // Check only lifetime parameters are present and that the lifetime - // parameters that are present have no bounds. - let non_lt_param_spans: Vec<_> = params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - if !param.bounds.is_empty() { - let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect(); - self.session.emit_err(ForbiddenLifetimeBound { spans }); - } - None - } - _ => Some(param.ident.span), - }) - .collect(); - if !non_lt_param_spans.is_empty() { - self.session.emit_err(ForbiddenNonLifetimeParam { spans: non_lt_param_spans }); - } - } - fn check_fn_decl(&self, fn_decl: &FnDecl, self_semantic: SelfSemantic) { self.check_decl_num_args(fn_decl); self.check_decl_cvaradic_pos(fn_decl); @@ -745,7 +724,6 @@ impl<'a> AstValidator<'a> { ) .emit(); }); - self.check_late_bound_lifetime_defs(&bfty.generic_params); if let Extern::Implicit(_) = bfty.ext { let sig_span = self.session.source_map().next_point(ty.span.shrink_to_lo()); self.maybe_lint_missing_abi(sig_span, ty.id); @@ -1318,9 +1296,6 @@ impl<'a> Visitor<'a> for AstValidator<'a> { for predicate in &generics.where_clause.predicates { match predicate { WherePredicate::BoundPredicate(bound_pred) => { - // A type binding, eg `for<'c> Foo: Send+Clone+'c` - self.check_late_bound_lifetime_defs(&bound_pred.bound_generic_params); - // This is slightly complicated. Our representation for poly-trait-refs contains a single // binder and thus we only allow a single level of quantification. However, // the syntax of Rust permits quantification in two places in where clauses, @@ -1396,11 +1371,6 @@ impl<'a> Visitor<'a> for AstValidator<'a> { visit::walk_param_bound(self, bound) } - fn visit_poly_trait_ref(&mut self, t: &'a PolyTraitRef) { - self.check_late_bound_lifetime_defs(&t.bound_generic_params); - visit::walk_poly_trait_ref(self, t); - } - fn visit_variant_data(&mut self, s: &'a VariantData) { self.with_banned_assoc_ty_bound(|this| visit::walk_struct_def(this, s)) } @@ -1437,10 +1407,6 @@ impl<'a> Visitor<'a> for AstValidator<'a> { .emit(); } - if let FnKind::Closure(ClosureBinder::For { generic_params, .. }, ..) = fk { - self.check_late_bound_lifetime_defs(generic_params); - } - if let FnKind::Fn( _, _, diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 89ba6f936d1..3af2ef4e727 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -11,6 +11,8 @@ use rustc_span::symbol::sym; use rustc_span::Span; use rustc_target::spec::abi; +use crate::errors::ForbiddenLifetimeBound; + macro_rules! gate_feature_fn { ($visitor: expr, $has_feature: expr, $span: expr, $name: expr, $explain: expr, $help: expr) => {{ let (visitor, has_feature, span, name, explain, help) = @@ -136,6 +138,34 @@ impl<'a> PostExpansionVisitor<'a> { } ImplTraitVisitor { vis: self }.visit_ty(ty); } + + fn check_late_bound_lifetime_defs(&self, params: &[ast::GenericParam]) { + // Check only lifetime parameters are present and that the lifetime + // parameters that are present have no bounds. + let non_lt_param_spans: Vec<_> = params + .iter() + .filter_map(|param| match param.kind { + ast::GenericParamKind::Lifetime { .. } => None, + _ => Some(param.ident.span), + }) + .collect(); + // FIXME: gate_feature_post doesn't really handle multispans... + if !non_lt_param_spans.is_empty() && !self.features.non_lifetime_binders { + feature_err( + &self.sess.parse_sess, + sym::non_lifetime_binders, + non_lt_param_spans, + rustc_errors::fluent::ast_passes_forbidden_non_lifetime_param, + ) + .emit(); + } + for param in params { + if !param.bounds.is_empty() { + let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect(); + self.sess.emit_err(ForbiddenLifetimeBound { spans }); + } + } + } } impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { @@ -147,7 +177,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { .. }) = attr_info { - gate_feature_fn!(self, has_feature, attr.span, *name, descr); + gate_feature_fn!(self, has_feature, attr.span, *name, *descr); } // Check unstable flavors of the `#[doc]` attribute. if attr.has_name(sym::doc) { @@ -306,6 +336,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { ast::TyKind::BareFn(bare_fn_ty) => { // Function pointers cannot be `const` self.check_extern(bare_fn_ty.ext, ast::Const::No); + self.check_late_bound_lifetime_defs(&bare_fn_ty.generic_params); } ast::TyKind::Never => { gate_feature_post!(&self, never_type, ty.span, "the `!` type is experimental"); @@ -318,6 +349,19 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { visit::walk_ty(self, ty) } + fn visit_generics(&mut self, g: &'a ast::Generics) { + for predicate in &g.where_clause.predicates { + match predicate { + ast::WherePredicate::BoundPredicate(bound_pred) => { + // A type binding, eg `for<'c> Foo: Send+Clone+'c` + self.check_late_bound_lifetime_defs(&bound_pred.bound_generic_params); + } + _ => {} + } + } + visit::walk_generics(self, g); + } + fn visit_fn_ret_ty(&mut self, ret_ty: &'a ast::FnRetTy) { if let ast::FnRetTy::Ty(output_ty) = ret_ty { if let ast::TyKind::Never = output_ty.kind { @@ -437,12 +481,21 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { visit::walk_pat(self, pattern) } + fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef) { + self.check_late_bound_lifetime_defs(&t.bound_generic_params); + visit::walk_poly_trait_ref(self, t); + } + fn visit_fn(&mut self, fn_kind: FnKind<'a>, span: Span, _: NodeId) { if let Some(header) = fn_kind.header() { // Stability of const fn methods are covered in `visit_assoc_item` below. self.check_extern(header.ext, header.constness); } + if let FnKind::Closure(ast::ClosureBinder::For { generic_params, .. }, ..) = fn_kind { + self.check_late_bound_lifetime_defs(generic_params); + } + if fn_kind.ctxt() != Some(FnCtxt::Foreign) && fn_kind.decl().c_variadic() { gate_feature_post!(&self, c_variadic, span, "C-variadic functions are unstable"); } diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs index 40531c1c164..3d240108b4a 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -731,7 +731,7 @@ pub fn eval_condition( sess, sym::cfg_target_compact, cfg.span, - &"compact `cfg(target(..))` is experimental and subject to change" + "compact `cfg(target(..))` is experimental and subject to change" ).emit(); } diff --git a/compiler/rustc_feature/src/active.rs b/compiler/rustc_feature/src/active.rs index 21d211eefbe..b96766f4245 100644 --- a/compiler/rustc_feature/src/active.rs +++ b/compiler/rustc_feature/src/active.rs @@ -473,6 +473,8 @@ declare_features! ( (active, no_sanitize, "1.42.0", Some(39699), None), /// Allows using the `non_exhaustive_omitted_patterns` lint. (active, non_exhaustive_omitted_patterns_lint, "1.57.0", Some(89554), None), + /// Allows `for` binders in where-clauses + (incomplete, non_lifetime_binders, "CURRENT_RUSTC_VERSION", Some(1), None), /// Allows making `dyn Trait` well-formed even if `Trait` is not object safe. /// In that case, `dyn Trait: Trait` does not hold. Moreover, coercions and /// casts in safe Rust to `dyn Trait` for such a `Trait` is also forbidden. diff --git a/compiler/rustc_session/src/errors.rs b/compiler/rustc_session/src/errors.rs index c851145440b..bb1327fc7c7 100644 --- a/compiler/rustc_session/src/errors.rs +++ b/compiler/rustc_session/src/errors.rs @@ -4,7 +4,7 @@ use crate::cgu_reuse_tracker::CguReuse; use crate::parse::ParseSess; use rustc_ast::token; use rustc_ast::util::literal::LitError; -use rustc_errors::MultiSpan; +use rustc_errors::{error_code, DiagnosticMessage, EmissionGuarantee, IntoDiagnostic, MultiSpan}; use rustc_macros::Diagnostic; use rustc_span::{Span, Symbol}; use rustc_target::spec::{SplitDebuginfo, StackProtector, TargetTriple}; @@ -27,12 +27,22 @@ pub struct CguNotRecorded<'a> { pub cgu_name: &'a str, } -#[derive(Diagnostic)] -#[diag(session_feature_gate_error, code = "E0658")] -pub struct FeatureGateError<'a> { - #[primary_span] +pub struct FeatureGateError { pub span: MultiSpan, - pub explain: &'a str, + pub explain: DiagnosticMessage, +} + +impl<'a, T: EmissionGuarantee> IntoDiagnostic<'a, T> for FeatureGateError { + #[track_caller] + fn into_diagnostic( + self, + handler: &'a rustc_errors::Handler, + ) -> rustc_errors::DiagnosticBuilder<'a, T> { + let mut diag = handler.struct_diagnostic(self.explain); + diag.set_span(self.span); + diag.code(error_code!(E0658)); + diag + } } #[derive(Subdiagnostic)] diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 2aa8ca9e4a9..cbdcc5581e5 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -88,7 +88,7 @@ pub fn feature_err<'a>( sess: &'a ParseSess, feature: Symbol, span: impl Into, - explain: &str, + explain: impl Into, ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { feature_err_issue(sess, feature, span, GateIssue::Language, explain) } @@ -103,7 +103,7 @@ pub fn feature_err_issue<'a>( feature: Symbol, span: impl Into, issue: GateIssue, - explain: &str, + explain: impl Into, ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { let span = span.into(); @@ -114,7 +114,7 @@ pub fn feature_err_issue<'a>( .map(|err| err.cancel()); } - let mut err = sess.create_err(FeatureGateError { span, explain }); + let mut err = sess.create_err(FeatureGateError { span, explain: explain.into() }); add_feature_diagnostics_for_issue(&mut err, sess, feature, issue); err } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 56835a2466a..37d2aea42ad 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1016,6 +1016,7 @@ symbols! { non_ascii_idents, non_exhaustive, non_exhaustive_omitted_patterns_lint, + non_lifetime_binders, non_modrs_mods, nontemporal_store, noop_method_borrow, diff --git a/tests/ui/bounds-lifetime.stderr b/tests/ui/bounds-lifetime.stderr index a0395ed4904..a3427e21cde 100644 --- a/tests/ui/bounds-lifetime.stderr +++ b/tests/ui/bounds-lifetime.stderr @@ -16,17 +16,24 @@ error: lifetime bounds cannot be used in this context LL | type C = for<'b, 'a: 'b +> fn(); | ^^ -error: only lifetime parameters can be used in this context +error[E0658]: only lifetime parameters can be used in this context --> $DIR/bounds-lifetime.rs:4:18 | LL | type D = for<'a, T> fn(); | ^ + | + = note: see issue #1 for more information + = help: add `#![feature(non_lifetime_binders)]` to the crate attributes to enable -error: only lifetime parameters can be used in this context +error[E0658]: only lifetime parameters can be used in this context --> $DIR/bounds-lifetime.rs:5:18 | LL | type E = dyn for Fn(); | ^ + | + = note: see issue #1 for more information + = help: add `#![feature(non_lifetime_binders)]` to the crate attributes to enable error: aborting due to 5 previous errors +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/closures/binder/disallow-const.stderr b/tests/ui/closures/binder/disallow-const.stderr index 3c3b43d8cf3..9f4deaa774d 100644 --- a/tests/ui/closures/binder/disallow-const.stderr +++ b/tests/ui/closures/binder/disallow-const.stderr @@ -1,8 +1,12 @@ -error: only lifetime parameters can be used in this context +error[E0658]: only lifetime parameters can be used in this context --> $DIR/disallow-const.rs:4:15 | LL | for || -> () {}; | ^ + | + = note: see issue #1 for more information + = help: add `#![feature(non_lifetime_binders)]` to the crate attributes to enable error: aborting due to previous error +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/closures/binder/disallow-ty.stderr b/tests/ui/closures/binder/disallow-ty.stderr index 51b6773edea..22882ca2ba6 100644 --- a/tests/ui/closures/binder/disallow-ty.stderr +++ b/tests/ui/closures/binder/disallow-ty.stderr @@ -1,8 +1,12 @@ -error: only lifetime parameters can be used in this context +error[E0658]: only lifetime parameters can be used in this context --> $DIR/disallow-ty.rs:4:9 | LL | for || -> () {}; | ^ + | + = note: see issue #1 for more information + = help: add `#![feature(non_lifetime_binders)]` to the crate attributes to enable error: aborting due to previous error +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/conditional-compilation/cfg-generic-params.stderr b/tests/ui/conditional-compilation/cfg-generic-params.stderr index 4d6560e96e5..69b0f741156 100644 --- a/tests/ui/conditional-compilation/cfg-generic-params.stderr +++ b/tests/ui/conditional-compilation/cfg-generic-params.stderr @@ -1,21 +1,3 @@ -error: only lifetime parameters can be used in this context - --> $DIR/cfg-generic-params.rs:7:45 - | -LL | type FnBad = for<#[cfg(no)] 'a, #[cfg(yes)] T> fn(); - | ^ - -error: only lifetime parameters can be used in this context - --> $DIR/cfg-generic-params.rs:11:51 - | -LL | type PolyBad = dyn for<#[cfg(no)] 'a, #[cfg(yes)] T> Copy; - | ^ - -error: only lifetime parameters can be used in this context - --> $DIR/cfg-generic-params.rs:15:54 - | -LL | struct WhereBad where for<#[cfg(no)] 'a, #[cfg(yes)] T> u8: Copy; - | ^ - error: cannot find attribute `unknown` in this scope --> $DIR/cfg-generic-params.rs:19:29 | @@ -46,5 +28,33 @@ error: cannot find attribute `unknown` in this scope LL | struct WhereYes where for<#[cfg_attr(yes, unknown)] 'a> u8: Copy; | ^^^^^^^ +error[E0658]: only lifetime parameters can be used in this context + --> $DIR/cfg-generic-params.rs:7:45 + | +LL | type FnBad = for<#[cfg(no)] 'a, #[cfg(yes)] T> fn(); + | ^ + | + = note: see issue #1 for more information + = help: add `#![feature(non_lifetime_binders)]` to the crate attributes to enable + +error[E0658]: only lifetime parameters can be used in this context + --> $DIR/cfg-generic-params.rs:11:51 + | +LL | type PolyBad = dyn for<#[cfg(no)] 'a, #[cfg(yes)] T> Copy; + | ^ + | + = note: see issue #1 for more information + = help: add `#![feature(non_lifetime_binders)]` to the crate attributes to enable + +error[E0658]: only lifetime parameters can be used in this context + --> $DIR/cfg-generic-params.rs:15:54 + | +LL | struct WhereBad where for<#[cfg(no)] 'a, #[cfg(yes)] T> u8: Copy; + | ^ + | + = note: see issue #1 for more information + = help: add `#![feature(non_lifetime_binders)]` to the crate attributes to enable + error: aborting due to 8 previous errors +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/feature-gates/feature-gate-non_lifetime_binders.rs b/tests/ui/feature-gates/feature-gate-non_lifetime_binders.rs new file mode 100644 index 00000000000..221e9133fcc --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-non_lifetime_binders.rs @@ -0,0 +1,4 @@ +fn foo() where for T:, {} +//~^ ERROR only lifetime parameters can be used in this context + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-non_lifetime_binders.stderr b/tests/ui/feature-gates/feature-gate-non_lifetime_binders.stderr new file mode 100644 index 00000000000..75645e32401 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-non_lifetime_binders.stderr @@ -0,0 +1,12 @@ +error[E0658]: only lifetime parameters can be used in this context + --> $DIR/feature-gate-non_lifetime_binders.rs:1:20 + | +LL | fn foo() where for T:, {} + | ^ + | + = note: see issue #1 for more information + = help: add `#![feature(non_lifetime_binders)]` to the crate attributes to enable + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/higher-rank-trait-bounds/hrtb-wrong-kind.stderr b/tests/ui/higher-rank-trait-bounds/hrtb-wrong-kind.stderr index f31aa554634..d605c9e0df7 100644 --- a/tests/ui/higher-rank-trait-bounds/hrtb-wrong-kind.stderr +++ b/tests/ui/higher-rank-trait-bounds/hrtb-wrong-kind.stderr @@ -1,14 +1,21 @@ -error: only lifetime parameters can be used in this context +error[E0658]: only lifetime parameters can be used in this context --> $DIR/hrtb-wrong-kind.rs:1:18 | LL | fn a() where for T: Copy {} | ^ + | + = note: see issue #1 for more information + = help: add `#![feature(non_lifetime_binders)]` to the crate attributes to enable -error: only lifetime parameters can be used in this context +error[E0658]: only lifetime parameters can be used in this context --> $DIR/hrtb-wrong-kind.rs:4:24 | LL | fn b() where for [(); C]: Copy {} | ^ + | + = note: see issue #1 for more information + = help: add `#![feature(non_lifetime_binders)]` to the crate attributes to enable error: aborting due to 2 previous errors +For more information about this error, try `rustc --explain E0658`. diff --git a/tests/ui/parser/recover-fn-ptr-with-generics.stderr b/tests/ui/parser/recover-fn-ptr-with-generics.stderr index 1da9c18571b..069fcffe9a0 100644 --- a/tests/ui/parser/recover-fn-ptr-with-generics.stderr +++ b/tests/ui/parser/recover-fn-ptr-with-generics.stderr @@ -88,12 +88,6 @@ error: expected identifier, found `>` LL | type QuiteBroken = fn(); | ^ expected identifier -error: lifetime bounds cannot be used in this context - --> $DIR/recover-fn-ptr-with-generics.rs:22:26 - | -LL | let _: extern fn<'a: 'static>(); - | ^^^^^^^ - error[E0412]: cannot find type `T` in this scope --> $DIR/recover-fn-ptr-with-generics.rs:5:27 | @@ -106,6 +100,12 @@ error[E0412]: cannot find type `T` in this scope LL | type Identity = fn(T) -> T; | ^ not found in this scope +error: lifetime bounds cannot be used in this context + --> $DIR/recover-fn-ptr-with-generics.rs:22:26 + | +LL | let _: extern fn<'a: 'static>(); + | ^^^^^^^ + error: aborting due to 12 previous errors For more information about this error, try `rustc --explain E0412`. -- cgit 1.4.1-3-g733a5 From eff2cb7760ffd1ed06fd5a68ba04dcb6689106f6 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 6 Feb 2023 18:38:52 +0000 Subject: Rename some region-specific stuff --- compiler/rustc_hir_analysis/src/astconv/mod.rs | 14 +- compiler/rustc_hir_analysis/src/collect.rs | 4 +- .../rustc_hir_analysis/src/collect/generics_of.rs | 11 +- .../rustc_hir_analysis/src/collect/lifetimes.rs | 1874 ------------------- .../src/collect/resolve_bound_vars.rs | 1884 ++++++++++++++++++++ .../nice_region_error/find_anon_type.rs | 30 +- compiler/rustc_lint/src/builtin.rs | 12 +- compiler/rustc_metadata/src/rmeta/mod.rs | 2 +- compiler/rustc_middle/src/middle/mod.rs | 2 +- .../rustc_middle/src/middle/resolve_bound_vars.rs | 55 + .../rustc_middle/src/middle/resolve_lifetime.rs | 55 - compiler/rustc_middle/src/query/mod.rs | 6 +- compiler/rustc_middle/src/ty/context.rs | 6 +- compiler/rustc_middle/src/ty/parameterized.rs | 2 +- compiler/rustc_middle/src/ty/query.rs | 2 +- compiler/rustc_mir_transform/src/ssa.rs | 2 +- compiler/rustc_passes/src/check_attr.rs | 2 +- compiler/rustc_resolve/src/late.rs | 4 +- src/librustdoc/clean/mod.rs | 10 +- src/tools/clippy/clippy_lints/src/ptr.rs | 4 +- 20 files changed, 1996 insertions(+), 1985 deletions(-) delete mode 100644 compiler/rustc_hir_analysis/src/collect/lifetimes.rs create mode 100644 compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs create mode 100644 compiler/rustc_middle/src/middle/resolve_bound_vars.rs delete mode 100644 compiler/rustc_middle/src/middle/resolve_lifetime.rs diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index 8c753a99a09..7690f44a23d 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -14,7 +14,7 @@ use crate::errors::{ AmbiguousLifetimeBound, MultipleRelaxedDefaultBounds, TraitObjectDeclaredWithNoTraits, TypeofReservedKeywordUsed, ValueOfAssociatedStructAlreadySpecified, }; -use crate::middle::resolve_lifetime as rl; +use crate::middle::resolve_bound_vars as rbv; use crate::require_c_abi_if_c_variadic; use rustc_ast::TraitObjectSyntax; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; @@ -225,10 +225,10 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let tcx = self.tcx(); let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id)); - match tcx.named_region(lifetime.hir_id) { - Some(rl::Region::Static) => tcx.lifetimes.re_static, + match tcx.named_bound_var(lifetime.hir_id) { + Some(rbv::ResolvedArg::StaticLifetime) => tcx.lifetimes.re_static, - Some(rl::Region::LateBound(debruijn, index, def_id)) => { + Some(rbv::ResolvedArg::LateBound(debruijn, index, def_id)) => { let name = lifetime_name(def_id.expect_local()); let br = ty::BoundRegion { var: ty::BoundVar::from_u32(index), @@ -237,7 +237,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { tcx.mk_region(ty::ReLateBound(debruijn, br)) } - Some(rl::Region::EarlyBound(def_id)) => { + Some(rbv::ResolvedArg::EarlyBound(def_id)) => { let name = tcx.hir().ty_param_name(def_id.expect_local()); let item_def_id = tcx.hir().ty_param_owner(def_id.expect_local()); let generics = tcx.generics_of(item_def_id); @@ -245,7 +245,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, index, name })) } - Some(rl::Region::Free(scope, id)) => { + Some(rbv::ResolvedArg::Free(scope, id)) => { let name = lifetime_name(id.expect_local()); tcx.mk_region(ty::ReFree(ty::FreeRegion { scope, @@ -1604,7 +1604,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { self.ast_region_to_region(lifetime, None) } else { self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| { - if tcx.named_region(lifetime.hir_id).is_some() { + if tcx.named_bound_var(lifetime.hir_id).is_some() { self.ast_region_to_region(lifetime, None) } else { self.re_infer(None, span).unwrap_or_else(|| { diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 9f33d84ab52..bd1d81c7207 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -41,8 +41,8 @@ use std::iter; mod generics_of; mod item_bounds; -mod lifetimes; mod predicates_of; +mod resolve_bound_vars; mod type_of; /////////////////////////////////////////////////////////////////////////// @@ -53,7 +53,7 @@ fn collect_mod_item_types(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { } pub fn provide(providers: &mut Providers) { - lifetimes::provide(providers); + resolve_bound_vars::provide(providers); *providers = Providers { opt_const_param_of: type_of::opt_const_param_of, type_of: type_of::type_of, diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index 014ee9fcc20..7bcaeadbcf6 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -1,4 +1,4 @@ -use crate::middle::resolve_lifetime as rl; +use crate::middle::resolve_bound_vars as rbv; use hir::{ intravisit::{self, Visitor}, GenericParamKind, HirId, Node, @@ -394,10 +394,11 @@ fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option {} - Some(rl::Region::LateBound(debruijn, _, _)) if debruijn < self.outer_index => {} - Some(rl::Region::LateBound(..) | rl::Region::Free(..)) | None => { + match self.tcx.named_bound_var(lt.hir_id) { + Some(rbv::ResolvedArg::StaticLifetime | rbv::ResolvedArg::EarlyBound(..)) => {} + Some(rbv::ResolvedArg::LateBound(debruijn, _, _)) + if debruijn < self.outer_index => {} + Some(rbv::ResolvedArg::LateBound(..) | rbv::ResolvedArg::Free(..)) | None => { self.has_late_bound_regions = Some(lt.ident.span); } } diff --git a/compiler/rustc_hir_analysis/src/collect/lifetimes.rs b/compiler/rustc_hir_analysis/src/collect/lifetimes.rs deleted file mode 100644 index d8606f759b2..00000000000 --- a/compiler/rustc_hir_analysis/src/collect/lifetimes.rs +++ /dev/null @@ -1,1874 +0,0 @@ -//! Resolution of early vs late bound lifetimes. -//! -//! Name resolution for lifetimes is performed on the AST and embedded into HIR. From this -//! information, typechecking needs to transform the lifetime parameters into bound lifetimes. -//! Lifetimes can be early-bound or late-bound. Construction of typechecking terms needs to visit -//! the types in HIR to identify late-bound lifetimes and assign their Debruijn indices. This file -//! is also responsible for assigning their semantics to implicit lifetimes in trait objects. - -use rustc_ast::walk_list; -use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; -use rustc_errors::struct_span_err; -use rustc_hir as hir; -use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::LocalDefId; -use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::{GenericArg, GenericParam, GenericParamKind, HirIdMap, LifetimeName, Node}; -use rustc_middle::bug; -use rustc_middle::hir::nested_filter; -use rustc_middle::middle::resolve_lifetime::*; -use rustc_middle::ty::{self, ir::TypeVisitor, DefIdTree, TyCtxt, TypeSuperVisitable}; -use rustc_span::def_id::DefId; -use rustc_span::symbol::{sym, Ident}; -use rustc_span::Span; -use std::fmt; - -trait RegionExt { - fn early(param: &GenericParam<'_>) -> (LocalDefId, Region); - - fn late(index: u32, param: &GenericParam<'_>) -> (LocalDefId, Region); - - fn id(&self) -> Option; - - fn shifted(self, amount: u32) -> Region; -} - -impl RegionExt for Region { - fn early(param: &GenericParam<'_>) -> (LocalDefId, Region) { - debug!("Region::early: def_id={:?}", param.def_id); - (param.def_id, Region::EarlyBound(param.def_id.to_def_id())) - } - - fn late(idx: u32, param: &GenericParam<'_>) -> (LocalDefId, Region) { - let depth = ty::INNERMOST; - debug!( - "Region::late: idx={:?}, param={:?} depth={:?} def_id={:?}", - idx, param, depth, param.def_id, - ); - (param.def_id, Region::LateBound(depth, idx, param.def_id.to_def_id())) - } - - fn id(&self) -> Option { - match *self { - Region::Static => None, - - Region::EarlyBound(id) | Region::LateBound(_, _, id) | Region::Free(_, id) => Some(id), - } - } - - fn shifted(self, amount: u32) -> Region { - match self { - Region::LateBound(debruijn, idx, id) => { - Region::LateBound(debruijn.shifted_in(amount), idx, id) - } - _ => self, - } - } -} - -/// Maps the id of each lifetime reference to the lifetime decl -/// that it corresponds to. -/// -/// FIXME. This struct gets converted to a `ResolveLifetimes` for -/// actual use. It has the same data, but indexed by `LocalDefId`. This -/// is silly. -#[derive(Debug, Default)] -struct NamedRegionMap { - // maps from every use of a named (not anonymous) lifetime to a - // `Region` describing how that region is bound - defs: HirIdMap, - - // Maps relevant hir items to the bound vars on them. These include: - // - function defs - // - function pointers - // - closures - // - trait refs - // - bound types (like `T` in `for<'a> T<'a>: Foo`) - late_bound_vars: HirIdMap>, -} - -struct LifetimeContext<'a, 'tcx> { - tcx: TyCtxt<'tcx>, - map: &'a mut NamedRegionMap, - scope: ScopeRef<'a>, -} - -#[derive(Debug)] -enum Scope<'a> { - /// Declares lifetimes, and each can be early-bound or late-bound. - /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and - /// it should be shifted by the number of `Binder`s in between the - /// declaration `Binder` and the location it's referenced from. - Binder { - /// We use an IndexMap here because we want these lifetimes in order - /// for diagnostics. - lifetimes: FxIndexMap, - - scope_type: BinderScopeType, - - /// The late bound vars for a given item are stored by `HirId` to be - /// queried later. However, if we enter an elision scope, we have to - /// later append the elided bound vars to the list and need to know what - /// to append to. - hir_id: hir::HirId, - - s: ScopeRef<'a>, - - /// If this binder comes from a where clause, specify how it was created. - /// This is used to diagnose inaccessible lifetimes in APIT: - /// ```ignore (illustrative) - /// fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {} - /// ``` - where_bound_origin: Option, - }, - - /// Lifetimes introduced by a fn are scoped to the call-site for that fn, - /// if this is a fn body, otherwise the original definitions are used. - /// Unspecified lifetimes are inferred, unless an elision scope is nested, - /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`. - Body { - id: hir::BodyId, - s: ScopeRef<'a>, - }, - - /// A scope which either determines unspecified lifetimes or errors - /// on them (e.g., due to ambiguity). - Elision { - s: ScopeRef<'a>, - }, - - /// Use a specific lifetime (if `Some`) or leave it unset (to be - /// inferred in a function body or potentially error outside one), - /// for the default choice of lifetime in a trait object type. - ObjectLifetimeDefault { - lifetime: Option, - s: ScopeRef<'a>, - }, - - /// When we have nested trait refs, we concatenate late bound vars for inner - /// trait refs from outer ones. But we also need to include any HRTB - /// lifetimes encountered when identifying the trait that an associated type - /// is declared on. - Supertrait { - lifetimes: Vec, - s: ScopeRef<'a>, - }, - - TraitRefBoundary { - s: ScopeRef<'a>, - }, - - Root { - opt_parent_item: Option, - }, -} - -#[derive(Copy, Clone, Debug)] -enum BinderScopeType { - /// Any non-concatenating binder scopes. - Normal, - /// Within a syntactic trait ref, there may be multiple poly trait refs that - /// are nested (under the `associated_type_bounds` feature). The binders of - /// the inner poly trait refs are extended from the outer poly trait refs - /// and don't increase the late bound depth. If you had - /// `T: for<'a> Foo Baz<'a, 'b>>`, then the `for<'b>` scope - /// would be `Concatenating`. This also used in trait refs in where clauses - /// where we have two binders `for<> T: for<> Foo` (I've intentionally left - /// out any lifetimes because they aren't needed to show the two scopes). - /// The inner `for<>` has a scope of `Concatenating`. - Concatenating, -} - -// A helper struct for debugging scopes without printing parent scopes -struct TruncatedScopeDebug<'a>(&'a Scope<'a>); - -impl<'a> fmt::Debug for TruncatedScopeDebug<'a> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self.0 { - Scope::Binder { lifetimes, scope_type, hir_id, where_bound_origin, s: _ } => f - .debug_struct("Binder") - .field("lifetimes", lifetimes) - .field("scope_type", scope_type) - .field("hir_id", hir_id) - .field("where_bound_origin", where_bound_origin) - .field("s", &"..") - .finish(), - Scope::Body { id, s: _ } => { - f.debug_struct("Body").field("id", id).field("s", &"..").finish() - } - Scope::Elision { s: _ } => f.debug_struct("Elision").field("s", &"..").finish(), - Scope::ObjectLifetimeDefault { lifetime, s: _ } => f - .debug_struct("ObjectLifetimeDefault") - .field("lifetime", lifetime) - .field("s", &"..") - .finish(), - Scope::Supertrait { lifetimes, s: _ } => f - .debug_struct("Supertrait") - .field("lifetimes", lifetimes) - .field("s", &"..") - .finish(), - Scope::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(), - Scope::Root { opt_parent_item } => { - f.debug_struct("Root").field("opt_parent_item", &opt_parent_item).finish() - } - } - } -} - -type ScopeRef<'a> = &'a Scope<'a>; - -pub(crate) fn provide(providers: &mut ty::query::Providers) { - *providers = ty::query::Providers { - resolve_lifetimes, - - named_region_map: |tcx, id| tcx.resolve_lifetimes(id).defs.get(&id), - is_late_bound_map, - object_lifetime_default, - late_bound_vars_map: |tcx, id| tcx.resolve_lifetimes(id).late_bound_vars.get(&id), - - ..*providers - }; -} - -/// Computes the `ResolveLifetimes` map that contains data for an entire `Item`. -/// You should not read the result of this query directly, but rather use -/// `named_region_map`, `is_late_bound_map`, etc. -#[instrument(level = "debug", skip(tcx))] -fn resolve_lifetimes(tcx: TyCtxt<'_>, local_def_id: hir::OwnerId) -> ResolveLifetimes { - let mut named_region_map = - NamedRegionMap { defs: Default::default(), late_bound_vars: Default::default() }; - let mut visitor = LifetimeContext { - tcx, - map: &mut named_region_map, - scope: &Scope::Root { opt_parent_item: None }, - }; - match tcx.hir().owner(local_def_id) { - hir::OwnerNode::Item(item) => visitor.visit_item(item), - hir::OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item), - hir::OwnerNode::TraitItem(item) => { - let scope = - Scope::Root { opt_parent_item: Some(tcx.local_parent(item.owner_id.def_id)) }; - visitor.scope = &scope; - visitor.visit_trait_item(item) - } - hir::OwnerNode::ImplItem(item) => { - let scope = - Scope::Root { opt_parent_item: Some(tcx.local_parent(item.owner_id.def_id)) }; - visitor.scope = &scope; - visitor.visit_impl_item(item) - } - hir::OwnerNode::Crate(_) => {} - } - - let mut rl = ResolveLifetimes::default(); - - for (hir_id, v) in named_region_map.defs { - let map = rl.defs.entry(hir_id.owner).or_default(); - map.insert(hir_id.local_id, v); - } - for (hir_id, v) in named_region_map.late_bound_vars { - let map = rl.late_bound_vars.entry(hir_id.owner).or_default(); - map.insert(hir_id.local_id, v); - } - - debug!(?rl.defs); - debug!(?rl.late_bound_vars); - rl -} - -fn late_region_as_bound_region(tcx: TyCtxt<'_>, region: &Region) -> ty::BoundVariableKind { - match region { - Region::LateBound(_, _, def_id) => { - let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local())); - ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name)) - } - _ => bug!("{:?} is not a late region", region), - } -} - -impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { - /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref. - fn poly_trait_ref_binder_info(&mut self) -> (Vec, BinderScopeType) { - let mut scope = self.scope; - let mut supertrait_lifetimes = vec![]; - loop { - match scope { - Scope::Body { .. } | Scope::Root { .. } => { - break (vec![], BinderScopeType::Normal); - } - - Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => { - scope = s; - } - - Scope::Supertrait { s, lifetimes } => { - supertrait_lifetimes = lifetimes.clone(); - scope = s; - } - - Scope::TraitRefBoundary { .. } => { - // We should only see super trait lifetimes if there is a `Binder` above - assert!(supertrait_lifetimes.is_empty()); - break (vec![], BinderScopeType::Normal); - } - - Scope::Binder { hir_id, .. } => { - // Nested poly trait refs have the binders concatenated - let mut full_binders = - self.map.late_bound_vars.entry(*hir_id).or_default().clone(); - full_binders.extend(supertrait_lifetimes.into_iter()); - break (full_binders, BinderScopeType::Concatenating); - } - } - } - } -} -impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { - type NestedFilter = nested_filter::OnlyBodies; - - fn nested_visit_map(&mut self) -> Self::Map { - self.tcx.hir() - } - - fn visit_nested_body(&mut self, body: hir::BodyId) { - let body = self.tcx.hir().body(body); - self.with(Scope::Body { id: body.id(), s: self.scope }, |this| { - this.visit_body(body); - }); - } - - fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { - if let hir::ExprKind::Closure(hir::Closure { - binder, bound_generic_params, fn_decl, .. - }) = e.kind - { - if let &hir::ClosureBinder::For { span: for_sp, .. } = binder { - fn span_of_infer(ty: &hir::Ty<'_>) -> Option { - struct V(Option); - - impl<'v> Visitor<'v> for V { - fn visit_ty(&mut self, t: &'v hir::Ty<'v>) { - match t.kind { - _ if self.0.is_some() => (), - hir::TyKind::Infer => { - self.0 = Some(t.span); - } - _ => intravisit::walk_ty(self, t), - } - } - } - - let mut v = V(None); - v.visit_ty(ty); - v.0 - } - - let infer_in_rt_sp = match fn_decl.output { - hir::FnRetTy::DefaultReturn(sp) => Some(sp), - hir::FnRetTy::Return(ty) => span_of_infer(ty), - }; - - let infer_spans = fn_decl - .inputs - .into_iter() - .filter_map(span_of_infer) - .chain(infer_in_rt_sp) - .collect::>(); - - if !infer_spans.is_empty() { - self.tcx.sess - .struct_span_err( - infer_spans, - "implicit types in closure signatures are forbidden when `for<...>` is present", - ) - .span_label(for_sp, "`for<...>` is here") - .emit(); - } - } - - let (lifetimes, binders): (FxIndexMap, Vec<_>) = - bound_generic_params - .iter() - .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) - .enumerate() - .map(|(late_bound_idx, param)| { - let pair = Region::late(late_bound_idx as u32, param); - let r = late_region_as_bound_region(self.tcx, &pair.1); - (pair, r) - }) - .unzip(); - - self.record_late_bound_vars(e.hir_id, binders); - let scope = Scope::Binder { - hir_id: e.hir_id, - lifetimes, - s: self.scope, - scope_type: BinderScopeType::Normal, - where_bound_origin: None, - }; - - self.with(scope, |this| { - // a closure has no bounds, so everything - // contained within is scoped within its binder. - intravisit::walk_expr(this, e) - }); - } else { - intravisit::walk_expr(self, e) - } - } - - #[instrument(level = "debug", skip(self))] - fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { - match &item.kind { - hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => { - if let Some(of_trait) = of_trait { - self.record_late_bound_vars(of_trait.hir_ref_id, Vec::default()); - } - } - _ => {} - } - match item.kind { - hir::ItemKind::Fn(_, generics, _) => { - self.visit_early_late(item.hir_id(), generics, |this| { - intravisit::walk_item(this, item); - }); - } - - hir::ItemKind::ExternCrate(_) - | hir::ItemKind::Use(..) - | hir::ItemKind::Macro(..) - | hir::ItemKind::Mod(..) - | hir::ItemKind::ForeignMod { .. } - | hir::ItemKind::GlobalAsm(..) => { - // These sorts of items have no lifetime parameters at all. - intravisit::walk_item(self, item); - } - hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => { - // No lifetime parameters, but implied 'static. - self.with(Scope::Elision { s: self.scope }, |this| { - intravisit::walk_item(this, item) - }); - } - hir::ItemKind::OpaqueTy(hir::OpaqueTy { - origin: hir::OpaqueTyOrigin::TyAlias, .. - }) => { - // Opaque types are visited when we visit the - // `TyKind::OpaqueDef`, so that they have the lifetimes from - // their parent opaque_ty in scope. - // - // The core idea here is that since OpaqueTys are generated with the impl Trait as - // their owner, we can keep going until we find the Item that owns that. We then - // conservatively add all resolved lifetimes. Otherwise we run into problems in - // cases like `type Foo<'a> = impl Bar`. - let parent_item = self.tcx.hir().get_parent_item(item.hir_id()); - let resolved_lifetimes: &ResolveLifetimes = self.tcx.resolve_lifetimes(parent_item); - // We need to add *all* deps, since opaque tys may want them from *us* - for (&owner, defs) in resolved_lifetimes.defs.iter() { - defs.iter().for_each(|(&local_id, region)| { - self.map.defs.insert(hir::HirId { owner, local_id }, *region); - }); - } - for (&owner, late_bound_vars) in resolved_lifetimes.late_bound_vars.iter() { - late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| { - self.record_late_bound_vars( - hir::HirId { owner, local_id }, - late_bound_vars.clone(), - ); - }); - } - } - hir::ItemKind::OpaqueTy(hir::OpaqueTy { - origin: hir::OpaqueTyOrigin::FnReturn(_) | hir::OpaqueTyOrigin::AsyncFn(_), - generics, - .. - }) => { - // We want to start our early-bound indices at the end of the parent scope, - // not including any parent `impl Trait`s. - let mut lifetimes = FxIndexMap::default(); - debug!(?generics.params); - for param in generics.params { - match param.kind { - GenericParamKind::Lifetime { .. } => { - let (def_id, reg) = Region::early(¶m); - lifetimes.insert(def_id, reg); - } - GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {} - } - } - - let scope = Scope::Binder { - hir_id: item.hir_id(), - lifetimes, - s: self.scope, - scope_type: BinderScopeType::Normal, - where_bound_origin: None, - }; - self.with(scope, |this| { - let scope = Scope::TraitRefBoundary { s: this.scope }; - this.with(scope, |this| intravisit::walk_item(this, item)) - }); - } - hir::ItemKind::TyAlias(_, generics) - | hir::ItemKind::Enum(_, generics) - | hir::ItemKind::Struct(_, generics) - | hir::ItemKind::Union(_, generics) - | hir::ItemKind::Trait(_, _, generics, ..) - | hir::ItemKind::TraitAlias(generics, ..) - | hir::ItemKind::Impl(&hir::Impl { generics, .. }) => { - // These kinds of items have only early-bound lifetime parameters. - let lifetimes = generics - .params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => Some(Region::early(param)), - GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => None, - }) - .collect(); - self.record_late_bound_vars(item.hir_id(), vec![]); - let scope = Scope::Binder { - hir_id: item.hir_id(), - lifetimes, - scope_type: BinderScopeType::Normal, - s: self.scope, - where_bound_origin: None, - }; - self.with(scope, |this| { - let scope = Scope::TraitRefBoundary { s: this.scope }; - this.with(scope, |this| { - intravisit::walk_item(this, item); - }); - }); - } - } - } - - fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) { - match item.kind { - hir::ForeignItemKind::Fn(_, _, generics) => { - self.visit_early_late(item.hir_id(), generics, |this| { - intravisit::walk_foreign_item(this, item); - }) - } - hir::ForeignItemKind::Static(..) => { - intravisit::walk_foreign_item(self, item); - } - hir::ForeignItemKind::Type => { - intravisit::walk_foreign_item(self, item); - } - } - } - - #[instrument(level = "debug", skip(self))] - fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) { - match ty.kind { - hir::TyKind::BareFn(c) => { - let (lifetimes, binders): (FxIndexMap, Vec<_>) = c - .generic_params - .iter() - .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) - .enumerate() - .map(|(late_bound_idx, param)| { - let pair = Region::late(late_bound_idx as u32, param); - let r = late_region_as_bound_region(self.tcx, &pair.1); - (pair, r) - }) - .unzip(); - self.record_late_bound_vars(ty.hir_id, binders); - let scope = Scope::Binder { - hir_id: ty.hir_id, - lifetimes, - s: self.scope, - scope_type: BinderScopeType::Normal, - where_bound_origin: None, - }; - self.with(scope, |this| { - // a bare fn has no bounds, so everything - // contained within is scoped within its binder. - intravisit::walk_ty(this, ty); - }); - } - hir::TyKind::TraitObject(bounds, lifetime, _) => { - debug!(?bounds, ?lifetime, "TraitObject"); - let scope = Scope::TraitRefBoundary { s: self.scope }; - self.with(scope, |this| { - for bound in bounds { - this.visit_poly_trait_ref(bound); - } - }); - match lifetime.res { - LifetimeName::ImplicitObjectLifetimeDefault => { - // If the user does not write *anything*, we - // use the object lifetime defaulting - // rules. So e.g., `Box` becomes - // `Box`. - self.resolve_object_lifetime_default(lifetime) - } - LifetimeName::Infer => { - // If the user writes `'_`, we use the *ordinary* elision - // rules. So the `'_` in e.g., `Box` will be - // resolved the same as the `'_` in `&'_ Foo`. - // - // cc #48468 - } - LifetimeName::Param(..) | LifetimeName::Static => { - // If the user wrote an explicit name, use that. - self.visit_lifetime(lifetime); - } - LifetimeName::Error => {} - } - } - hir::TyKind::Ref(lifetime_ref, ref mt) => { - self.visit_lifetime(lifetime_ref); - let scope = Scope::ObjectLifetimeDefault { - lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(), - s: self.scope, - }; - self.with(scope, |this| this.visit_ty(&mt.ty)); - } - hir::TyKind::OpaqueDef(item_id, lifetimes, _in_trait) => { - // Resolve the lifetimes in the bounds to the lifetime defs in the generics. - // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to - // `type MyAnonTy<'b> = impl MyTrait<'b>;` - // ^ ^ this gets resolved in the scope of - // the opaque_ty generics - let opaque_ty = self.tcx.hir().item(item_id); - match &opaque_ty.kind { - hir::ItemKind::OpaqueTy(hir::OpaqueTy { - origin: hir::OpaqueTyOrigin::TyAlias, - .. - }) => { - intravisit::walk_ty(self, ty); - - // Elided lifetimes are not allowed in non-return - // position impl Trait - let scope = Scope::TraitRefBoundary { s: self.scope }; - self.with(scope, |this| { - let scope = Scope::Elision { s: this.scope }; - this.with(scope, |this| { - intravisit::walk_item(this, opaque_ty); - }) - }); - - return; - } - hir::ItemKind::OpaqueTy(hir::OpaqueTy { - origin: hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..), - .. - }) => {} - i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i), - }; - - // Resolve the lifetimes that are applied to the opaque type. - // These are resolved in the current scope. - // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to - // `fn foo<'a>() -> MyAnonTy<'a> { ... }` - // ^ ^this gets resolved in the current scope - for lifetime in lifetimes { - let hir::GenericArg::Lifetime(lifetime) = lifetime else { - continue - }; - self.visit_lifetime(lifetime); - - // Check for predicates like `impl for<'a> Trait>` - // and ban them. Type variables instantiated inside binders aren't - // well-supported at the moment, so this doesn't work. - // In the future, this should be fixed and this error should be removed. - let def = self.map.defs.get(&lifetime.hir_id).cloned(); - let Some(Region::LateBound(_, _, def_id)) = def else { - continue - }; - let Some(def_id) = def_id.as_local() else { - continue - }; - let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); - // Ensure that the parent of the def is an item, not HRTB - let parent_id = self.tcx.hir().parent_id(hir_id); - if !parent_id.is_owner() { - struct_span_err!( - self.tcx.sess, - lifetime.ident.span, - E0657, - "`impl Trait` can only capture lifetimes bound at the fn or impl level" - ) - .emit(); - self.uninsert_lifetime_on_error(lifetime, def.unwrap()); - } - if let hir::Node::Item(hir::Item { - kind: hir::ItemKind::OpaqueTy { .. }, .. - }) = self.tcx.hir().get(parent_id) - { - let mut err = self.tcx.sess.struct_span_err( - lifetime.ident.span, - "higher kinded lifetime bounds on nested opaque types are not supported yet", - ); - err.span_note(self.tcx.def_span(def_id), "lifetime declared here"); - err.emit(); - self.uninsert_lifetime_on_error(lifetime, def.unwrap()); - } - } - } - _ => intravisit::walk_ty(self, ty), - } - } - - #[instrument(level = "debug", skip(self))] - fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { - use self::hir::TraitItemKind::*; - match trait_item.kind { - Fn(_, _) => { - self.visit_early_late(trait_item.hir_id(), &trait_item.generics, |this| { - intravisit::walk_trait_item(this, trait_item) - }); - } - Type(bounds, ty) => { - let generics = &trait_item.generics; - let lifetimes = generics - .params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => Some(Region::early(param)), - GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => None, - }) - .collect(); - self.record_late_bound_vars(trait_item.hir_id(), vec![]); - let scope = Scope::Binder { - hir_id: trait_item.hir_id(), - lifetimes, - s: self.scope, - scope_type: BinderScopeType::Normal, - where_bound_origin: None, - }; - self.with(scope, |this| { - let scope = Scope::TraitRefBoundary { s: this.scope }; - this.with(scope, |this| { - this.visit_generics(generics); - for bound in bounds { - this.visit_param_bound(bound); - } - if let Some(ty) = ty { - this.visit_ty(ty); - } - }) - }); - } - Const(_, _) => { - // Only methods and types support generics. - assert!(trait_item.generics.params.is_empty()); - intravisit::walk_trait_item(self, trait_item); - } - } - } - - #[instrument(level = "debug", skip(self))] - fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { - use self::hir::ImplItemKind::*; - match impl_item.kind { - Fn(..) => self.visit_early_late(impl_item.hir_id(), &impl_item.generics, |this| { - intravisit::walk_impl_item(this, impl_item) - }), - Type(ty) => { - let generics = &impl_item.generics; - let lifetimes: FxIndexMap = generics - .params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => Some(Region::early(param)), - GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => None, - }) - .collect(); - self.record_late_bound_vars(impl_item.hir_id(), vec![]); - let scope = Scope::Binder { - hir_id: impl_item.hir_id(), - lifetimes, - s: self.scope, - scope_type: BinderScopeType::Normal, - where_bound_origin: None, - }; - self.with(scope, |this| { - let scope = Scope::TraitRefBoundary { s: this.scope }; - this.with(scope, |this| { - this.visit_generics(generics); - this.visit_ty(ty); - }) - }); - } - Const(_, _) => { - // Only methods and types support generics. - assert!(impl_item.generics.params.is_empty()); - intravisit::walk_impl_item(self, impl_item); - } - } - } - - #[instrument(level = "debug", skip(self))] - fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) { - match lifetime_ref.res { - hir::LifetimeName::Static => self.insert_lifetime(lifetime_ref, Region::Static), - hir::LifetimeName::Param(param_def_id) => { - self.resolve_lifetime_ref(param_def_id, lifetime_ref) - } - // If we've already reported an error, just ignore `lifetime_ref`. - hir::LifetimeName::Error => {} - // Those will be resolved by typechecking. - hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Infer => {} - } - } - - fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) { - for (i, segment) in path.segments.iter().enumerate() { - let depth = path.segments.len() - i - 1; - if let Some(args) = segment.args { - self.visit_segment_args(path.res, depth, args); - } - } - } - - fn visit_fn( - &mut self, - fk: intravisit::FnKind<'tcx>, - fd: &'tcx hir::FnDecl<'tcx>, - body_id: hir::BodyId, - _: Span, - _: LocalDefId, - ) { - let output = match fd.output { - hir::FnRetTy::DefaultReturn(_) => None, - hir::FnRetTy::Return(ty) => Some(ty), - }; - self.visit_fn_like_elision(&fd.inputs, output, matches!(fk, intravisit::FnKind::Closure)); - intravisit::walk_fn_kind(self, fk); - self.visit_nested_body(body_id) - } - - fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { - let scope = Scope::TraitRefBoundary { s: self.scope }; - self.with(scope, |this| { - for param in generics.params { - match param.kind { - GenericParamKind::Lifetime { .. } => {} - GenericParamKind::Type { default, .. } => { - if let Some(ty) = default { - this.visit_ty(ty); - } - } - GenericParamKind::Const { ty, default } => { - this.visit_ty(ty); - if let Some(default) = default { - this.visit_body(this.tcx.hir().body(default.body)); - } - } - } - } - for predicate in generics.predicates { - match predicate { - &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate { - hir_id, - bounded_ty, - bounds, - bound_generic_params, - origin, - .. - }) => { - let lifetimes: FxIndexMap = - bound_generic_params - .iter() - .filter(|param| { - matches!(param.kind, GenericParamKind::Lifetime { .. }) - }) - .enumerate() - .map(|(late_bound_idx, param)| { - Region::late(late_bound_idx as u32, param) - }) - .collect(); - let binders: Vec<_> = - lifetimes - .iter() - .map(|(_, region)| { - late_region_as_bound_region(this.tcx, region) - }) - .collect(); - this.record_late_bound_vars(hir_id, binders.clone()); - // Even if there are no lifetimes defined here, we still wrap it in a binder - // scope. If there happens to be a nested poly trait ref (an error), that - // will be `Concatenating` anyways, so we don't have to worry about the depth - // being wrong. - let scope = Scope::Binder { - hir_id, - lifetimes, - s: this.scope, - scope_type: BinderScopeType::Normal, - where_bound_origin: Some(origin), - }; - this.with(scope, |this| { - this.visit_ty(&bounded_ty); - walk_list!(this, visit_param_bound, bounds); - }) - } - &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate { - lifetime, - bounds, - .. - }) => { - this.visit_lifetime(lifetime); - walk_list!(this, visit_param_bound, bounds); - - if lifetime.res != hir::LifetimeName::Static { - for bound in bounds { - let hir::GenericBound::Outlives(lt) = bound else { - continue; - }; - if lt.res != hir::LifetimeName::Static { - continue; - } - this.insert_lifetime(lt, Region::Static); - this.tcx - .sess - .struct_span_warn( - lifetime.ident.span, - &format!( - "unnecessary lifetime parameter `{}`", - lifetime.ident, - ), - ) - .help(&format!( - "you can use the `'static` lifetime directly, in place of `{}`", - lifetime.ident, - )) - .emit(); - } - } - } - &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate { - lhs_ty, - rhs_ty, - .. - }) => { - this.visit_ty(lhs_ty); - this.visit_ty(rhs_ty); - } - } - } - }) - } - - fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) { - match bound { - hir::GenericBound::LangItemTrait(_, _, hir_id, _) => { - // FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go - // through the regular poly trait ref code, so we don't get another - // chance to introduce a binder. For now, I'm keeping the existing logic - // of "if there isn't a Binder scope above us, add one", but I - // imagine there's a better way to go about this. - let (binders, scope_type) = self.poly_trait_ref_binder_info(); - - self.record_late_bound_vars(*hir_id, binders); - let scope = Scope::Binder { - hir_id: *hir_id, - lifetimes: FxIndexMap::default(), - s: self.scope, - scope_type, - where_bound_origin: None, - }; - self.with(scope, |this| { - intravisit::walk_param_bound(this, bound); - }); - } - _ => intravisit::walk_param_bound(self, bound), - } - } - - fn visit_poly_trait_ref(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) { - debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref); - - let (mut binders, scope_type) = self.poly_trait_ref_binder_info(); - - let initial_bound_vars = binders.len() as u32; - let mut lifetimes: FxIndexMap = FxIndexMap::default(); - let binders_iter = trait_ref - .bound_generic_params - .iter() - .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) - .enumerate() - .map(|(late_bound_idx, param)| { - let pair = Region::late(initial_bound_vars + late_bound_idx as u32, param); - let r = late_region_as_bound_region(self.tcx, &pair.1); - lifetimes.insert(pair.0, pair.1); - r - }); - binders.extend(binders_iter); - - debug!(?binders); - self.record_late_bound_vars(trait_ref.trait_ref.hir_ref_id, binders); - - // Always introduce a scope here, even if this is in a where clause and - // we introduced the binders around the bounded Ty. In that case, we - // just reuse the concatenation functionality also present in nested trait - // refs. - let scope = Scope::Binder { - hir_id: trait_ref.trait_ref.hir_ref_id, - lifetimes, - s: self.scope, - scope_type, - where_bound_origin: None, - }; - self.with(scope, |this| { - walk_list!(this, visit_generic_param, trait_ref.bound_generic_params); - this.visit_trait_ref(&trait_ref.trait_ref); - }); - } -} - -fn object_lifetime_default(tcx: TyCtxt<'_>, param_def_id: DefId) -> ObjectLifetimeDefault { - debug_assert_eq!(tcx.def_kind(param_def_id), DefKind::TyParam); - let param_def_id = param_def_id.expect_local(); - let parent_def_id = tcx.local_parent(param_def_id); - let generics = tcx.hir().get_generics(parent_def_id).unwrap(); - let param_hir_id = tcx.local_def_id_to_hir_id(param_def_id); - let param = generics.params.iter().find(|p| p.hir_id == param_hir_id).unwrap(); - - // Scan the bounds and where-clauses on parameters to extract bounds - // of the form `T:'a` so as to determine the `ObjectLifetimeDefault` - // for each type parameter. - match param.kind { - GenericParamKind::Type { .. } => { - let mut set = Set1::Empty; - - // Look for `type: ...` where clauses. - for bound in generics.bounds_for_param(param_def_id) { - // Ignore `for<'a> type: ...` as they can change what - // lifetimes mean (although we could "just" handle it). - if !bound.bound_generic_params.is_empty() { - continue; - } - - for bound in bound.bounds { - if let hir::GenericBound::Outlives(lifetime) = bound { - set.insert(lifetime.res); - } - } - } - - match set { - Set1::Empty => ObjectLifetimeDefault::Empty, - Set1::One(hir::LifetimeName::Static) => ObjectLifetimeDefault::Static, - Set1::One(hir::LifetimeName::Param(param_def_id)) => { - ObjectLifetimeDefault::Param(param_def_id.to_def_id()) - } - _ => ObjectLifetimeDefault::Ambiguous, - } - } - _ => { - bug!("object_lifetime_default_raw must only be called on a type parameter") - } - } -} - -impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { - fn with(&mut self, wrap_scope: Scope<'_>, f: F) - where - F: for<'b> FnOnce(&mut LifetimeContext<'b, 'tcx>), - { - let LifetimeContext { tcx, map, .. } = self; - let mut this = LifetimeContext { tcx: *tcx, map, scope: &wrap_scope }; - let span = debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope)); - { - let _enter = span.enter(); - f(&mut this); - } - } - - fn record_late_bound_vars(&mut self, hir_id: hir::HirId, binder: Vec) { - if let Some(old) = self.map.late_bound_vars.insert(hir_id, binder) { - bug!( - "overwrote bound vars for {hir_id:?}:\nold={old:?}\nnew={:?}", - self.map.late_bound_vars[&hir_id] - ) - } - } - - /// Visits self by adding a scope and handling recursive walk over the contents with `walk`. - /// - /// Handles visiting fns and methods. These are a bit complicated because we must distinguish - /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear - /// within type bounds; those are early bound lifetimes, and the rest are late bound. - /// - /// For example: - /// - /// fn foo<'a,'b,'c,T:Trait<'b>>(...) - /// - /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound - /// lifetimes may be interspersed together. - /// - /// If early bound lifetimes are present, we separate them into their own list (and likewise - /// for late bound). They will be numbered sequentially, starting from the lowest index that is - /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late - /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the - /// ordering is not important there. - fn visit_early_late( - &mut self, - hir_id: hir::HirId, - generics: &'tcx hir::Generics<'tcx>, - walk: F, - ) where - F: for<'b, 'c> FnOnce(&'b mut LifetimeContext<'c, 'tcx>), - { - let mut named_late_bound_vars = 0; - let lifetimes: FxIndexMap = generics - .params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => { - if self.tcx.is_late_bound(param.hir_id) { - let late_bound_idx = named_late_bound_vars; - named_late_bound_vars += 1; - Some(Region::late(late_bound_idx, param)) - } else { - Some(Region::early(param)) - } - } - GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => None, - }) - .collect(); - - let binders: Vec<_> = generics - .params - .iter() - .filter(|param| { - matches!(param.kind, GenericParamKind::Lifetime { .. }) - && self.tcx.is_late_bound(param.hir_id) - }) - .enumerate() - .map(|(late_bound_idx, param)| { - let pair = Region::late(late_bound_idx as u32, param); - late_region_as_bound_region(self.tcx, &pair.1) - }) - .collect(); - self.record_late_bound_vars(hir_id, binders); - let scope = Scope::Binder { - hir_id, - lifetimes, - s: self.scope, - scope_type: BinderScopeType::Normal, - where_bound_origin: None, - }; - self.with(scope, walk); - } - - #[instrument(level = "debug", skip(self))] - fn resolve_lifetime_ref( - &mut self, - region_def_id: LocalDefId, - lifetime_ref: &'tcx hir::Lifetime, - ) { - // Walk up the scope chain, tracking the number of fn scopes - // that we pass through, until we find a lifetime with the - // given name or we run out of scopes. - // search. - let mut late_depth = 0; - let mut scope = self.scope; - let mut outermost_body = None; - let result = loop { - match *scope { - Scope::Body { id, s } => { - outermost_body = Some(id); - scope = s; - } - - Scope::Root { opt_parent_item } => { - if let Some(parent_item) = opt_parent_item - && let parent_generics = self.tcx.generics_of(parent_item) - && parent_generics.param_def_id_to_index.contains_key(®ion_def_id.to_def_id()) - { - break Some(Region::EarlyBound(region_def_id.to_def_id())); - } - break None; - } - - Scope::Binder { ref lifetimes, scope_type, s, where_bound_origin, .. } => { - if let Some(&def) = lifetimes.get(®ion_def_id) { - break Some(def.shifted(late_depth)); - } - match scope_type { - BinderScopeType::Normal => late_depth += 1, - BinderScopeType::Concatenating => {} - } - // Fresh lifetimes in APIT used to be allowed in async fns and forbidden in - // regular fns. - if let Some(hir::PredicateOrigin::ImplTrait) = where_bound_origin - && let hir::LifetimeName::Param(param_id) = lifetime_ref.res - && let Some(generics) = self.tcx.hir().get_generics(self.tcx.local_parent(param_id)) - && let Some(param) = generics.params.iter().find(|p| p.def_id == param_id) - && param.is_elided_lifetime() - && let hir::IsAsync::NotAsync = self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id) - && !self.tcx.features().anonymous_lifetime_in_impl_trait - { - let mut diag = rustc_session::parse::feature_err( - &self.tcx.sess.parse_sess, - sym::anonymous_lifetime_in_impl_trait, - lifetime_ref.ident.span, - "anonymous lifetimes in `impl Trait` are unstable", - ); - - if let Some(generics) = - self.tcx.hir().get_generics(lifetime_ref.hir_id.owner.def_id) - { - let new_param_sugg = if let Some(span) = - generics.span_for_lifetime_suggestion() - { - (span, "'a, ".to_owned()) - } else { - (generics.span, "<'a>".to_owned()) - }; - - let lifetime_sugg = match lifetime_ref.suggestion_position() { - (hir::LifetimeSuggestionPosition::Normal, span) => (span, "'a".to_owned()), - (hir::LifetimeSuggestionPosition::Ampersand, span) => (span, "'a ".to_owned()), - (hir::LifetimeSuggestionPosition::ElidedPath, span) => (span, "<'a>".to_owned()), - (hir::LifetimeSuggestionPosition::ElidedPathArgument, span) => (span, "'a, ".to_owned()), - (hir::LifetimeSuggestionPosition::ObjectDefault, span) => (span, "+ 'a".to_owned()), - }; - let suggestions = vec![ - lifetime_sugg, - new_param_sugg, - ]; - - diag.span_label( - lifetime_ref.ident.span, - "expected named lifetime parameter", - ); - diag.multipart_suggestion( - "consider introducing a named lifetime parameter", - suggestions, - rustc_errors::Applicability::MaybeIncorrect, - ); - } - - diag.emit(); - return; - } - scope = s; - } - - Scope::Elision { s, .. } - | Scope::ObjectLifetimeDefault { s, .. } - | Scope::Supertrait { s, .. } - | Scope::TraitRefBoundary { s, .. } => { - scope = s; - } - } - }; - - if let Some(mut def) = result { - if let Region::EarlyBound(..) = def { - // Do not free early-bound regions, only late-bound ones. - } else if let Some(body_id) = outermost_body { - let fn_id = self.tcx.hir().body_owner(body_id); - match self.tcx.hir().get(fn_id) { - Node::Item(hir::Item { owner_id, kind: hir::ItemKind::Fn(..), .. }) - | Node::TraitItem(hir::TraitItem { - owner_id, - kind: hir::TraitItemKind::Fn(..), - .. - }) - | Node::ImplItem(hir::ImplItem { - owner_id, - kind: hir::ImplItemKind::Fn(..), - .. - }) => { - def = Region::Free(owner_id.to_def_id(), def.id().unwrap()); - } - Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) => { - def = Region::Free(closure.def_id.to_def_id(), def.id().unwrap()); - } - _ => {} - } - } - - self.insert_lifetime(lifetime_ref, def); - return; - } - - // We may fail to resolve higher-ranked lifetimes that are mentioned by APIT. - // AST-based resolution does not care for impl-trait desugaring, which are the - // responibility of lowering. This may create a mismatch between the resolution - // AST found (`region_def_id`) which points to HRTB, and what HIR allows. - // ``` - // fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {} - // ``` - // - // In such case, walk back the binders to diagnose it properly. - let mut scope = self.scope; - loop { - match *scope { - Scope::Binder { - where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), .. - } => { - let mut err = self.tcx.sess.struct_span_err( - lifetime_ref.ident.span, - "`impl Trait` can only mention lifetimes bound at the fn or impl level", - ); - err.span_note(self.tcx.def_span(region_def_id), "lifetime declared here"); - err.emit(); - return; - } - Scope::Root { .. } => break, - Scope::Binder { s, .. } - | Scope::Body { s, .. } - | Scope::Elision { s, .. } - | Scope::ObjectLifetimeDefault { s, .. } - | Scope::Supertrait { s, .. } - | Scope::TraitRefBoundary { s, .. } => { - scope = s; - } - } - } - - self.tcx.sess.delay_span_bug( - lifetime_ref.ident.span, - &format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,), - ); - } - - #[instrument(level = "debug", skip(self))] - fn visit_segment_args( - &mut self, - res: Res, - depth: usize, - generic_args: &'tcx hir::GenericArgs<'tcx>, - ) { - if generic_args.parenthesized { - self.visit_fn_like_elision( - generic_args.inputs(), - Some(generic_args.bindings[0].ty()), - false, - ); - return; - } - - for arg in generic_args.args { - if let hir::GenericArg::Lifetime(lt) = arg { - self.visit_lifetime(lt); - } - } - - // Figure out if this is a type/trait segment, - // which requires object lifetime defaults. - let type_def_id = match res { - Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(self.tcx.parent(def_id)), - Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(self.tcx.parent(def_id)), - Res::Def( - DefKind::Struct - | DefKind::Union - | DefKind::Enum - | DefKind::TyAlias - | DefKind::Trait, - def_id, - ) if depth == 0 => Some(def_id), - _ => None, - }; - - debug!(?type_def_id); - - // Compute a vector of defaults, one for each type parameter, - // per the rules given in RFCs 599 and 1156. Example: - // - // ```rust - // struct Foo<'a, T: 'a, U> { } - // ``` - // - // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default - // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound) - // and `dyn Baz` to `dyn Baz + 'static` (because there is no - // such bound). - // - // Therefore, we would compute `object_lifetime_defaults` to a - // vector like `['x, 'static]`. Note that the vector only - // includes type parameters. - let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| { - let in_body = { - let mut scope = self.scope; - loop { - match *scope { - Scope::Root { .. } => break false, - - Scope::Body { .. } => break true, - - Scope::Binder { s, .. } - | Scope::Elision { s, .. } - | Scope::ObjectLifetimeDefault { s, .. } - | Scope::Supertrait { s, .. } - | Scope::TraitRefBoundary { s, .. } => { - scope = s; - } - } - } - }; - - let map = &self.map; - let generics = self.tcx.generics_of(def_id); - - // `type_def_id` points to an item, so there is nothing to inherit generics from. - debug_assert_eq!(generics.parent_count, 0); - - let set_to_region = |set: ObjectLifetimeDefault| match set { - ObjectLifetimeDefault::Empty => { - if in_body { - None - } else { - Some(Region::Static) - } - } - ObjectLifetimeDefault::Static => Some(Region::Static), - ObjectLifetimeDefault::Param(param_def_id) => { - // This index can be used with `generic_args` since `parent_count == 0`. - let index = generics.param_def_id_to_index[¶m_def_id] as usize; - generic_args.args.get(index).and_then(|arg| match arg { - GenericArg::Lifetime(lt) => map.defs.get(<.hir_id).copied(), - _ => None, - }) - } - ObjectLifetimeDefault::Ambiguous => None, - }; - generics - .params - .iter() - .filter_map(|param| { - match self.tcx.def_kind(param.def_id) { - // Generic consts don't impose any constraints. - // - // We still store a dummy value here to allow generic parameters - // in an arbitrary order. - DefKind::ConstParam => Some(ObjectLifetimeDefault::Empty), - DefKind::TyParam => Some(self.tcx.object_lifetime_default(param.def_id)), - // We may also get a `Trait` or `TraitAlias` because of how generics `Self` parameter - // works. Ignore it because it can't have a meaningful lifetime default. - DefKind::LifetimeParam | DefKind::Trait | DefKind::TraitAlias => None, - dk => bug!("unexpected def_kind {:?}", dk), - } - }) - .map(set_to_region) - .collect() - }); - - debug!(?object_lifetime_defaults); - - let mut i = 0; - for arg in generic_args.args { - match arg { - GenericArg::Lifetime(_) => {} - GenericArg::Type(ty) => { - if let Some(<) = object_lifetime_defaults.get(i) { - let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope }; - self.with(scope, |this| this.visit_ty(ty)); - } else { - self.visit_ty(ty); - } - i += 1; - } - GenericArg::Const(ct) => { - self.visit_anon_const(&ct.value); - i += 1; - } - GenericArg::Infer(inf) => { - self.visit_id(inf.hir_id); - i += 1; - } - } - } - - // Hack: when resolving the type `XX` in binding like `dyn - // Foo<'b, Item = XX>`, the current object-lifetime default - // would be to examine the trait `Foo` to check whether it has - // a lifetime bound declared on `Item`. e.g., if `Foo` is - // declared like so, then the default object lifetime bound in - // `XX` should be `'b`: - // - // ```rust - // trait Foo<'a> { - // type Item: 'a; - // } - // ``` - // - // but if we just have `type Item;`, then it would be - // `'static`. However, we don't get all of this logic correct. - // - // Instead, we do something hacky: if there are no lifetime parameters - // to the trait, then we simply use a default object lifetime - // bound of `'static`, because there is no other possibility. On the other hand, - // if there ARE lifetime parameters, then we require the user to give an - // explicit bound for now. - // - // This is intended to leave room for us to implement the - // correct behavior in the future. - let has_lifetime_parameter = - generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))); - - // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or - // in the trait ref `YY<...>` in `Item: YY<...>`. - for binding in generic_args.bindings { - let scope = Scope::ObjectLifetimeDefault { - lifetime: if has_lifetime_parameter { None } else { Some(Region::Static) }, - s: self.scope, - }; - if let Some(type_def_id) = type_def_id { - let lifetimes = LifetimeContext::supertrait_hrtb_lifetimes( - self.tcx, - type_def_id, - binding.ident, - ); - self.with(scope, |this| { - let scope = Scope::Supertrait { - lifetimes: lifetimes.unwrap_or_default(), - s: this.scope, - }; - this.with(scope, |this| this.visit_assoc_type_binding(binding)); - }); - } else { - self.with(scope, |this| this.visit_assoc_type_binding(binding)); - } - } - } - - /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the - /// associated type name and starting trait. - /// For example, imagine we have - /// ```ignore (illustrative) - /// trait Foo<'a, 'b> { - /// type As; - /// } - /// trait Bar<'b>: for<'a> Foo<'a, 'b> {} - /// trait Bar: for<'b> Bar<'b> {} - /// ``` - /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on - /// the starting trait `Bar`, we would return `Some(['b, 'a])`. - fn supertrait_hrtb_lifetimes( - tcx: TyCtxt<'tcx>, - def_id: DefId, - assoc_name: Ident, - ) -> Option> { - let trait_defines_associated_type_named = |trait_def_id: DefId| { - tcx.associated_items(trait_def_id) - .find_by_name_and_kind(tcx, assoc_name, ty::AssocKind::Type, trait_def_id) - .is_some() - }; - - use smallvec::{smallvec, SmallVec}; - let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> = - smallvec![(def_id, smallvec![])]; - let mut visited: FxHashSet = FxHashSet::default(); - loop { - let Some((def_id, bound_vars)) = stack.pop() else { - break None; - }; - // See issue #83753. If someone writes an associated type on a non-trait, just treat it as - // there being no supertrait HRTBs. - match tcx.def_kind(def_id) { - DefKind::Trait | DefKind::TraitAlias | DefKind::Impl { .. } => {} - _ => break None, - } - - if trait_defines_associated_type_named(def_id) { - break Some(bound_vars.into_iter().collect()); - } - let predicates = - tcx.super_predicates_that_define_assoc_type((def_id, Some(assoc_name))); - let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| { - let bound_predicate = pred.kind(); - match bound_predicate.skip_binder() { - ty::PredicateKind::Clause(ty::Clause::Trait(data)) => { - // The order here needs to match what we would get from `subst_supertrait` - let pred_bound_vars = bound_predicate.bound_vars(); - let mut all_bound_vars = bound_vars.clone(); - all_bound_vars.extend(pred_bound_vars.iter()); - let super_def_id = data.trait_ref.def_id; - Some((super_def_id, all_bound_vars)) - } - _ => None, - } - }); - - let obligations = obligations.filter(|o| visited.insert(o.0)); - stack.extend(obligations); - } - } - - #[instrument(level = "debug", skip(self))] - fn visit_fn_like_elision( - &mut self, - inputs: &'tcx [hir::Ty<'tcx>], - output: Option<&'tcx hir::Ty<'tcx>>, - in_closure: bool, - ) { - self.with(Scope::Elision { s: self.scope }, |this| { - for input in inputs { - this.visit_ty(input); - } - if !in_closure && let Some(output) = output { - this.visit_ty(output); - } - }); - if in_closure && let Some(output) = output { - self.visit_ty(output); - } - } - - fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) { - debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref); - let mut late_depth = 0; - let mut scope = self.scope; - let lifetime = loop { - match *scope { - Scope::Binder { s, scope_type, .. } => { - match scope_type { - BinderScopeType::Normal => late_depth += 1, - BinderScopeType::Concatenating => {} - } - scope = s; - } - - Scope::Root { .. } | Scope::Elision { .. } => break Region::Static, - - Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return, - - Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l, - - Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => { - scope = s; - } - } - }; - self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth)); - } - - #[instrument(level = "debug", skip(self))] - fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: Region) { - debug!(span = ?lifetime_ref.ident.span); - self.map.defs.insert(lifetime_ref.hir_id, def); - } - - /// Sometimes we resolve a lifetime, but later find that it is an - /// error (esp. around impl trait). In that case, we remove the - /// entry into `map.defs` so as not to confuse later code. - fn uninsert_lifetime_on_error(&mut self, lifetime_ref: &'tcx hir::Lifetime, bad_def: Region) { - let old_value = self.map.defs.remove(&lifetime_ref.hir_id); - assert_eq!(old_value, Some(bad_def)); - } -} - -/// Detects late-bound lifetimes and inserts them into -/// `late_bound`. -/// -/// A region declared on a fn is **late-bound** if: -/// - it is constrained by an argument type; -/// - it does not appear in a where-clause. -/// -/// "Constrained" basically means that it appears in any type but -/// not amongst the inputs to a projection. In other words, `<&'a -/// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`. -fn is_late_bound_map( - tcx: TyCtxt<'_>, - owner_id: hir::OwnerId, -) -> Option<&FxIndexSet> { - let decl = tcx.hir().fn_decl_by_hir_id(owner_id.into())?; - let generics = tcx.hir().get_generics(owner_id.def_id)?; - - let mut late_bound = FxIndexSet::default(); - - let mut constrained_by_input = ConstrainedCollector { regions: Default::default(), tcx }; - for arg_ty in decl.inputs { - constrained_by_input.visit_ty(arg_ty); - } - - let mut appears_in_output = AllCollector::default(); - intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output); - - debug!(?constrained_by_input.regions); - - // Walk the lifetimes that appear in where clauses. - // - // Subtle point: because we disallow nested bindings, we can just - // ignore binders here and scrape up all names we see. - let mut appears_in_where_clause = AllCollector::default(); - appears_in_where_clause.visit_generics(generics); - debug!(?appears_in_where_clause.regions); - - // Late bound regions are those that: - // - appear in the inputs - // - do not appear in the where-clauses - // - are not implicitly captured by `impl Trait` - for param in generics.params { - match param.kind { - hir::GenericParamKind::Lifetime { .. } => { /* fall through */ } - - // Neither types nor consts are late-bound. - hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue, - } - - // appears in the where clauses? early-bound. - if appears_in_where_clause.regions.contains(¶m.def_id) { - continue; - } - - // does not appear in the inputs, but appears in the return type? early-bound. - if !constrained_by_input.regions.contains(¶m.def_id) - && appears_in_output.regions.contains(¶m.def_id) - { - continue; - } - - debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.def_id); - - let inserted = late_bound.insert(param.hir_id.local_id); - assert!(inserted, "visited lifetime {:?} twice", param.def_id); - } - - debug!(?late_bound); - return Some(tcx.arena.alloc(late_bound)); - - /// Visits a `ty::Ty` collecting information about what generic parameters are constrained. - /// - /// The visitor does not operate on `hir::Ty` so that it can be called on the rhs of a `type Alias<...> = ...;` - /// which may live in a separate crate so there would not be any hir available. Instead we use the `type_of` - /// query to obtain a `ty::Ty` which will be present even in cross crate scenarios. It also naturally - /// handles cycle detection as we go through the query system. - /// - /// This is necessary in the first place for the following case: - /// ``` - /// type Alias<'a, T> = >::Assoc; - /// fn foo<'a>(_: Alias<'a, ()>) -> Alias<'a, ()> { ... } - /// ``` - /// - /// If we conservatively considered `'a` unconstrained then we could break users who had written code before - /// we started correctly handling aliases. If we considered `'a` constrained then it would become late bound - /// causing an error during astconv as the `'a` is not constrained by the input type `<() as Trait<'a>>::Assoc` - /// but appears in the output type `<() as Trait<'a>>::Assoc`. - /// - /// We must therefore "look into" the `Alias` to see whether we should consider `'a` constrained or not. - /// - /// See #100508 #85533 #47511 for additional context - struct ConstrainedCollectorPostAstConv { - arg_is_constrained: Box<[bool]>, - } - - use std::ops::ControlFlow; - use ty::Ty; - impl<'tcx> TypeVisitor> for ConstrainedCollectorPostAstConv { - fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow { - match t.kind() { - ty::Param(param_ty) => { - self.arg_is_constrained[param_ty.index as usize] = true; - } - ty::Alias(ty::Projection, _) => return ControlFlow::Continue(()), - _ => (), - } - t.super_visit_with(self) - } - - fn visit_const(&mut self, _: ty::Const<'tcx>) -> ControlFlow { - ControlFlow::Continue(()) - } - - fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow { - debug!("r={:?}", r.kind()); - if let ty::RegionKind::ReEarlyBound(region) = r.kind() { - self.arg_is_constrained[region.index as usize] = true; - } - - ControlFlow::Continue(()) - } - } - - struct ConstrainedCollector<'tcx> { - tcx: TyCtxt<'tcx>, - regions: FxHashSet, - } - - impl<'v> Visitor<'v> for ConstrainedCollector<'_> { - fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) { - match ty.kind { - hir::TyKind::Path( - hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..), - ) => { - // ignore lifetimes appearing in associated type - // projections, as they are not *constrained* - // (defined above) - } - - hir::TyKind::Path(hir::QPath::Resolved( - None, - hir::Path { res: Res::Def(DefKind::TyAlias, alias_def), segments, span }, - )) => { - // See comments on `ConstrainedCollectorPostAstConv` for why this arm does not just consider - // substs to be unconstrained. - let generics = self.tcx.generics_of(alias_def); - let mut walker = ConstrainedCollectorPostAstConv { - arg_is_constrained: vec![false; generics.params.len()].into_boxed_slice(), - }; - walker.visit_ty(self.tcx.type_of(alias_def)); - - match segments.last() { - Some(hir::PathSegment { args: Some(args), .. }) => { - let tcx = self.tcx; - for constrained_arg in - args.args.iter().enumerate().flat_map(|(n, arg)| { - match walker.arg_is_constrained.get(n) { - Some(true) => Some(arg), - Some(false) => None, - None => { - tcx.sess.delay_span_bug( - *span, - format!( - "Incorrect generic arg count for alias {:?}", - alias_def - ), - ); - None - } - } - }) - { - self.visit_generic_arg(constrained_arg); - } - } - Some(_) => (), - None => bug!("Path with no segments or self type"), - } - } - - hir::TyKind::Path(hir::QPath::Resolved(None, path)) => { - // consider only the lifetimes on the final - // segment; I am not sure it's even currently - // valid to have them elsewhere, but even if it - // is, those would be potentially inputs to - // projections - if let Some(last_segment) = path.segments.last() { - self.visit_path_segment(last_segment); - } - } - - _ => { - intravisit::walk_ty(self, ty); - } - } - } - - fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) { - if let hir::LifetimeName::Param(def_id) = lifetime_ref.res { - self.regions.insert(def_id); - } - } - } - - #[derive(Default)] - struct AllCollector { - regions: FxHashSet, - } - - impl<'v> Visitor<'v> for AllCollector { - fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) { - if let hir::LifetimeName::Param(def_id) = lifetime_ref.res { - self.regions.insert(def_id); - } - } - } -} diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs new file mode 100644 index 00000000000..0b570f21178 --- /dev/null +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -0,0 +1,1884 @@ +//! Resolution of early vs late bound lifetimes. +//! +//! Name resolution for lifetimes is performed on the AST and embedded into HIR. From this +//! information, typechecking needs to transform the lifetime parameters into bound lifetimes. +//! Lifetimes can be early-bound or late-bound. Construction of typechecking terms needs to visit +//! the types in HIR to identify late-bound lifetimes and assign their Debruijn indices. This file +//! is also responsible for assigning their semantics to implicit lifetimes in trait objects. + +use rustc_ast::walk_list; +use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; +use rustc_errors::struct_span_err; +use rustc_hir as hir; +use rustc_hir::def::{DefKind, Res}; +use rustc_hir::def_id::LocalDefId; +use rustc_hir::intravisit::{self, Visitor}; +use rustc_hir::{GenericArg, GenericParam, GenericParamKind, HirIdMap, LifetimeName, Node}; +use rustc_middle::bug; +use rustc_middle::hir::nested_filter; +use rustc_middle::middle::resolve_bound_vars::*; +use rustc_middle::ty::{self, ir::TypeVisitor, DefIdTree, TyCtxt, TypeSuperVisitable}; +use rustc_span::def_id::DefId; +use rustc_span::symbol::{sym, Ident}; +use rustc_span::Span; +use std::fmt; + +trait RegionExt { + fn early(param: &GenericParam<'_>) -> (LocalDefId, ResolvedArg); + + fn late(index: u32, param: &GenericParam<'_>) -> (LocalDefId, ResolvedArg); + + fn id(&self) -> Option; + + fn shifted(self, amount: u32) -> ResolvedArg; +} + +impl RegionExt for ResolvedArg { + fn early(param: &GenericParam<'_>) -> (LocalDefId, ResolvedArg) { + debug!("Region::early: def_id={:?}", param.def_id); + (param.def_id, ResolvedArg::EarlyBound(param.def_id.to_def_id())) + } + + fn late(idx: u32, param: &GenericParam<'_>) -> (LocalDefId, ResolvedArg) { + let depth = ty::INNERMOST; + debug!( + "Region::late: idx={:?}, param={:?} depth={:?} def_id={:?}", + idx, param, depth, param.def_id, + ); + (param.def_id, ResolvedArg::LateBound(depth, idx, param.def_id.to_def_id())) + } + + fn id(&self) -> Option { + match *self { + ResolvedArg::StaticLifetime => None, + + ResolvedArg::EarlyBound(id) + | ResolvedArg::LateBound(_, _, id) + | ResolvedArg::Free(_, id) => Some(id), + } + } + + fn shifted(self, amount: u32) -> ResolvedArg { + match self { + ResolvedArg::LateBound(debruijn, idx, id) => { + ResolvedArg::LateBound(debruijn.shifted_in(amount), idx, id) + } + _ => self, + } + } +} + +/// Maps the id of each bound variable reference to the variable decl +/// that it corresponds to. +/// +/// FIXME. This struct gets converted to a `ResolveBoundVars` for +/// actual use. It has the same data, but indexed by `LocalDefId`. This +/// is silly. +#[derive(Debug, Default)] +struct NamedVarMap { + // maps from every use of a named (not anonymous) bound var to a + // `ResolvedArg` describing how that variable is bound + defs: HirIdMap, + + // Maps relevant hir items to the bound vars on them. These include: + // - function defs + // - function pointers + // - closures + // - trait refs + // - bound types (like `T` in `for<'a> T<'a>: Foo`) + late_bound_vars: HirIdMap>, +} + +struct BoundVarContext<'a, 'tcx> { + tcx: TyCtxt<'tcx>, + map: &'a mut NamedVarMap, + scope: ScopeRef<'a>, +} + +#[derive(Debug)] +enum Scope<'a> { + /// Declares lifetimes, and each can be early-bound or late-bound. + /// The `DebruijnIndex` of late-bound lifetimes starts at `1` and + /// it should be shifted by the number of `Binder`s in between the + /// declaration `Binder` and the location it's referenced from. + Binder { + /// We use an IndexMap here because we want these lifetimes in order + /// for diagnostics. + bound_vars: FxIndexMap, + + scope_type: BinderScopeType, + + /// The late bound vars for a given item are stored by `HirId` to be + /// queried later. However, if we enter an elision scope, we have to + /// later append the elided bound vars to the list and need to know what + /// to append to. + hir_id: hir::HirId, + + s: ScopeRef<'a>, + + /// If this binder comes from a where clause, specify how it was created. + /// This is used to diagnose inaccessible lifetimes in APIT: + /// ```ignore (illustrative) + /// fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {} + /// ``` + where_bound_origin: Option, + }, + + /// Lifetimes introduced by a fn are scoped to the call-site for that fn, + /// if this is a fn body, otherwise the original definitions are used. + /// Unspecified lifetimes are inferred, unless an elision scope is nested, + /// e.g., `(&T, fn(&T) -> &T);` becomes `(&'_ T, for<'a> fn(&'a T) -> &'a T)`. + Body { + id: hir::BodyId, + s: ScopeRef<'a>, + }, + + /// A scope which either determines unspecified lifetimes or errors + /// on them (e.g., due to ambiguity). + Elision { + s: ScopeRef<'a>, + }, + + /// Use a specific lifetime (if `Some`) or leave it unset (to be + /// inferred in a function body or potentially error outside one), + /// for the default choice of lifetime in a trait object type. + ObjectLifetimeDefault { + lifetime: Option, + s: ScopeRef<'a>, + }, + + /// When we have nested trait refs, we concatenate late bound vars for inner + /// trait refs from outer ones. But we also need to include any HRTB + /// lifetimes encountered when identifying the trait that an associated type + /// is declared on. + Supertrait { + bound_vars: Vec, + s: ScopeRef<'a>, + }, + + TraitRefBoundary { + s: ScopeRef<'a>, + }, + + Root { + opt_parent_item: Option, + }, +} + +#[derive(Copy, Clone, Debug)] +enum BinderScopeType { + /// Any non-concatenating binder scopes. + Normal, + /// Within a syntactic trait ref, there may be multiple poly trait refs that + /// are nested (under the `associated_type_bounds` feature). The binders of + /// the inner poly trait refs are extended from the outer poly trait refs + /// and don't increase the late bound depth. If you had + /// `T: for<'a> Foo Baz<'a, 'b>>`, then the `for<'b>` scope + /// would be `Concatenating`. This also used in trait refs in where clauses + /// where we have two binders `for<> T: for<> Foo` (I've intentionally left + /// out any lifetimes because they aren't needed to show the two scopes). + /// The inner `for<>` has a scope of `Concatenating`. + Concatenating, +} + +// A helper struct for debugging scopes without printing parent scopes +struct TruncatedScopeDebug<'a>(&'a Scope<'a>); + +impl<'a> fmt::Debug for TruncatedScopeDebug<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self.0 { + Scope::Binder { bound_vars, scope_type, hir_id, where_bound_origin, s: _ } => f + .debug_struct("Binder") + .field("bound_vars", bound_vars) + .field("scope_type", scope_type) + .field("hir_id", hir_id) + .field("where_bound_origin", where_bound_origin) + .field("s", &"..") + .finish(), + Scope::Body { id, s: _ } => { + f.debug_struct("Body").field("id", id).field("s", &"..").finish() + } + Scope::Elision { s: _ } => f.debug_struct("Elision").field("s", &"..").finish(), + Scope::ObjectLifetimeDefault { lifetime, s: _ } => f + .debug_struct("ObjectLifetimeDefault") + .field("lifetime", lifetime) + .field("s", &"..") + .finish(), + Scope::Supertrait { bound_vars, s: _ } => f + .debug_struct("Supertrait") + .field("bound_vars", bound_vars) + .field("s", &"..") + .finish(), + Scope::TraitRefBoundary { s: _ } => f.debug_struct("TraitRefBoundary").finish(), + Scope::Root { opt_parent_item } => { + f.debug_struct("Root").field("opt_parent_item", &opt_parent_item).finish() + } + } + } +} + +type ScopeRef<'a> = &'a Scope<'a>; + +pub(crate) fn provide(providers: &mut ty::query::Providers) { + *providers = ty::query::Providers { + resolve_bound_vars, + + named_variable_map: |tcx, id| tcx.resolve_bound_vars(id).defs.get(&id), + is_late_bound_map, + object_lifetime_default, + late_bound_vars_map: |tcx, id| tcx.resolve_bound_vars(id).late_bound_vars.get(&id), + + ..*providers + }; +} + +/// Computes the `ResolveBoundVars` map that contains data for an entire `Item`. +/// You should not read the result of this query directly, but rather use +/// `named_variable_map`, `is_late_bound_map`, etc. +#[instrument(level = "debug", skip(tcx))] +fn resolve_bound_vars(tcx: TyCtxt<'_>, local_def_id: hir::OwnerId) -> ResolveBoundVars { + let mut named_variable_map = + NamedVarMap { defs: Default::default(), late_bound_vars: Default::default() }; + let mut visitor = BoundVarContext { + tcx, + map: &mut named_variable_map, + scope: &Scope::Root { opt_parent_item: None }, + }; + match tcx.hir().owner(local_def_id) { + hir::OwnerNode::Item(item) => visitor.visit_item(item), + hir::OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item), + hir::OwnerNode::TraitItem(item) => { + let scope = + Scope::Root { opt_parent_item: Some(tcx.local_parent(item.owner_id.def_id)) }; + visitor.scope = &scope; + visitor.visit_trait_item(item) + } + hir::OwnerNode::ImplItem(item) => { + let scope = + Scope::Root { opt_parent_item: Some(tcx.local_parent(item.owner_id.def_id)) }; + visitor.scope = &scope; + visitor.visit_impl_item(item) + } + hir::OwnerNode::Crate(_) => {} + } + + let mut rl = ResolveBoundVars::default(); + + for (hir_id, v) in named_variable_map.defs { + let map = rl.defs.entry(hir_id.owner).or_default(); + map.insert(hir_id.local_id, v); + } + for (hir_id, v) in named_variable_map.late_bound_vars { + let map = rl.late_bound_vars.entry(hir_id.owner).or_default(); + map.insert(hir_id.local_id, v); + } + + debug!(?rl.defs); + debug!(?rl.late_bound_vars); + rl +} + +fn late_region_as_bound_region(tcx: TyCtxt<'_>, region: &ResolvedArg) -> ty::BoundVariableKind { + match region { + ResolvedArg::LateBound(_, _, def_id) => { + let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local())); + ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name)) + } + _ => bug!("{:?} is not a late argument", region), + } +} + +impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { + /// Returns the binders in scope and the type of `Binder` that should be created for a poly trait ref. + fn poly_trait_ref_binder_info(&mut self) -> (Vec, BinderScopeType) { + let mut scope = self.scope; + let mut supertrait_bound_vars = vec![]; + loop { + match scope { + Scope::Body { .. } | Scope::Root { .. } => { + break (vec![], BinderScopeType::Normal); + } + + Scope::Elision { s, .. } | Scope::ObjectLifetimeDefault { s, .. } => { + scope = s; + } + + Scope::Supertrait { s, bound_vars } => { + supertrait_bound_vars = bound_vars.clone(); + scope = s; + } + + Scope::TraitRefBoundary { .. } => { + // We should only see super trait lifetimes if there is a `Binder` above + assert!(supertrait_bound_vars.is_empty()); + break (vec![], BinderScopeType::Normal); + } + + Scope::Binder { hir_id, .. } => { + // Nested poly trait refs have the binders concatenated + let mut full_binders = + self.map.late_bound_vars.entry(*hir_id).or_default().clone(); + full_binders.extend(supertrait_bound_vars.into_iter()); + break (full_binders, BinderScopeType::Concatenating); + } + } + } + } +} +impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { + type NestedFilter = nested_filter::OnlyBodies; + + fn nested_visit_map(&mut self) -> Self::Map { + self.tcx.hir() + } + + fn visit_nested_body(&mut self, body: hir::BodyId) { + let body = self.tcx.hir().body(body); + self.with(Scope::Body { id: body.id(), s: self.scope }, |this| { + this.visit_body(body); + }); + } + + fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { + if let hir::ExprKind::Closure(hir::Closure { + binder, bound_generic_params, fn_decl, .. + }) = e.kind + { + if let &hir::ClosureBinder::For { span: for_sp, .. } = binder { + fn span_of_infer(ty: &hir::Ty<'_>) -> Option { + struct V(Option); + + impl<'v> Visitor<'v> for V { + fn visit_ty(&mut self, t: &'v hir::Ty<'v>) { + match t.kind { + _ if self.0.is_some() => (), + hir::TyKind::Infer => { + self.0 = Some(t.span); + } + _ => intravisit::walk_ty(self, t), + } + } + } + + let mut v = V(None); + v.visit_ty(ty); + v.0 + } + + let infer_in_rt_sp = match fn_decl.output { + hir::FnRetTy::DefaultReturn(sp) => Some(sp), + hir::FnRetTy::Return(ty) => span_of_infer(ty), + }; + + let infer_spans = fn_decl + .inputs + .into_iter() + .filter_map(span_of_infer) + .chain(infer_in_rt_sp) + .collect::>(); + + if !infer_spans.is_empty() { + self.tcx.sess + .struct_span_err( + infer_spans, + "implicit types in closure signatures are forbidden when `for<...>` is present", + ) + .span_label(for_sp, "`for<...>` is here") + .emit(); + } + } + + let (bound_vars, binders): (FxIndexMap, Vec<_>) = + bound_generic_params + .iter() + .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) + .enumerate() + .map(|(late_bound_idx, param)| { + let pair = ResolvedArg::late(late_bound_idx as u32, param); + let r = late_region_as_bound_region(self.tcx, &pair.1); + (pair, r) + }) + .unzip(); + + self.record_late_bound_vars(e.hir_id, binders); + let scope = Scope::Binder { + hir_id: e.hir_id, + bound_vars, + s: self.scope, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + + self.with(scope, |this| { + // a closure has no bounds, so everything + // contained within is scoped within its binder. + intravisit::walk_expr(this, e) + }); + } else { + intravisit::walk_expr(self, e) + } + } + + #[instrument(level = "debug", skip(self))] + fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { + match &item.kind { + hir::ItemKind::Impl(hir::Impl { of_trait, .. }) => { + if let Some(of_trait) = of_trait { + self.record_late_bound_vars(of_trait.hir_ref_id, Vec::default()); + } + } + _ => {} + } + match item.kind { + hir::ItemKind::Fn(_, generics, _) => { + self.visit_early_late(item.hir_id(), generics, |this| { + intravisit::walk_item(this, item); + }); + } + + hir::ItemKind::ExternCrate(_) + | hir::ItemKind::Use(..) + | hir::ItemKind::Macro(..) + | hir::ItemKind::Mod(..) + | hir::ItemKind::ForeignMod { .. } + | hir::ItemKind::GlobalAsm(..) => { + // These sorts of items have no lifetime parameters at all. + intravisit::walk_item(self, item); + } + hir::ItemKind::Static(..) | hir::ItemKind::Const(..) => { + // No lifetime parameters, but implied 'static. + self.with(Scope::Elision { s: self.scope }, |this| { + intravisit::walk_item(this, item) + }); + } + hir::ItemKind::OpaqueTy(hir::OpaqueTy { + origin: hir::OpaqueTyOrigin::TyAlias, .. + }) => { + // Opaque types are visited when we visit the + // `TyKind::OpaqueDef`, so that they have the lifetimes from + // their parent opaque_ty in scope. + // + // The core idea here is that since OpaqueTys are generated with the impl Trait as + // their owner, we can keep going until we find the Item that owns that. We then + // conservatively add all resolved lifetimes. Otherwise we run into problems in + // cases like `type Foo<'a> = impl Bar`. + let parent_item = self.tcx.hir().get_parent_item(item.hir_id()); + let resolved_lifetimes: &ResolveBoundVars = + self.tcx.resolve_bound_vars(parent_item); + // We need to add *all* deps, since opaque tys may want them from *us* + for (&owner, defs) in resolved_lifetimes.defs.iter() { + defs.iter().for_each(|(&local_id, region)| { + self.map.defs.insert(hir::HirId { owner, local_id }, *region); + }); + } + for (&owner, late_bound_vars) in resolved_lifetimes.late_bound_vars.iter() { + late_bound_vars.iter().for_each(|(&local_id, late_bound_vars)| { + self.record_late_bound_vars( + hir::HirId { owner, local_id }, + late_bound_vars.clone(), + ); + }); + } + } + hir::ItemKind::OpaqueTy(hir::OpaqueTy { + origin: hir::OpaqueTyOrigin::FnReturn(_) | hir::OpaqueTyOrigin::AsyncFn(_), + generics, + .. + }) => { + // We want to start our early-bound indices at the end of the parent scope, + // not including any parent `impl Trait`s. + let mut bound_vars = FxIndexMap::default(); + debug!(?generics.params); + for param in generics.params { + match param.kind { + GenericParamKind::Lifetime { .. } => { + let (def_id, reg) = ResolvedArg::early(¶m); + bound_vars.insert(def_id, reg); + } + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {} + } + } + + let scope = Scope::Binder { + hir_id: item.hir_id(), + bound_vars, + s: self.scope, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + self.with(scope, |this| { + let scope = Scope::TraitRefBoundary { s: this.scope }; + this.with(scope, |this| intravisit::walk_item(this, item)) + }); + } + hir::ItemKind::TyAlias(_, generics) + | hir::ItemKind::Enum(_, generics) + | hir::ItemKind::Struct(_, generics) + | hir::ItemKind::Union(_, generics) + | hir::ItemKind::Trait(_, _, generics, ..) + | hir::ItemKind::TraitAlias(generics, ..) + | hir::ItemKind::Impl(&hir::Impl { generics, .. }) => { + // These kinds of items have only early-bound lifetime parameters. + let bound_vars = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => Some(ResolvedArg::early(param)), + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => None, + }) + .collect(); + self.record_late_bound_vars(item.hir_id(), vec![]); + let scope = Scope::Binder { + hir_id: item.hir_id(), + bound_vars, + scope_type: BinderScopeType::Normal, + s: self.scope, + where_bound_origin: None, + }; + self.with(scope, |this| { + let scope = Scope::TraitRefBoundary { s: this.scope }; + this.with(scope, |this| { + intravisit::walk_item(this, item); + }); + }); + } + } + } + + fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) { + match item.kind { + hir::ForeignItemKind::Fn(_, _, generics) => { + self.visit_early_late(item.hir_id(), generics, |this| { + intravisit::walk_foreign_item(this, item); + }) + } + hir::ForeignItemKind::Static(..) => { + intravisit::walk_foreign_item(self, item); + } + hir::ForeignItemKind::Type => { + intravisit::walk_foreign_item(self, item); + } + } + } + + #[instrument(level = "debug", skip(self))] + fn visit_ty(&mut self, ty: &'tcx hir::Ty<'tcx>) { + match ty.kind { + hir::TyKind::BareFn(c) => { + let (bound_vars, binders): (FxIndexMap, Vec<_>) = c + .generic_params + .iter() + .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) + .enumerate() + .map(|(late_bound_idx, param)| { + let pair = ResolvedArg::late(late_bound_idx as u32, param); + let r = late_region_as_bound_region(self.tcx, &pair.1); + (pair, r) + }) + .unzip(); + self.record_late_bound_vars(ty.hir_id, binders); + let scope = Scope::Binder { + hir_id: ty.hir_id, + bound_vars, + s: self.scope, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + self.with(scope, |this| { + // a bare fn has no bounds, so everything + // contained within is scoped within its binder. + intravisit::walk_ty(this, ty); + }); + } + hir::TyKind::TraitObject(bounds, lifetime, _) => { + debug!(?bounds, ?lifetime, "TraitObject"); + let scope = Scope::TraitRefBoundary { s: self.scope }; + self.with(scope, |this| { + for bound in bounds { + this.visit_poly_trait_ref(bound); + } + }); + match lifetime.res { + LifetimeName::ImplicitObjectLifetimeDefault => { + // If the user does not write *anything*, we + // use the object lifetime defaulting + // rules. So e.g., `Box` becomes + // `Box`. + self.resolve_object_lifetime_default(lifetime) + } + LifetimeName::Infer => { + // If the user writes `'_`, we use the *ordinary* elision + // rules. So the `'_` in e.g., `Box` will be + // resolved the same as the `'_` in `&'_ Foo`. + // + // cc #48468 + } + LifetimeName::Param(..) | LifetimeName::Static => { + // If the user wrote an explicit name, use that. + self.visit_lifetime(lifetime); + } + LifetimeName::Error => {} + } + } + hir::TyKind::Ref(lifetime_ref, ref mt) => { + self.visit_lifetime(lifetime_ref); + let scope = Scope::ObjectLifetimeDefault { + lifetime: self.map.defs.get(&lifetime_ref.hir_id).cloned(), + s: self.scope, + }; + self.with(scope, |this| this.visit_ty(&mt.ty)); + } + hir::TyKind::OpaqueDef(item_id, lifetimes, _in_trait) => { + // Resolve the lifetimes in the bounds to the lifetime defs in the generics. + // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to + // `type MyAnonTy<'b> = impl MyTrait<'b>;` + // ^ ^ this gets resolved in the scope of + // the opaque_ty generics + let opaque_ty = self.tcx.hir().item(item_id); + match &opaque_ty.kind { + hir::ItemKind::OpaqueTy(hir::OpaqueTy { + origin: hir::OpaqueTyOrigin::TyAlias, + .. + }) => { + intravisit::walk_ty(self, ty); + + // Elided lifetimes are not allowed in non-return + // position impl Trait + let scope = Scope::TraitRefBoundary { s: self.scope }; + self.with(scope, |this| { + let scope = Scope::Elision { s: this.scope }; + this.with(scope, |this| { + intravisit::walk_item(this, opaque_ty); + }) + }); + + return; + } + hir::ItemKind::OpaqueTy(hir::OpaqueTy { + origin: hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..), + .. + }) => {} + i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i), + }; + + // Resolve the lifetimes that are applied to the opaque type. + // These are resolved in the current scope. + // `fn foo<'a>() -> impl MyTrait<'a> { ... }` desugars to + // `fn foo<'a>() -> MyAnonTy<'a> { ... }` + // ^ ^this gets resolved in the current scope + for lifetime in lifetimes { + let hir::GenericArg::Lifetime(lifetime) = lifetime else { + continue + }; + self.visit_lifetime(lifetime); + + // Check for predicates like `impl for<'a> Trait>` + // and ban them. Type variables instantiated inside binders aren't + // well-supported at the moment, so this doesn't work. + // In the future, this should be fixed and this error should be removed. + let def = self.map.defs.get(&lifetime.hir_id).cloned(); + let Some(ResolvedArg::LateBound(_, _, def_id)) = def else { + continue + }; + let Some(def_id) = def_id.as_local() else { + continue + }; + let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); + // Ensure that the parent of the def is an item, not HRTB + let parent_id = self.tcx.hir().parent_id(hir_id); + if !parent_id.is_owner() { + struct_span_err!( + self.tcx.sess, + lifetime.ident.span, + E0657, + "`impl Trait` can only capture lifetimes bound at the fn or impl level" + ) + .emit(); + self.uninsert_lifetime_on_error(lifetime, def.unwrap()); + } + if let hir::Node::Item(hir::Item { + kind: hir::ItemKind::OpaqueTy { .. }, .. + }) = self.tcx.hir().get(parent_id) + { + let mut err = self.tcx.sess.struct_span_err( + lifetime.ident.span, + "higher kinded lifetime bounds on nested opaque types are not supported yet", + ); + err.span_note(self.tcx.def_span(def_id), "lifetime declared here"); + err.emit(); + self.uninsert_lifetime_on_error(lifetime, def.unwrap()); + } + } + } + _ => intravisit::walk_ty(self, ty), + } + } + + #[instrument(level = "debug", skip(self))] + fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { + use self::hir::TraitItemKind::*; + match trait_item.kind { + Fn(_, _) => { + self.visit_early_late(trait_item.hir_id(), &trait_item.generics, |this| { + intravisit::walk_trait_item(this, trait_item) + }); + } + Type(bounds, ty) => { + let generics = &trait_item.generics; + let bound_vars = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => Some(ResolvedArg::early(param)), + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => None, + }) + .collect(); + self.record_late_bound_vars(trait_item.hir_id(), vec![]); + let scope = Scope::Binder { + hir_id: trait_item.hir_id(), + bound_vars, + s: self.scope, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + self.with(scope, |this| { + let scope = Scope::TraitRefBoundary { s: this.scope }; + this.with(scope, |this| { + this.visit_generics(generics); + for bound in bounds { + this.visit_param_bound(bound); + } + if let Some(ty) = ty { + this.visit_ty(ty); + } + }) + }); + } + Const(_, _) => { + // Only methods and types support generics. + assert!(trait_item.generics.params.is_empty()); + intravisit::walk_trait_item(self, trait_item); + } + } + } + + #[instrument(level = "debug", skip(self))] + fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { + use self::hir::ImplItemKind::*; + match impl_item.kind { + Fn(..) => self.visit_early_late(impl_item.hir_id(), &impl_item.generics, |this| { + intravisit::walk_impl_item(this, impl_item) + }), + Type(ty) => { + let generics = &impl_item.generics; + let bound_vars: FxIndexMap = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => Some(ResolvedArg::early(param)), + GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => None, + }) + .collect(); + self.record_late_bound_vars(impl_item.hir_id(), vec![]); + let scope = Scope::Binder { + hir_id: impl_item.hir_id(), + bound_vars, + s: self.scope, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + self.with(scope, |this| { + let scope = Scope::TraitRefBoundary { s: this.scope }; + this.with(scope, |this| { + this.visit_generics(generics); + this.visit_ty(ty); + }) + }); + } + Const(_, _) => { + // Only methods and types support generics. + assert!(impl_item.generics.params.is_empty()); + intravisit::walk_impl_item(self, impl_item); + } + } + } + + #[instrument(level = "debug", skip(self))] + fn visit_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime) { + match lifetime_ref.res { + hir::LifetimeName::Static => { + self.insert_lifetime(lifetime_ref, ResolvedArg::StaticLifetime) + } + hir::LifetimeName::Param(param_def_id) => { + self.resolve_lifetime_ref(param_def_id, lifetime_ref) + } + // If we've already reported an error, just ignore `lifetime_ref`. + hir::LifetimeName::Error => {} + // Those will be resolved by typechecking. + hir::LifetimeName::ImplicitObjectLifetimeDefault | hir::LifetimeName::Infer => {} + } + } + + fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) { + for (i, segment) in path.segments.iter().enumerate() { + let depth = path.segments.len() - i - 1; + if let Some(args) = segment.args { + self.visit_segment_args(path.res, depth, args); + } + } + } + + fn visit_fn( + &mut self, + fk: intravisit::FnKind<'tcx>, + fd: &'tcx hir::FnDecl<'tcx>, + body_id: hir::BodyId, + _: Span, + _: LocalDefId, + ) { + let output = match fd.output { + hir::FnRetTy::DefaultReturn(_) => None, + hir::FnRetTy::Return(ty) => Some(ty), + }; + self.visit_fn_like_elision(&fd.inputs, output, matches!(fk, intravisit::FnKind::Closure)); + intravisit::walk_fn_kind(self, fk); + self.visit_nested_body(body_id) + } + + fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { + let scope = Scope::TraitRefBoundary { s: self.scope }; + self.with(scope, |this| { + for param in generics.params { + match param.kind { + GenericParamKind::Lifetime { .. } => {} + GenericParamKind::Type { default, .. } => { + if let Some(ty) = default { + this.visit_ty(ty); + } + } + GenericParamKind::Const { ty, default } => { + this.visit_ty(ty); + if let Some(default) = default { + this.visit_body(this.tcx.hir().body(default.body)); + } + } + } + } + for predicate in generics.predicates { + match predicate { + &hir::WherePredicate::BoundPredicate(hir::WhereBoundPredicate { + hir_id, + bounded_ty, + bounds, + bound_generic_params, + origin, + .. + }) => { + let bound_vars: FxIndexMap = + bound_generic_params + .iter() + .filter(|param| { + matches!(param.kind, GenericParamKind::Lifetime { .. }) + }) + .enumerate() + .map(|(late_bound_idx, param)| { + ResolvedArg::late(late_bound_idx as u32, param) + }) + .collect(); + let binders: Vec<_> = + bound_vars + .iter() + .map(|(_, region)| { + late_region_as_bound_region(this.tcx, region) + }) + .collect(); + this.record_late_bound_vars(hir_id, binders.clone()); + // Even if there are no lifetimes defined here, we still wrap it in a binder + // scope. If there happens to be a nested poly trait ref (an error), that + // will be `Concatenating` anyways, so we don't have to worry about the depth + // being wrong. + let scope = Scope::Binder { + hir_id, + bound_vars, + s: this.scope, + scope_type: BinderScopeType::Normal, + where_bound_origin: Some(origin), + }; + this.with(scope, |this| { + this.visit_ty(&bounded_ty); + walk_list!(this, visit_param_bound, bounds); + }) + } + &hir::WherePredicate::RegionPredicate(hir::WhereRegionPredicate { + lifetime, + bounds, + .. + }) => { + this.visit_lifetime(lifetime); + walk_list!(this, visit_param_bound, bounds); + + if lifetime.res != hir::LifetimeName::Static { + for bound in bounds { + let hir::GenericBound::Outlives(lt) = bound else { + continue; + }; + if lt.res != hir::LifetimeName::Static { + continue; + } + this.insert_lifetime(lt, ResolvedArg::StaticLifetime); + this.tcx + .sess + .struct_span_warn( + lifetime.ident.span, + &format!( + "unnecessary lifetime parameter `{}`", + lifetime.ident, + ), + ) + .help(&format!( + "you can use the `'static` lifetime directly, in place of `{}`", + lifetime.ident, + )) + .emit(); + } + } + } + &hir::WherePredicate::EqPredicate(hir::WhereEqPredicate { + lhs_ty, + rhs_ty, + .. + }) => { + this.visit_ty(lhs_ty); + this.visit_ty(rhs_ty); + } + } + } + }) + } + + fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) { + match bound { + hir::GenericBound::LangItemTrait(_, _, hir_id, _) => { + // FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go + // through the regular poly trait ref code, so we don't get another + // chance to introduce a binder. For now, I'm keeping the existing logic + // of "if there isn't a Binder scope above us, add one", but I + // imagine there's a better way to go about this. + let (binders, scope_type) = self.poly_trait_ref_binder_info(); + + self.record_late_bound_vars(*hir_id, binders); + let scope = Scope::Binder { + hir_id: *hir_id, + bound_vars: FxIndexMap::default(), + s: self.scope, + scope_type, + where_bound_origin: None, + }; + self.with(scope, |this| { + intravisit::walk_param_bound(this, bound); + }); + } + _ => intravisit::walk_param_bound(self, bound), + } + } + + fn visit_poly_trait_ref(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) { + debug!("visit_poly_trait_ref(trait_ref={:?})", trait_ref); + + let (mut binders, scope_type) = self.poly_trait_ref_binder_info(); + + let initial_bound_vars = binders.len() as u32; + let mut bound_vars: FxIndexMap = FxIndexMap::default(); + let binders_iter = trait_ref + .bound_generic_params + .iter() + .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) + .enumerate() + .map(|(late_bound_idx, param)| { + let pair = ResolvedArg::late(initial_bound_vars + late_bound_idx as u32, param); + let r = late_region_as_bound_region(self.tcx, &pair.1); + bound_vars.insert(pair.0, pair.1); + r + }); + binders.extend(binders_iter); + + debug!(?binders); + self.record_late_bound_vars(trait_ref.trait_ref.hir_ref_id, binders); + + // Always introduce a scope here, even if this is in a where clause and + // we introduced the binders around the bounded Ty. In that case, we + // just reuse the concatenation functionality also present in nested trait + // refs. + let scope = Scope::Binder { + hir_id: trait_ref.trait_ref.hir_ref_id, + bound_vars, + s: self.scope, + scope_type, + where_bound_origin: None, + }; + self.with(scope, |this| { + walk_list!(this, visit_generic_param, trait_ref.bound_generic_params); + this.visit_trait_ref(&trait_ref.trait_ref); + }); + } +} + +fn object_lifetime_default(tcx: TyCtxt<'_>, param_def_id: DefId) -> ObjectLifetimeDefault { + debug_assert_eq!(tcx.def_kind(param_def_id), DefKind::TyParam); + let param_def_id = param_def_id.expect_local(); + let parent_def_id = tcx.local_parent(param_def_id); + let generics = tcx.hir().get_generics(parent_def_id).unwrap(); + let param_hir_id = tcx.local_def_id_to_hir_id(param_def_id); + let param = generics.params.iter().find(|p| p.hir_id == param_hir_id).unwrap(); + + // Scan the bounds and where-clauses on parameters to extract bounds + // of the form `T:'a` so as to determine the `ObjectLifetimeDefault` + // for each type parameter. + match param.kind { + GenericParamKind::Type { .. } => { + let mut set = Set1::Empty; + + // Look for `type: ...` where clauses. + for bound in generics.bounds_for_param(param_def_id) { + // Ignore `for<'a> type: ...` as they can change what + // lifetimes mean (although we could "just" handle it). + if !bound.bound_generic_params.is_empty() { + continue; + } + + for bound in bound.bounds { + if let hir::GenericBound::Outlives(lifetime) = bound { + set.insert(lifetime.res); + } + } + } + + match set { + Set1::Empty => ObjectLifetimeDefault::Empty, + Set1::One(hir::LifetimeName::Static) => ObjectLifetimeDefault::Static, + Set1::One(hir::LifetimeName::Param(param_def_id)) => { + ObjectLifetimeDefault::Param(param_def_id.to_def_id()) + } + _ => ObjectLifetimeDefault::Ambiguous, + } + } + _ => { + bug!("object_lifetime_default_raw must only be called on a type parameter") + } + } +} + +impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { + fn with(&mut self, wrap_scope: Scope<'_>, f: F) + where + F: for<'b> FnOnce(&mut BoundVarContext<'b, 'tcx>), + { + let BoundVarContext { tcx, map, .. } = self; + let mut this = BoundVarContext { tcx: *tcx, map, scope: &wrap_scope }; + let span = debug_span!("scope", scope = ?TruncatedScopeDebug(&this.scope)); + { + let _enter = span.enter(); + f(&mut this); + } + } + + fn record_late_bound_vars(&mut self, hir_id: hir::HirId, binder: Vec) { + if let Some(old) = self.map.late_bound_vars.insert(hir_id, binder) { + bug!( + "overwrote bound vars for {hir_id:?}:\nold={old:?}\nnew={:?}", + self.map.late_bound_vars[&hir_id] + ) + } + } + + /// Visits self by adding a scope and handling recursive walk over the contents with `walk`. + /// + /// Handles visiting fns and methods. These are a bit complicated because we must distinguish + /// early- vs late-bound lifetime parameters. We do this by checking which lifetimes appear + /// within type bounds; those are early bound lifetimes, and the rest are late bound. + /// + /// For example: + /// + /// fn foo<'a,'b,'c,T:Trait<'b>>(...) + /// + /// Here `'a` and `'c` are late bound but `'b` is early bound. Note that early- and late-bound + /// lifetimes may be interspersed together. + /// + /// If early bound lifetimes are present, we separate them into their own list (and likewise + /// for late bound). They will be numbered sequentially, starting from the lowest index that is + /// already in scope (for a fn item, that will be 0, but for a method it might not be). Late + /// bound lifetimes are resolved by name and associated with a binder ID (`binder_id`), so the + /// ordering is not important there. + fn visit_early_late( + &mut self, + hir_id: hir::HirId, + generics: &'tcx hir::Generics<'tcx>, + walk: F, + ) where + F: for<'b, 'c> FnOnce(&'b mut BoundVarContext<'c, 'tcx>), + { + let mut named_late_bound_vars = 0; + let bound_vars: FxIndexMap = generics + .params + .iter() + .filter_map(|param| match param.kind { + GenericParamKind::Lifetime { .. } => { + if self.tcx.is_late_bound(param.hir_id) { + let late_bound_idx = named_late_bound_vars; + named_late_bound_vars += 1; + Some(ResolvedArg::late(late_bound_idx, param)) + } else { + Some(ResolvedArg::early(param)) + } + } + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => None, + }) + .collect(); + + let binders: Vec<_> = generics + .params + .iter() + .filter(|param| { + matches!(param.kind, GenericParamKind::Lifetime { .. }) + && self.tcx.is_late_bound(param.hir_id) + }) + .enumerate() + .map(|(late_bound_idx, param)| { + let pair = ResolvedArg::late(late_bound_idx as u32, param); + late_region_as_bound_region(self.tcx, &pair.1) + }) + .collect(); + self.record_late_bound_vars(hir_id, binders); + let scope = Scope::Binder { + hir_id, + bound_vars, + s: self.scope, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + self.with(scope, walk); + } + + #[instrument(level = "debug", skip(self))] + fn resolve_lifetime_ref( + &mut self, + region_def_id: LocalDefId, + lifetime_ref: &'tcx hir::Lifetime, + ) { + // Walk up the scope chain, tracking the number of fn scopes + // that we pass through, until we find a lifetime with the + // given name or we run out of scopes. + // search. + let mut late_depth = 0; + let mut scope = self.scope; + let mut outermost_body = None; + let result = loop { + match *scope { + Scope::Body { id, s } => { + outermost_body = Some(id); + scope = s; + } + + Scope::Root { opt_parent_item } => { + if let Some(parent_item) = opt_parent_item + && let parent_generics = self.tcx.generics_of(parent_item) + && parent_generics.param_def_id_to_index.contains_key(®ion_def_id.to_def_id()) + { + break Some(ResolvedArg::EarlyBound(region_def_id.to_def_id())); + } + break None; + } + + Scope::Binder { ref bound_vars, scope_type, s, where_bound_origin, .. } => { + if let Some(&def) = bound_vars.get(®ion_def_id) { + break Some(def.shifted(late_depth)); + } + match scope_type { + BinderScopeType::Normal => late_depth += 1, + BinderScopeType::Concatenating => {} + } + // Fresh lifetimes in APIT used to be allowed in async fns and forbidden in + // regular fns. + if let Some(hir::PredicateOrigin::ImplTrait) = where_bound_origin + && let hir::LifetimeName::Param(param_id) = lifetime_ref.res + && let Some(generics) = self.tcx.hir().get_generics(self.tcx.local_parent(param_id)) + && let Some(param) = generics.params.iter().find(|p| p.def_id == param_id) + && param.is_elided_lifetime() + && let hir::IsAsync::NotAsync = self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id) + && !self.tcx.features().anonymous_lifetime_in_impl_trait + { + let mut diag = rustc_session::parse::feature_err( + &self.tcx.sess.parse_sess, + sym::anonymous_lifetime_in_impl_trait, + lifetime_ref.ident.span, + "anonymous lifetimes in `impl Trait` are unstable", + ); + + if let Some(generics) = + self.tcx.hir().get_generics(lifetime_ref.hir_id.owner.def_id) + { + let new_param_sugg = if let Some(span) = + generics.span_for_lifetime_suggestion() + { + (span, "'a, ".to_owned()) + } else { + (generics.span, "<'a>".to_owned()) + }; + + let lifetime_sugg = match lifetime_ref.suggestion_position() { + (hir::LifetimeSuggestionPosition::Normal, span) => (span, "'a".to_owned()), + (hir::LifetimeSuggestionPosition::Ampersand, span) => (span, "'a ".to_owned()), + (hir::LifetimeSuggestionPosition::ElidedPath, span) => (span, "<'a>".to_owned()), + (hir::LifetimeSuggestionPosition::ElidedPathArgument, span) => (span, "'a, ".to_owned()), + (hir::LifetimeSuggestionPosition::ObjectDefault, span) => (span, "+ 'a".to_owned()), + }; + let suggestions = vec![ + lifetime_sugg, + new_param_sugg, + ]; + + diag.span_label( + lifetime_ref.ident.span, + "expected named lifetime parameter", + ); + diag.multipart_suggestion( + "consider introducing a named lifetime parameter", + suggestions, + rustc_errors::Applicability::MaybeIncorrect, + ); + } + + diag.emit(); + return; + } + scope = s; + } + + Scope::Elision { s, .. } + | Scope::ObjectLifetimeDefault { s, .. } + | Scope::Supertrait { s, .. } + | Scope::TraitRefBoundary { s, .. } => { + scope = s; + } + } + }; + + if let Some(mut def) = result { + if let ResolvedArg::EarlyBound(..) = def { + // Do not free early-bound regions, only late-bound ones. + } else if let Some(body_id) = outermost_body { + let fn_id = self.tcx.hir().body_owner(body_id); + match self.tcx.hir().get(fn_id) { + Node::Item(hir::Item { owner_id, kind: hir::ItemKind::Fn(..), .. }) + | Node::TraitItem(hir::TraitItem { + owner_id, + kind: hir::TraitItemKind::Fn(..), + .. + }) + | Node::ImplItem(hir::ImplItem { + owner_id, + kind: hir::ImplItemKind::Fn(..), + .. + }) => { + def = ResolvedArg::Free(owner_id.to_def_id(), def.id().unwrap()); + } + Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(closure), .. }) => { + def = ResolvedArg::Free(closure.def_id.to_def_id(), def.id().unwrap()); + } + _ => {} + } + } + + self.insert_lifetime(lifetime_ref, def); + return; + } + + // We may fail to resolve higher-ranked lifetimes that are mentioned by APIT. + // AST-based resolution does not care for impl-trait desugaring, which are the + // responibility of lowering. This may create a mismatch between the resolution + // AST found (`region_def_id`) which points to HRTB, and what HIR allows. + // ``` + // fn foo(x: impl for<'a> Trait<'a, Assoc = impl Copy + 'a>) {} + // ``` + // + // In such case, walk back the binders to diagnose it properly. + let mut scope = self.scope; + loop { + match *scope { + Scope::Binder { + where_bound_origin: Some(hir::PredicateOrigin::ImplTrait), .. + } => { + let mut err = self.tcx.sess.struct_span_err( + lifetime_ref.ident.span, + "`impl Trait` can only mention lifetimes bound at the fn or impl level", + ); + err.span_note(self.tcx.def_span(region_def_id), "lifetime declared here"); + err.emit(); + return; + } + Scope::Root { .. } => break, + Scope::Binder { s, .. } + | Scope::Body { s, .. } + | Scope::Elision { s, .. } + | Scope::ObjectLifetimeDefault { s, .. } + | Scope::Supertrait { s, .. } + | Scope::TraitRefBoundary { s, .. } => { + scope = s; + } + } + } + + self.tcx.sess.delay_span_bug( + lifetime_ref.ident.span, + &format!("Could not resolve {:?} in scope {:#?}", lifetime_ref, self.scope,), + ); + } + + #[instrument(level = "debug", skip(self))] + fn visit_segment_args( + &mut self, + res: Res, + depth: usize, + generic_args: &'tcx hir::GenericArgs<'tcx>, + ) { + if generic_args.parenthesized { + self.visit_fn_like_elision( + generic_args.inputs(), + Some(generic_args.bindings[0].ty()), + false, + ); + return; + } + + for arg in generic_args.args { + if let hir::GenericArg::Lifetime(lt) = arg { + self.visit_lifetime(lt); + } + } + + // Figure out if this is a type/trait segment, + // which requires object lifetime defaults. + let type_def_id = match res { + Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(self.tcx.parent(def_id)), + Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(self.tcx.parent(def_id)), + Res::Def( + DefKind::Struct + | DefKind::Union + | DefKind::Enum + | DefKind::TyAlias + | DefKind::Trait, + def_id, + ) if depth == 0 => Some(def_id), + _ => None, + }; + + debug!(?type_def_id); + + // Compute a vector of defaults, one for each type parameter, + // per the rules given in RFCs 599 and 1156. Example: + // + // ```rust + // struct Foo<'a, T: 'a, U> { } + // ``` + // + // If you have `Foo<'x, dyn Bar, dyn Baz>`, we want to default + // `dyn Bar` to `dyn Bar + 'x` (because of the `T: 'a` bound) + // and `dyn Baz` to `dyn Baz + 'static` (because there is no + // such bound). + // + // Therefore, we would compute `object_lifetime_defaults` to a + // vector like `['x, 'static]`. Note that the vector only + // includes type parameters. + let object_lifetime_defaults = type_def_id.map_or_else(Vec::new, |def_id| { + let in_body = { + let mut scope = self.scope; + loop { + match *scope { + Scope::Root { .. } => break false, + + Scope::Body { .. } => break true, + + Scope::Binder { s, .. } + | Scope::Elision { s, .. } + | Scope::ObjectLifetimeDefault { s, .. } + | Scope::Supertrait { s, .. } + | Scope::TraitRefBoundary { s, .. } => { + scope = s; + } + } + } + }; + + let map = &self.map; + let generics = self.tcx.generics_of(def_id); + + // `type_def_id` points to an item, so there is nothing to inherit generics from. + debug_assert_eq!(generics.parent_count, 0); + + let set_to_region = |set: ObjectLifetimeDefault| match set { + ObjectLifetimeDefault::Empty => { + if in_body { + None + } else { + Some(ResolvedArg::StaticLifetime) + } + } + ObjectLifetimeDefault::Static => Some(ResolvedArg::StaticLifetime), + ObjectLifetimeDefault::Param(param_def_id) => { + // This index can be used with `generic_args` since `parent_count == 0`. + let index = generics.param_def_id_to_index[¶m_def_id] as usize; + generic_args.args.get(index).and_then(|arg| match arg { + GenericArg::Lifetime(lt) => map.defs.get(<.hir_id).copied(), + _ => None, + }) + } + ObjectLifetimeDefault::Ambiguous => None, + }; + generics + .params + .iter() + .filter_map(|param| { + match self.tcx.def_kind(param.def_id) { + // Generic consts don't impose any constraints. + // + // We still store a dummy value here to allow generic parameters + // in an arbitrary order. + DefKind::ConstParam => Some(ObjectLifetimeDefault::Empty), + DefKind::TyParam => Some(self.tcx.object_lifetime_default(param.def_id)), + // We may also get a `Trait` or `TraitAlias` because of how generics `Self` parameter + // works. Ignore it because it can't have a meaningful lifetime default. + DefKind::LifetimeParam | DefKind::Trait | DefKind::TraitAlias => None, + dk => bug!("unexpected def_kind {:?}", dk), + } + }) + .map(set_to_region) + .collect() + }); + + debug!(?object_lifetime_defaults); + + let mut i = 0; + for arg in generic_args.args { + match arg { + GenericArg::Lifetime(_) => {} + GenericArg::Type(ty) => { + if let Some(<) = object_lifetime_defaults.get(i) { + let scope = Scope::ObjectLifetimeDefault { lifetime: lt, s: self.scope }; + self.with(scope, |this| this.visit_ty(ty)); + } else { + self.visit_ty(ty); + } + i += 1; + } + GenericArg::Const(ct) => { + self.visit_anon_const(&ct.value); + i += 1; + } + GenericArg::Infer(inf) => { + self.visit_id(inf.hir_id); + i += 1; + } + } + } + + // Hack: when resolving the type `XX` in binding like `dyn + // Foo<'b, Item = XX>`, the current object-lifetime default + // would be to examine the trait `Foo` to check whether it has + // a lifetime bound declared on `Item`. e.g., if `Foo` is + // declared like so, then the default object lifetime bound in + // `XX` should be `'b`: + // + // ```rust + // trait Foo<'a> { + // type Item: 'a; + // } + // ``` + // + // but if we just have `type Item;`, then it would be + // `'static`. However, we don't get all of this logic correct. + // + // Instead, we do something hacky: if there are no lifetime parameters + // to the trait, then we simply use a default object lifetime + // bound of `'static`, because there is no other possibility. On the other hand, + // if there ARE lifetime parameters, then we require the user to give an + // explicit bound for now. + // + // This is intended to leave room for us to implement the + // correct behavior in the future. + let has_lifetime_parameter = + generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_))); + + // Resolve lifetimes found in the bindings, so either in the type `XX` in `Item = XX` or + // in the trait ref `YY<...>` in `Item: YY<...>`. + for binding in generic_args.bindings { + let scope = Scope::ObjectLifetimeDefault { + lifetime: if has_lifetime_parameter { + None + } else { + Some(ResolvedArg::StaticLifetime) + }, + s: self.scope, + }; + if let Some(type_def_id) = type_def_id { + let bound_vars = + BoundVarContext::supertrait_hrtb_vars(self.tcx, type_def_id, binding.ident); + self.with(scope, |this| { + let scope = Scope::Supertrait { + bound_vars: bound_vars.unwrap_or_default(), + s: this.scope, + }; + this.with(scope, |this| this.visit_assoc_type_binding(binding)); + }); + } else { + self.with(scope, |this| this.visit_assoc_type_binding(binding)); + } + } + } + + /// Returns all the late-bound vars that come into scope from supertrait HRTBs, based on the + /// associated type name and starting trait. + /// For example, imagine we have + /// ```ignore (illustrative) + /// trait Foo<'a, 'b> { + /// type As; + /// } + /// trait Bar<'b>: for<'a> Foo<'a, 'b> {} + /// trait Bar: for<'b> Bar<'b> {} + /// ``` + /// In this case, if we wanted to the supertrait HRTB lifetimes for `As` on + /// the starting trait `Bar`, we would return `Some(['b, 'a])`. + fn supertrait_hrtb_vars( + tcx: TyCtxt<'tcx>, + def_id: DefId, + assoc_name: Ident, + ) -> Option> { + let trait_defines_associated_type_named = |trait_def_id: DefId| { + tcx.associated_items(trait_def_id) + .find_by_name_and_kind(tcx, assoc_name, ty::AssocKind::Type, trait_def_id) + .is_some() + }; + + use smallvec::{smallvec, SmallVec}; + let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> = + smallvec![(def_id, smallvec![])]; + let mut visited: FxHashSet = FxHashSet::default(); + loop { + let Some((def_id, bound_vars)) = stack.pop() else { + break None; + }; + // See issue #83753. If someone writes an associated type on a non-trait, just treat it as + // there being no supertrait HRTBs. + match tcx.def_kind(def_id) { + DefKind::Trait | DefKind::TraitAlias | DefKind::Impl { .. } => {} + _ => break None, + } + + if trait_defines_associated_type_named(def_id) { + break Some(bound_vars.into_iter().collect()); + } + let predicates = + tcx.super_predicates_that_define_assoc_type((def_id, Some(assoc_name))); + let obligations = predicates.predicates.iter().filter_map(|&(pred, _)| { + let bound_predicate = pred.kind(); + match bound_predicate.skip_binder() { + ty::PredicateKind::Clause(ty::Clause::Trait(data)) => { + // The order here needs to match what we would get from `subst_supertrait` + let pred_bound_vars = bound_predicate.bound_vars(); + let mut all_bound_vars = bound_vars.clone(); + all_bound_vars.extend(pred_bound_vars.iter()); + let super_def_id = data.trait_ref.def_id; + Some((super_def_id, all_bound_vars)) + } + _ => None, + } + }); + + let obligations = obligations.filter(|o| visited.insert(o.0)); + stack.extend(obligations); + } + } + + #[instrument(level = "debug", skip(self))] + fn visit_fn_like_elision( + &mut self, + inputs: &'tcx [hir::Ty<'tcx>], + output: Option<&'tcx hir::Ty<'tcx>>, + in_closure: bool, + ) { + self.with(Scope::Elision { s: self.scope }, |this| { + for input in inputs { + this.visit_ty(input); + } + if !in_closure && let Some(output) = output { + this.visit_ty(output); + } + }); + if in_closure && let Some(output) = output { + self.visit_ty(output); + } + } + + fn resolve_object_lifetime_default(&mut self, lifetime_ref: &'tcx hir::Lifetime) { + debug!("resolve_object_lifetime_default(lifetime_ref={:?})", lifetime_ref); + let mut late_depth = 0; + let mut scope = self.scope; + let lifetime = loop { + match *scope { + Scope::Binder { s, scope_type, .. } => { + match scope_type { + BinderScopeType::Normal => late_depth += 1, + BinderScopeType::Concatenating => {} + } + scope = s; + } + + Scope::Root { .. } | Scope::Elision { .. } => break ResolvedArg::StaticLifetime, + + Scope::Body { .. } | Scope::ObjectLifetimeDefault { lifetime: None, .. } => return, + + Scope::ObjectLifetimeDefault { lifetime: Some(l), .. } => break l, + + Scope::Supertrait { s, .. } | Scope::TraitRefBoundary { s, .. } => { + scope = s; + } + } + }; + self.insert_lifetime(lifetime_ref, lifetime.shifted(late_depth)); + } + + #[instrument(level = "debug", skip(self))] + fn insert_lifetime(&mut self, lifetime_ref: &'tcx hir::Lifetime, def: ResolvedArg) { + debug!(span = ?lifetime_ref.ident.span); + self.map.defs.insert(lifetime_ref.hir_id, def); + } + + /// Sometimes we resolve a lifetime, but later find that it is an + /// error (esp. around impl trait). In that case, we remove the + /// entry into `map.defs` so as not to confuse later code. + fn uninsert_lifetime_on_error( + &mut self, + lifetime_ref: &'tcx hir::Lifetime, + bad_def: ResolvedArg, + ) { + let old_value = self.map.defs.remove(&lifetime_ref.hir_id); + assert_eq!(old_value, Some(bad_def)); + } +} + +/// Detects late-bound lifetimes and inserts them into +/// `late_bound`. +/// +/// A region declared on a fn is **late-bound** if: +/// - it is constrained by an argument type; +/// - it does not appear in a where-clause. +/// +/// "Constrained" basically means that it appears in any type but +/// not amongst the inputs to a projection. In other words, `<&'a +/// T as Trait<''b>>::Foo` does not constrain `'a` or `'b`. +fn is_late_bound_map( + tcx: TyCtxt<'_>, + owner_id: hir::OwnerId, +) -> Option<&FxIndexSet> { + let decl = tcx.hir().fn_decl_by_hir_id(owner_id.into())?; + let generics = tcx.hir().get_generics(owner_id.def_id)?; + + let mut late_bound = FxIndexSet::default(); + + let mut constrained_by_input = ConstrainedCollector { regions: Default::default(), tcx }; + for arg_ty in decl.inputs { + constrained_by_input.visit_ty(arg_ty); + } + + let mut appears_in_output = AllCollector::default(); + intravisit::walk_fn_ret_ty(&mut appears_in_output, &decl.output); + + debug!(?constrained_by_input.regions); + + // Walk the lifetimes that appear in where clauses. + // + // Subtle point: because we disallow nested bindings, we can just + // ignore binders here and scrape up all names we see. + let mut appears_in_where_clause = AllCollector::default(); + appears_in_where_clause.visit_generics(generics); + debug!(?appears_in_where_clause.regions); + + // Late bound regions are those that: + // - appear in the inputs + // - do not appear in the where-clauses + // - are not implicitly captured by `impl Trait` + for param in generics.params { + match param.kind { + hir::GenericParamKind::Lifetime { .. } => { /* fall through */ } + + // Neither types nor consts are late-bound. + hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue, + } + + // appears in the where clauses? early-bound. + if appears_in_where_clause.regions.contains(¶m.def_id) { + continue; + } + + // does not appear in the inputs, but appears in the return type? early-bound. + if !constrained_by_input.regions.contains(¶m.def_id) + && appears_in_output.regions.contains(¶m.def_id) + { + continue; + } + + debug!("lifetime {:?} with id {:?} is late-bound", param.name.ident(), param.def_id); + + let inserted = late_bound.insert(param.hir_id.local_id); + assert!(inserted, "visited lifetime {:?} twice", param.def_id); + } + + debug!(?late_bound); + return Some(tcx.arena.alloc(late_bound)); + + /// Visits a `ty::Ty` collecting information about what generic parameters are constrained. + /// + /// The visitor does not operate on `hir::Ty` so that it can be called on the rhs of a `type Alias<...> = ...;` + /// which may live in a separate crate so there would not be any hir available. Instead we use the `type_of` + /// query to obtain a `ty::Ty` which will be present even in cross crate scenarios. It also naturally + /// handles cycle detection as we go through the query system. + /// + /// This is necessary in the first place for the following case: + /// ``` + /// type Alias<'a, T> = >::Assoc; + /// fn foo<'a>(_: Alias<'a, ()>) -> Alias<'a, ()> { ... } + /// ``` + /// + /// If we conservatively considered `'a` unconstrained then we could break users who had written code before + /// we started correctly handling aliases. If we considered `'a` constrained then it would become late bound + /// causing an error during astconv as the `'a` is not constrained by the input type `<() as Trait<'a>>::Assoc` + /// but appears in the output type `<() as Trait<'a>>::Assoc`. + /// + /// We must therefore "look into" the `Alias` to see whether we should consider `'a` constrained or not. + /// + /// See #100508 #85533 #47511 for additional context + struct ConstrainedCollectorPostAstConv { + arg_is_constrained: Box<[bool]>, + } + + use std::ops::ControlFlow; + use ty::Ty; + impl<'tcx> TypeVisitor> for ConstrainedCollectorPostAstConv { + fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow { + match t.kind() { + ty::Param(param_ty) => { + self.arg_is_constrained[param_ty.index as usize] = true; + } + ty::Alias(ty::Projection, _) => return ControlFlow::Continue(()), + _ => (), + } + t.super_visit_with(self) + } + + fn visit_const(&mut self, _: ty::Const<'tcx>) -> ControlFlow { + ControlFlow::Continue(()) + } + + fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow { + debug!("r={:?}", r.kind()); + if let ty::RegionKind::ReEarlyBound(region) = r.kind() { + self.arg_is_constrained[region.index as usize] = true; + } + + ControlFlow::Continue(()) + } + } + + struct ConstrainedCollector<'tcx> { + tcx: TyCtxt<'tcx>, + regions: FxHashSet, + } + + impl<'v> Visitor<'v> for ConstrainedCollector<'_> { + fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) { + match ty.kind { + hir::TyKind::Path( + hir::QPath::Resolved(Some(_), _) | hir::QPath::TypeRelative(..), + ) => { + // ignore lifetimes appearing in associated type + // projections, as they are not *constrained* + // (defined above) + } + + hir::TyKind::Path(hir::QPath::Resolved( + None, + hir::Path { res: Res::Def(DefKind::TyAlias, alias_def), segments, span }, + )) => { + // See comments on `ConstrainedCollectorPostAstConv` for why this arm does not just consider + // substs to be unconstrained. + let generics = self.tcx.generics_of(alias_def); + let mut walker = ConstrainedCollectorPostAstConv { + arg_is_constrained: vec![false; generics.params.len()].into_boxed_slice(), + }; + walker.visit_ty(self.tcx.type_of(alias_def)); + + match segments.last() { + Some(hir::PathSegment { args: Some(args), .. }) => { + let tcx = self.tcx; + for constrained_arg in + args.args.iter().enumerate().flat_map(|(n, arg)| { + match walker.arg_is_constrained.get(n) { + Some(true) => Some(arg), + Some(false) => None, + None => { + tcx.sess.delay_span_bug( + *span, + format!( + "Incorrect generic arg count for alias {:?}", + alias_def + ), + ); + None + } + } + }) + { + self.visit_generic_arg(constrained_arg); + } + } + Some(_) => (), + None => bug!("Path with no segments or self type"), + } + } + + hir::TyKind::Path(hir::QPath::Resolved(None, path)) => { + // consider only the lifetimes on the final + // segment; I am not sure it's even currently + // valid to have them elsewhere, but even if it + // is, those would be potentially inputs to + // projections + if let Some(last_segment) = path.segments.last() { + self.visit_path_segment(last_segment); + } + } + + _ => { + intravisit::walk_ty(self, ty); + } + } + } + + fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) { + if let hir::LifetimeName::Param(def_id) = lifetime_ref.res { + self.regions.insert(def_id); + } + } + } + + #[derive(Default)] + struct AllCollector { + regions: FxHashSet, + } + + impl<'v> Visitor<'v> for AllCollector { + fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) { + if let hir::LifetimeName::Param(def_id) = lifetime_ref.res { + self.regions.insert(def_id); + } + } + } +} diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs index 39f4d502259..4fe6c6618f6 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs @@ -2,7 +2,7 @@ use rustc_hir as hir; use rustc_hir::intravisit::{self, Visitor}; use rustc_middle::hir::map::Map; use rustc_middle::hir::nested_filter; -use rustc_middle::middle::resolve_lifetime as rl; +use rustc_middle::middle::resolve_bound_vars as rbv; use rustc_middle::ty::{self, Region, TyCtxt}; /// This function calls the `visit_ty` method for the parameters @@ -99,11 +99,11 @@ impl<'tcx> Visitor<'tcx> for FindNestedTypeVisitor<'tcx> { hir::TyKind::Ref(ref lifetime, _) => { // the lifetime of the Ref let hir_id = lifetime.hir_id; - match (self.tcx.named_region(hir_id), self.bound_region) { + match (self.tcx.named_bound_var(hir_id), self.bound_region) { // Find the index of the named region that was part of the // error. We will then search the function parameters for a bound // region at the right depth with the same index - (Some(rl::Region::EarlyBound(id)), ty::BrNamed(def_id, _)) => { + (Some(rbv::ResolvedArg::EarlyBound(id)), ty::BrNamed(def_id, _)) => { debug!("EarlyBound id={:?} def_id={:?}", id, def_id); if id == def_id { self.found_type = Some(arg); @@ -115,7 +115,7 @@ impl<'tcx> Visitor<'tcx> for FindNestedTypeVisitor<'tcx> { // error. We will then search the function parameters for a bound // region at the right depth with the same index ( - Some(rl::Region::LateBound(debruijn_index, _, id)), + Some(rbv::ResolvedArg::LateBound(debruijn_index, _, id)), ty::BrNamed(def_id, _), ) => { debug!( @@ -131,10 +131,10 @@ impl<'tcx> Visitor<'tcx> for FindNestedTypeVisitor<'tcx> { ( Some( - rl::Region::Static - | rl::Region::Free(_, _) - | rl::Region::EarlyBound(_) - | rl::Region::LateBound(_, _, _), + rbv::ResolvedArg::StaticLifetime + | rbv::ResolvedArg::Free(_, _) + | rbv::ResolvedArg::EarlyBound(_) + | rbv::ResolvedArg::LateBound(_, _, _), ) | None, _, @@ -186,9 +186,9 @@ impl<'tcx> Visitor<'tcx> for TyPathVisitor<'tcx> { } fn visit_lifetime(&mut self, lifetime: &hir::Lifetime) { - match (self.tcx.named_region(lifetime.hir_id), self.bound_region) { + match (self.tcx.named_bound_var(lifetime.hir_id), self.bound_region) { // the lifetime of the TyPath! - (Some(rl::Region::EarlyBound(id)), ty::BrNamed(def_id, _)) => { + (Some(rbv::ResolvedArg::EarlyBound(id)), ty::BrNamed(def_id, _)) => { debug!("EarlyBound id={:?} def_id={:?}", id, def_id); if id == def_id { self.found_it = true; @@ -196,7 +196,7 @@ impl<'tcx> Visitor<'tcx> for TyPathVisitor<'tcx> { } } - (Some(rl::Region::LateBound(debruijn_index, _, id)), ty::BrNamed(def_id, _)) => { + (Some(rbv::ResolvedArg::LateBound(debruijn_index, _, id)), ty::BrNamed(def_id, _)) => { debug!("FindNestedTypeVisitor::visit_ty: LateBound depth = {:?}", debruijn_index,); debug!("id={:?}", id); debug!("def_id={:?}", def_id); @@ -208,10 +208,10 @@ impl<'tcx> Visitor<'tcx> for TyPathVisitor<'tcx> { ( Some( - rl::Region::Static - | rl::Region::EarlyBound(_) - | rl::Region::LateBound(_, _, _) - | rl::Region::Free(_, _), + rbv::ResolvedArg::StaticLifetime + | rbv::ResolvedArg::EarlyBound(_) + | rbv::ResolvedArg::LateBound(_, _, _) + | rbv::ResolvedArg::Free(_, _), ) | None, _, diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index f18c0aa377f..bf6a7128b1b 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -2007,7 +2007,7 @@ impl ExplicitOutlivesRequirements { inferred_outlives: &[ty::Region<'tcx>], predicate_span: Span, ) -> Vec<(usize, Span)> { - use rustc_middle::middle::resolve_lifetime::Region; + use rustc_middle::middle::resolve_bound_vars::ResolvedArg; bounds .iter() @@ -2017,8 +2017,8 @@ impl ExplicitOutlivesRequirements { return None; }; - let is_inferred = match tcx.named_region(lifetime.hir_id) { - Some(Region::EarlyBound(def_id)) => inferred_outlives + let is_inferred = match tcx.named_bound_var(lifetime.hir_id) { + Some(ResolvedArg::EarlyBound(def_id)) => inferred_outlives .iter() .any(|r| matches!(**r, ty::ReEarlyBound(ebr) if { ebr.def_id == def_id })), _ => false, @@ -2097,7 +2097,7 @@ impl ExplicitOutlivesRequirements { impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements { fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) { - use rustc_middle::middle::resolve_lifetime::Region; + use rustc_middle::middle::resolve_bound_vars::ResolvedArg; let def_id = item.owner_id.def_id; if let hir::ItemKind::Struct(_, hir_generics) @@ -2120,8 +2120,8 @@ impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements { let (relevant_lifetimes, bounds, predicate_span, in_where_clause) = match where_predicate { hir::WherePredicate::RegionPredicate(predicate) => { - if let Some(Region::EarlyBound(region_def_id)) = - cx.tcx.named_region(predicate.lifetime.hir_id) + if let Some(ResolvedArg::EarlyBound(region_def_id)) = + cx.tcx.named_bound_var(predicate.lifetime.hir_id) { ( Self::lifetimes_outliving_lifetime( diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index 9227609cc8b..a9fb8b246c6 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -18,7 +18,7 @@ use rustc_index::vec::IndexVec; use rustc_middle::metadata::ModChild; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo}; -use rustc_middle::middle::resolve_lifetime::ObjectLifetimeDefault; +use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault; use rustc_middle::mir; use rustc_middle::ty::fast_reject::SimplifiedType; use rustc_middle::ty::query::Providers; diff --git a/compiler/rustc_middle/src/middle/mod.rs b/compiler/rustc_middle/src/middle/mod.rs index 8dc68b1f5a8..0b6774f1b1f 100644 --- a/compiler/rustc_middle/src/middle/mod.rs +++ b/compiler/rustc_middle/src/middle/mod.rs @@ -29,7 +29,7 @@ pub mod lib_features { pub mod limits; pub mod privacy; pub mod region; -pub mod resolve_lifetime; +pub mod resolve_bound_vars; pub mod stability; pub fn provide(providers: &mut crate::ty::query::Providers) { diff --git a/compiler/rustc_middle/src/middle/resolve_bound_vars.rs b/compiler/rustc_middle/src/middle/resolve_bound_vars.rs new file mode 100644 index 00000000000..cd457696942 --- /dev/null +++ b/compiler/rustc_middle/src/middle/resolve_bound_vars.rs @@ -0,0 +1,55 @@ +//! Name resolution for lifetimes and late-bound type and const variables: type declarations. + +use crate::ty; + +use rustc_data_structures::fx::FxHashMap; +use rustc_hir::def_id::DefId; +use rustc_hir::{ItemLocalId, OwnerId}; +use rustc_macros::HashStable; + +#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, HashStable)] +pub enum ResolvedArg { + StaticLifetime, + EarlyBound(/* lifetime decl */ DefId), + LateBound(ty::DebruijnIndex, /* late-bound index */ u32, /* lifetime decl */ DefId), + Free(DefId, /* lifetime decl */ DefId), +} + +/// A set containing, at most, one known element. +/// If two distinct values are inserted into a set, then it +/// becomes `Many`, which can be used to detect ambiguities. +#[derive(Copy, Clone, PartialEq, Eq, TyEncodable, TyDecodable, Debug, HashStable)] +pub enum Set1 { + Empty, + One(T), + Many, +} + +impl Set1 { + pub fn insert(&mut self, value: T) { + *self = match self { + Set1::Empty => Set1::One(value), + Set1::One(old) if *old == value => return, + _ => Set1::Many, + }; + } +} + +#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)] +pub enum ObjectLifetimeDefault { + Empty, + Static, + Ambiguous, + Param(DefId), +} + +/// Maps the id of each lifetime reference to the lifetime decl +/// that it corresponds to. +#[derive(Default, HashStable, Debug)] +pub struct ResolveBoundVars { + /// Maps from every use of a named (not anonymous) lifetime to a + /// `Region` describing how that region is bound + pub defs: FxHashMap>, + + pub late_bound_vars: FxHashMap>>, +} diff --git a/compiler/rustc_middle/src/middle/resolve_lifetime.rs b/compiler/rustc_middle/src/middle/resolve_lifetime.rs deleted file mode 100644 index c3bf1c717d9..00000000000 --- a/compiler/rustc_middle/src/middle/resolve_lifetime.rs +++ /dev/null @@ -1,55 +0,0 @@ -//! Name resolution for lifetimes: type declarations. - -use crate::ty; - -use rustc_data_structures::fx::FxHashMap; -use rustc_hir::def_id::DefId; -use rustc_hir::{ItemLocalId, OwnerId}; -use rustc_macros::HashStable; - -#[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, HashStable)] -pub enum Region { - Static, - EarlyBound(/* lifetime decl */ DefId), - LateBound(ty::DebruijnIndex, /* late-bound index */ u32, /* lifetime decl */ DefId), - Free(DefId, /* lifetime decl */ DefId), -} - -/// A set containing, at most, one known element. -/// If two distinct values are inserted into a set, then it -/// becomes `Many`, which can be used to detect ambiguities. -#[derive(Copy, Clone, PartialEq, Eq, TyEncodable, TyDecodable, Debug, HashStable)] -pub enum Set1 { - Empty, - One(T), - Many, -} - -impl Set1 { - pub fn insert(&mut self, value: T) { - *self = match self { - Set1::Empty => Set1::One(value), - Set1::One(old) if *old == value => return, - _ => Set1::Many, - }; - } -} - -#[derive(Copy, Clone, Debug, HashStable, Encodable, Decodable)] -pub enum ObjectLifetimeDefault { - Empty, - Static, - Ambiguous, - Param(DefId), -} - -/// Maps the id of each lifetime reference to the lifetime decl -/// that it corresponds to. -#[derive(Default, HashStable, Debug)] -pub struct ResolveLifetimes { - /// Maps from every use of a named (not anonymous) lifetime to a - /// `Region` describing how that region is bound - pub defs: FxHashMap>, - - pub late_bound_vars: FxHashMap>>, -} diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 4b34f6b4881..c793676146d 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -1641,12 +1641,12 @@ rustc_queries! { /// Does lifetime resolution on items. Importantly, we can't resolve /// lifetimes directly on things like trait methods, because of trait params. /// See `rustc_resolve::late::lifetimes for details. - query resolve_lifetimes(_: hir::OwnerId) -> &'tcx ResolveLifetimes { + query resolve_bound_vars(_: hir::OwnerId) -> &'tcx ResolveBoundVars { arena_cache desc { "resolving lifetimes" } } - query named_region_map(_: hir::OwnerId) -> - Option<&'tcx FxHashMap> { + query named_variable_map(_: hir::OwnerId) -> + Option<&'tcx FxHashMap> { desc { "looking up a named region" } } query is_late_bound_map(_: hir::OwnerId) -> Option<&'tcx FxIndexSet> { diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 4aef071cd98..9c64454fbe6 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -9,7 +9,7 @@ use crate::dep_graph::{DepGraph, DepKindStruct}; use crate::infer::canonical::{CanonicalVarInfo, CanonicalVarInfos}; use crate::lint::struct_lint_level; use crate::middle::codegen_fn_attrs::CodegenFnAttrs; -use crate::middle::resolve_lifetime; +use crate::middle::resolve_bound_vars; use crate::middle::stability; use crate::mir::interpret::{self, Allocation, ConstAllocation}; use crate::mir::{ @@ -2278,9 +2278,9 @@ impl<'tcx> TyCtxt<'tcx> { Some(&*candidates) } - pub fn named_region(self, id: HirId) -> Option { + pub fn named_bound_var(self, id: HirId) -> Option { debug!(?id, "named_region"); - self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned()) + self.named_variable_map(id.owner).and_then(|map| map.get(&id.local_id).cloned()) } pub fn is_late_bound(self, id: HirId) -> bool { diff --git a/compiler/rustc_middle/src/ty/parameterized.rs b/compiler/rustc_middle/src/ty/parameterized.rs index 303675d3ca5..8849e7eab33 100644 --- a/compiler/rustc_middle/src/ty/parameterized.rs +++ b/compiler/rustc_middle/src/ty/parameterized.rs @@ -57,7 +57,7 @@ trivially_parameterized_over_tcx! { crate::metadata::ModChild, crate::middle::codegen_fn_attrs::CodegenFnAttrs, crate::middle::exported_symbols::SymbolExportInfo, - crate::middle::resolve_lifetime::ObjectLifetimeDefault, + crate::middle::resolve_bound_vars::ObjectLifetimeDefault, crate::mir::ConstQualifs, ty::AssocItemContainer, ty::DeducedParamAttrs, diff --git a/compiler/rustc_middle/src/ty/query.rs b/compiler/rustc_middle/src/ty/query.rs index ed54aa96f5b..f1128d7c8bb 100644 --- a/compiler/rustc_middle/src/ty/query.rs +++ b/compiler/rustc_middle/src/ty/query.rs @@ -6,7 +6,7 @@ use crate::middle::codegen_fn_attrs::CodegenFnAttrs; use crate::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo}; use crate::middle::lib_features::LibFeatures; use crate::middle::privacy::EffectiveVisibilities; -use crate::middle::resolve_lifetime::{ObjectLifetimeDefault, Region, ResolveLifetimes}; +use crate::middle::resolve_bound_vars::{ObjectLifetimeDefault, ResolveBoundVars, ResolvedArg}; use crate::middle::stability::{self, DeprecationEntry}; use crate::mir; use crate::mir::interpret::GlobalId; diff --git a/compiler/rustc_mir_transform/src/ssa.rs b/compiler/rustc_mir_transform/src/ssa.rs index bc3fe65cf6c..9e7d9873bed 100644 --- a/compiler/rustc_mir_transform/src/ssa.rs +++ b/compiler/rustc_mir_transform/src/ssa.rs @@ -2,7 +2,7 @@ use either::Either; use rustc_data_structures::graph::dominators::Dominators; use rustc_index::bit_set::BitSet; use rustc_index::vec::IndexVec; -use rustc_middle::middle::resolve_lifetime::Set1; +use rustc_middle::middle::resolve_bound_vars::Set1; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; use rustc_middle::ty::{ParamEnv, TyCtxt}; diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 225095948af..7cff8996d24 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -18,7 +18,7 @@ use rustc_hir::{ }; use rustc_hir::{MethodKind, Target, Unsafety}; use rustc_middle::hir::nested_filter; -use rustc_middle::middle::resolve_lifetime::ObjectLifetimeDefault; +use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault; use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams}; use rustc_middle::ty::query::Providers; use rustc_middle::ty::{ParamEnv, TyCtxt}; diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index d3bcbbabf55..844afb55f17 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -21,7 +21,7 @@ use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, PartialRes, PerNS}; use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE}; use rustc_hir::{BindingAnnotation, PrimTy, TraitCandidate}; -use rustc_middle::middle::resolve_lifetime::Set1; +use rustc_middle::middle::resolve_bound_vars::Set1; use rustc_middle::ty::DefIdTree; use rustc_middle::{bug, span_bug}; use rustc_session::config::{CrateType, ResolveDocLinks}; @@ -2505,7 +2505,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { let res = match kind { ItemRibKind(..) | AssocItemRibKind => Res::Def(def_kind, def_id.to_def_id()), - NormalRibKind => Res::Err, + NormalRibKind => Res::Err, /* FIXME(non_lifetime_binder): Resolve this to "late" */ _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind), }; self.r.record_partial_res(param.id, PartialRes::new(res)); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index bf3bbeb2dd1..1c01a9c6249 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -19,7 +19,7 @@ use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId, LOCAL_CRATE}; use rustc_hir::PredicateOrigin; use rustc_hir_analysis::hir_ty_to_ty; use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData}; -use rustc_middle::middle::resolve_lifetime as rl; +use rustc_middle::middle::resolve_bound_vars as rbv; use rustc_middle::ty::fold::ir::TypeFolder; use rustc_middle::ty::InternalSubsts; use rustc_middle::ty::TypeVisitable; @@ -198,11 +198,11 @@ fn clean_poly_trait_ref_with_bindings<'tcx>( } fn clean_lifetime<'tcx>(lifetime: &hir::Lifetime, cx: &mut DocContext<'tcx>) -> Lifetime { - let def = cx.tcx.named_region(lifetime.hir_id); + let def = cx.tcx.named_bound_var(lifetime.hir_id); if let Some( - rl::Region::EarlyBound(node_id) - | rl::Region::LateBound(_, _, node_id) - | rl::Region::Free(_, node_id), + rbv::ResolvedArg::EarlyBound(node_id) + | rbv::ResolvedArg::LateBound(_, _, node_id) + | rbv::ResolvedArg::Free(_, node_id), ) = def { if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() { diff --git a/src/tools/clippy/clippy_lints/src/ptr.rs b/src/tools/clippy/clippy_lints/src/ptr.rs index d88409c356e..fc550936165 100644 --- a/src/tools/clippy/clippy_lints/src/ptr.rs +++ b/src/tools/clippy/clippy_lints/src/ptr.rs @@ -505,13 +505,13 @@ fn check_mut_from_ref<'tcx>(cx: &LateContext<'tcx>, sig: &FnSig<'_>, body: Optio if let FnRetTy::Return(ty) = sig.decl.output && let Some((out, Mutability::Mut, _)) = get_ref_lm(ty) { - let out_region = cx.tcx.named_region(out.hir_id); + let out_region = cx.tcx.named_bound_var(out.hir_id); let args: Option> = sig .decl .inputs .iter() .filter_map(get_ref_lm) - .filter(|&(lt, _, _)| cx.tcx.named_region(lt.hir_id) == out_region) + .filter(|&(lt, _, _)| cx.tcx.named_bound_var(lt.hir_id) == out_region) .map(|(_, mutability, span)| (mutability == Mutability::Not).then_some(span)) .collect(); if let Some(args) = args -- cgit 1.4.1-3-g733a5 From 52f82354dc1dee723b0b1324dda7ddeabc332830 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 14 Dec 2022 23:53:05 +0000 Subject: Make things actually work --- compiler/rustc_hir_analysis/src/astconv/mod.rs | 27 ++- .../src/collect/resolve_bound_vars.rs | 203 ++++++++++++--------- compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs | 2 +- .../rustc_middle/src/middle/resolve_bound_vars.rs | 4 +- compiler/rustc_resolve/src/late.rs | 8 +- 5 files changed, 151 insertions(+), 93 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index 7690f44a23d..ae738177d76 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -2598,6 +2598,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { &self, opt_self_ty: Option>, path: &hir::Path<'_>, + hir_id: hir::HirId, permit_variants: bool, ) -> Ty<'tcx> { let tcx = self.tcx(); @@ -2661,11 +2662,25 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } }); - let def_id = def_id.expect_local(); - let item_def_id = tcx.hir().ty_param_owner(def_id); - let generics = tcx.generics_of(item_def_id); - let index = generics.param_def_id_to_index[&def_id.to_def_id()]; - tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id)) + match tcx.named_bound_var(hir_id) { + Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => { + let name = + tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local())); + let br = ty::BoundTy { + var: ty::BoundVar::from_u32(index), + kind: ty::BoundTyKind::Param(def_id, name), + }; + tcx.mk_ty(ty::Bound(debruijn, br)) + } + Some(rbv::ResolvedArg::EarlyBound(_)) => { + let def_id = def_id.expect_local(); + let item_def_id = tcx.hir().ty_param_owner(def_id); + let generics = tcx.generics_of(item_def_id); + let index = generics.param_def_id_to_index[&def_id.to_def_id()]; + tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id)) + } + arg => bug!("unexpected bound var resolution for {hir_id:?}: {arg:?}"), + } } Res::SelfTyParam { .. } => { // `Self` in trait or type alias. @@ -2888,7 +2903,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => { debug!(?maybe_qself, ?path); let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself)); - self.res_to_ty(opt_self_ty, path, false) + self.res_to_ty(opt_self_ty, path, ast_ty.hir_id, false) } &hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => { let opaque_ty = tcx.hir().item(item_id); diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index 0b570f21178..97d7556a41d 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -35,14 +35,14 @@ trait RegionExt { impl RegionExt for ResolvedArg { fn early(param: &GenericParam<'_>) -> (LocalDefId, ResolvedArg) { - debug!("Region::early: def_id={:?}", param.def_id); + debug!("ResolvedArg::early: def_id={:?}", param.def_id); (param.def_id, ResolvedArg::EarlyBound(param.def_id.to_def_id())) } fn late(idx: u32, param: &GenericParam<'_>) -> (LocalDefId, ResolvedArg) { let depth = ty::INNERMOST; debug!( - "Region::late: idx={:?}, param={:?} depth={:?} def_id={:?}", + "ResolvedArg::late: idx={:?}, param={:?} depth={:?} def_id={:?}", idx, param, depth, param.def_id, ); (param.def_id, ResolvedArg::LateBound(depth, idx, param.def_id.to_def_id())) @@ -278,13 +278,25 @@ fn resolve_bound_vars(tcx: TyCtxt<'_>, local_def_id: hir::OwnerId) -> ResolveBou rl } -fn late_region_as_bound_region(tcx: TyCtxt<'_>, region: &ResolvedArg) -> ty::BoundVariableKind { - match region { +fn late_arg_as_bound_arg<'tcx>( + tcx: TyCtxt<'tcx>, + arg: &ResolvedArg, + param: &GenericParam<'tcx>, +) -> ty::BoundVariableKind { + match arg { ResolvedArg::LateBound(_, _, def_id) => { let name = tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id.expect_local())); - ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name)) + match param.kind { + GenericParamKind::Lifetime { .. } => { + ty::BoundVariableKind::Region(ty::BrNamed(*def_id, name)) + } + GenericParamKind::Type { .. } => { + ty::BoundVariableKind::Ty(ty::BoundTyKind::Param(*def_id, name)) + } + GenericParamKind::Const { .. } => ty::BoundVariableKind::Const, + } } - _ => bug!("{:?} is not a late argument", region), + _ => bug!("{:?} is not a late argument", arg), } } @@ -391,11 +403,10 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { let (bound_vars, binders): (FxIndexMap, Vec<_>) = bound_generic_params .iter() - .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) .enumerate() .map(|(late_bound_idx, param)| { let pair = ResolvedArg::late(late_bound_idx as u32, param); - let r = late_region_as_bound_region(self.tcx, &pair.1); + let r = late_arg_as_bound_arg(self.tcx, &pair.1, param); (pair, r) }) .unzip(); @@ -481,7 +492,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { } } hir::ItemKind::OpaqueTy(hir::OpaqueTy { - origin: hir::OpaqueTyOrigin::FnReturn(_) | hir::OpaqueTyOrigin::AsyncFn(_), + origin: hir::OpaqueTyOrigin::FnReturn(parent) | hir::OpaqueTyOrigin::AsyncFn(parent), generics, .. }) => { @@ -490,26 +501,24 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { let mut bound_vars = FxIndexMap::default(); debug!(?generics.params); for param in generics.params { - match param.kind { - GenericParamKind::Lifetime { .. } => { - let (def_id, reg) = ResolvedArg::early(¶m); - bound_vars.insert(def_id, reg); - } - GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {} - } + let (def_id, reg) = ResolvedArg::early(¶m); + bound_vars.insert(def_id, reg); } - let scope = Scope::Binder { - hir_id: item.hir_id(), - bound_vars, - s: self.scope, - scope_type: BinderScopeType::Normal, - where_bound_origin: None, - }; + let scope = Scope::Root { opt_parent_item: Some(parent) }; self.with(scope, |this| { - let scope = Scope::TraitRefBoundary { s: this.scope }; - this.with(scope, |this| intravisit::walk_item(this, item)) - }); + let scope = Scope::Binder { + hir_id: item.hir_id(), + bound_vars, + s: this.scope, + scope_type: BinderScopeType::Normal, + where_bound_origin: None, + }; + this.with(scope, |this| { + let scope = Scope::TraitRefBoundary { s: this.scope }; + this.with(scope, |this| intravisit::walk_item(this, item)) + }); + }) } hir::ItemKind::TyAlias(_, generics) | hir::ItemKind::Enum(_, generics) @@ -519,14 +528,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { | hir::ItemKind::TraitAlias(generics, ..) | hir::ItemKind::Impl(&hir::Impl { generics, .. }) => { // These kinds of items have only early-bound lifetime parameters. - let bound_vars = generics - .params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => Some(ResolvedArg::early(param)), - GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => None, - }) - .collect(); + let bound_vars = generics.params.iter().map(ResolvedArg::early).collect(); self.record_late_bound_vars(item.hir_id(), vec![]); let scope = Scope::Binder { hir_id: item.hir_id(), @@ -568,11 +570,10 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { let (bound_vars, binders): (FxIndexMap, Vec<_>) = c .generic_params .iter() - .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) .enumerate() .map(|(late_bound_idx, param)| { let pair = ResolvedArg::late(late_bound_idx as u32, param); - let r = late_region_as_bound_region(self.tcx, &pair.1); + let r = late_arg_as_bound_arg(self.tcx, &pair.1, param); (pair, r) }) .unzip(); @@ -725,14 +726,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { } Type(bounds, ty) => { let generics = &trait_item.generics; - let bound_vars = generics - .params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => Some(ResolvedArg::early(param)), - GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => None, - }) - .collect(); + let bound_vars = generics.params.iter().map(ResolvedArg::early).collect(); self.record_late_bound_vars(trait_item.hir_id(), vec![]); let scope = Scope::Binder { hir_id: trait_item.hir_id(), @@ -771,14 +765,8 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { }), Type(ty) => { let generics = &impl_item.generics; - let bound_vars: FxIndexMap = generics - .params - .iter() - .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => Some(ResolvedArg::early(param)), - GenericParamKind::Const { .. } | GenericParamKind::Type { .. } => None, - }) - .collect(); + let bound_vars: FxIndexMap = + generics.params.iter().map(ResolvedArg::early).collect(); self.record_late_bound_vars(impl_item.hir_id(), vec![]); let scope = Scope::Binder { hir_id: impl_item.hir_id(), @@ -819,13 +807,16 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { } } - fn visit_path(&mut self, path: &hir::Path<'tcx>, _: hir::HirId) { + fn visit_path(&mut self, path: &hir::Path<'tcx>, hir_id: hir::HirId) { for (i, segment) in path.segments.iter().enumerate() { let depth = path.segments.len() - i - 1; if let Some(args) = segment.args { self.visit_segment_args(path.res, depth, args); } } + if let Res::Def(DefKind::TyParam | DefKind::ConstParam, param_def_id) = path.res { + self.resolve_type_ref(param_def_id.expect_local(), hir_id); + } } fn visit_fn( @@ -874,24 +865,17 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { origin, .. }) => { - let bound_vars: FxIndexMap = + + let (bound_vars, binders): (FxIndexMap, Vec<_>) = bound_generic_params - .iter() - .filter(|param| { - matches!(param.kind, GenericParamKind::Lifetime { .. }) - }) - .enumerate() - .map(|(late_bound_idx, param)| { - ResolvedArg::late(late_bound_idx as u32, param) - }) - .collect(); - let binders: Vec<_> = - bound_vars - .iter() - .map(|(_, region)| { - late_region_as_bound_region(this.tcx, region) - }) - .collect(); + .iter() + .enumerate() + .map(|(late_bound_idx, param)| { + let pair = ResolvedArg::late(late_bound_idx as u32, param); + let r = late_arg_as_bound_arg(this.tcx, &pair.1, param); + (pair, r) + }) + .unzip(); this.record_late_bound_vars(hir_id, binders.clone()); // Even if there are no lifetimes defined here, we still wrap it in a binder // scope. If there happens to be a nested poly trait ref (an error), that @@ -989,14 +973,10 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { let initial_bound_vars = binders.len() as u32; let mut bound_vars: FxIndexMap = FxIndexMap::default(); - let binders_iter = trait_ref - .bound_generic_params - .iter() - .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. })) - .enumerate() - .map(|(late_bound_idx, param)| { + let binders_iter = + trait_ref.bound_generic_params.iter().enumerate().map(|(late_bound_idx, param)| { let pair = ResolvedArg::late(initial_bound_vars + late_bound_idx as u32, param); - let r = late_region_as_bound_region(self.tcx, &pair.1); + let r = late_arg_as_bound_arg(self.tcx, &pair.1, param); bound_vars.insert(pair.0, pair.1); r }); @@ -1121,17 +1101,19 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { let bound_vars: FxIndexMap = generics .params .iter() - .filter_map(|param| match param.kind { + .map(|param| match param.kind { GenericParamKind::Lifetime { .. } => { if self.tcx.is_late_bound(param.hir_id) { let late_bound_idx = named_late_bound_vars; named_late_bound_vars += 1; - Some(ResolvedArg::late(late_bound_idx, param)) + ResolvedArg::late(late_bound_idx, param) } else { - Some(ResolvedArg::early(param)) + ResolvedArg::early(param) } } - GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => None, + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { + ResolvedArg::early(param) + } }) .collect(); @@ -1145,7 +1127,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { .enumerate() .map(|(late_bound_idx, param)| { let pair = ResolvedArg::late(late_bound_idx as u32, param); - late_region_as_bound_region(self.tcx, &pair.1) + late_arg_as_bound_arg(self.tcx, &pair.1, param) }) .collect(); self.record_late_bound_vars(hir_id, binders); @@ -1182,7 +1164,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { Scope::Root { opt_parent_item } => { if let Some(parent_item) = opt_parent_item && let parent_generics = self.tcx.generics_of(parent_item) - && parent_generics.param_def_id_to_index.contains_key(®ion_def_id.to_def_id()) + && parent_generics.param_def_id_to_index(self.tcx, region_def_id.to_def_id()).is_some() { break Some(ResolvedArg::EarlyBound(region_def_id.to_def_id())); } @@ -1334,6 +1316,61 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { ); } + fn resolve_type_ref(&mut self, param_def_id: LocalDefId, hir_id: hir::HirId) { + // Walk up the scope chain, tracking the number of fn scopes + // that we pass through, until we find a lifetime with the + // given name or we run out of scopes. + // search. + let mut late_depth = 0; + let mut scope = self.scope; + let result = loop { + match *scope { + Scope::Body { s, .. } => { + scope = s; + } + + Scope::Root { opt_parent_item } => { + if let Some(parent_item) = opt_parent_item + && let parent_generics = self.tcx.generics_of(parent_item) + && parent_generics.param_def_id_to_index(self.tcx, param_def_id.to_def_id()).is_some() + { + break Some(ResolvedArg::EarlyBound(param_def_id.to_def_id())); + } + break None; + } + + Scope::Binder { ref bound_vars, scope_type, s, .. } => { + if let Some(&def) = bound_vars.get(¶m_def_id) { + break Some(def.shifted(late_depth)); + } + match scope_type { + BinderScopeType::Normal => late_depth += 1, + BinderScopeType::Concatenating => {} + } + scope = s; + } + + Scope::Elision { s, .. } + | Scope::ObjectLifetimeDefault { s, .. } + | Scope::Supertrait { s, .. } + | Scope::TraitRefBoundary { s, .. } => { + scope = s; + } + } + }; + + if let Some(def) = result { + self.map.defs.insert(hir_id, def); + return; + } + + span_bug!( + self.tcx.hir().span(hir_id), + "could not resolve {param_def_id:?}, scopes: {:#?}", + self.scope + ); + } + #[instrument(level = "debug", skip(self))] fn visit_segment_args( &mut self, diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 9c7a84ce198..74f40d97f2b 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -1669,7 +1669,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match *qpath { QPath::Resolved(ref maybe_qself, ref path) => { let self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself).raw); - let ty = self.astconv().res_to_ty(self_ty, path, true); + let ty = self.astconv().res_to_ty(self_ty, path, hir_id, true); (path.res, self.handle_raw_ty(path_span, ty)) } QPath::TypeRelative(ref qself, ref segment) => { diff --git a/compiler/rustc_middle/src/middle/resolve_bound_vars.rs b/compiler/rustc_middle/src/middle/resolve_bound_vars.rs index cd457696942..b96d07e7dc8 100644 --- a/compiler/rustc_middle/src/middle/resolve_bound_vars.rs +++ b/compiler/rustc_middle/src/middle/resolve_bound_vars.rs @@ -10,8 +10,8 @@ use rustc_macros::HashStable; #[derive(Clone, Copy, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, HashStable)] pub enum ResolvedArg { StaticLifetime, - EarlyBound(/* lifetime decl */ DefId), - LateBound(ty::DebruijnIndex, /* late-bound index */ u32, /* lifetime decl */ DefId), + EarlyBound(/* decl */ DefId), + LateBound(ty::DebruijnIndex, /* late-bound index */ u32, /* decl */ DefId), Free(DefId, /* lifetime decl */ DefId), } diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 844afb55f17..324de7461cd 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -2505,7 +2505,13 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { let res = match kind { ItemRibKind(..) | AssocItemRibKind => Res::Def(def_kind, def_id.to_def_id()), - NormalRibKind => Res::Err, /* FIXME(non_lifetime_binder): Resolve this to "late" */ + NormalRibKind => { + if self.r.session.features_untracked().non_lifetime_binders { + Res::Def(def_kind, def_id.to_def_id()) + } else { + Res::Err + } + } _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind), }; self.r.record_partial_res(param.id, PartialRes::new(res)); -- cgit 1.4.1-3-g733a5 From 3f521b3542458d177aa1723cafdb70fc8179682b Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 6 Feb 2023 20:13:42 +0000 Subject: Be better about bound vars --- compiler/rustc_middle/src/ty/fast_reject.rs | 4 ++-- .../src/traits/error_reporting/on_unimplemented.rs | 2 +- .../src/traits/error_reporting/suggestions.rs | 2 +- .../src/traits/select/candidate_assembly.rs | 9 ++++++++- 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_middle/src/ty/fast_reject.rs b/compiler/rustc_middle/src/ty/fast_reject.rs index 9afa37e9ef3..106ce9990e1 100644 --- a/compiler/rustc_middle/src/ty/fast_reject.rs +++ b/compiler/rustc_middle/src/ty/fast_reject.rs @@ -290,7 +290,7 @@ impl DeepRejectCtxt { // Impls cannot contain these types as these cannot be named directly. ty::FnDef(..) | ty::Closure(..) | ty::Generator(..) => false, - ty::Placeholder(..) => false, + ty::Placeholder(..) | ty::Bound(..) => false, // Depending on the value of `treat_obligation_params`, we either // treat generic parameters like placeholders or like inference variables. @@ -310,7 +310,7 @@ impl DeepRejectCtxt { ty::Error(_) => true, - ty::GeneratorWitness(..) | ty::GeneratorWitnessMIR(..) | ty::Bound(..) => { + ty::GeneratorWitness(..) | ty::GeneratorWitnessMIR(..) => { bug!("unexpected obligation type: {:?}", obligation_ty) } } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs index a3209d35e58..a8d9e79434c 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs @@ -60,7 +60,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ) -> Option<(DefId, SubstsRef<'tcx>)> { let tcx = self.tcx; let param_env = obligation.param_env; - let trait_ref = tcx.erase_late_bound_regions(trait_ref); + let trait_ref = self.instantiate_binder_with_placeholders(trait_ref); let trait_self_ty = trait_ref.self_ty(); let mut self_match_impls = vec![]; diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 0a1dfa7925b..ecfd45afc2d 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -1060,7 +1060,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> bool { let self_ty = self.resolve_vars_if_possible(trait_pred.self_ty()); - let ty = self.tcx.erase_late_bound_regions(self_ty); + let ty = self.instantiate_binder_with_placeholders(self_ty); let Some(generics) = self.tcx.hir().get_generics(obligation.cause.body_id) else { return false }; let ty::Ref(_, inner_ty, hir::Mutability::Not) = ty.kind() else { return false }; let ty::Param(param) = inner_ty.kind() else { return false }; diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index e9f7c3bc4cc..dae602908a3 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -396,7 +396,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // still be provided by a manual implementation for // this trait and type. } - ty::Param(..) | ty::Alias(ty::Projection, ..) => { + ty::Param(..) + | ty::Alias(ty::Projection, ..) + | ty::Placeholder(..) + | ty::Bound(..) => { // In these cases, we don't know what the actual // type is. Therefore, we cannot break it down // into its constituent types. So we don't @@ -448,6 +451,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ); self.infcx.probe(|_snapshot| { + if obligation.has_non_region_late_bound() { + return; + } + // The code below doesn't care about regions, and the // self-ty here doesn't escape this probe, so just erase // any LBR. -- cgit 1.4.1-3-g733a5 From 915703ca7a98439061f8e1514c3c4d026a15ad98 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 6 Feb 2023 22:02:10 +0000 Subject: A bit more work on late-bound consts --- .../src/collect/resolve_bound_vars.rs | 6 +---- compiler/rustc_middle/src/ty/consts.rs | 31 +++++++++++++++------- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index 97d7556a41d..8c388040fbf 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -1364,11 +1364,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { return; } - span_bug!( - self.tcx.hir().span(hir_id), - "could not resolve {param_def_id:?}, scopes: {:#?}", - self.scope - ); + span_bug!(self.tcx.hir().span(hir_id), "could not resolve {param_def_id:?}",); } #[instrument(level = "debug", skip(self))] diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index 3ad56e8f273..79807df706e 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -1,7 +1,9 @@ +use crate::middle::resolve_bound_vars as rbv; use crate::mir::interpret::LitToConstInput; use crate::ty::{self, DefIdTree, InternalSubsts, ParamEnv, ParamEnvAnd, Ty, TyCtxt}; use rustc_data_structures::intern::Interned; use rustc_hir as hir; +use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_macros::HashStable; use std::fmt; @@ -125,16 +127,27 @@ impl<'tcx> Const<'tcx> { } } - use hir::{def::DefKind::ConstParam, def::Res, ExprKind, Path, QPath}; match expr.kind { - ExprKind::Path(QPath::Resolved(_, &Path { res: Res::Def(ConstParam, def_id), .. })) => { - // Find the name and index of the const parameter by indexing the generics of - // the parent item and construct a `ParamConst`. - let item_def_id = tcx.parent(def_id); - let generics = tcx.generics_of(item_def_id); - let index = generics.param_def_id_to_index[&def_id]; - let name = tcx.item_name(def_id); - Some(tcx.mk_const(ty::ParamConst::new(index, name), ty)) + hir::ExprKind::Path(hir::QPath::Resolved( + _, + &hir::Path { res: Res::Def(DefKind::ConstParam, def_id), .. }, + )) => { + match tcx.named_bound_var(expr.hir_id) { + Some(rbv::ResolvedArg::EarlyBound(_)) => { + // Find the name and index of the const parameter by indexing the generics of + // the parent item and construct a `ParamConst`. + let item_def_id = tcx.parent(def_id); + let generics = tcx.generics_of(item_def_id); + let index = generics.param_def_id_to_index[&def_id]; + let name = tcx.item_name(def_id); + Some(tcx.mk_const(ty::ParamConst::new(index, name), ty)) + } + Some(rbv::ResolvedArg::LateBound(debruijn, index, _)) => Some(tcx.mk_const( + ty::ConstKind::Bound(debruijn, ty::BoundVar::from_u32(index)), + ty, + )), + arg => bug!("unexpected bound var resolution for {:?}: {arg:?}", expr.hir_id), + } } _ => None, } -- cgit 1.4.1-3-g733a5 From 95f35fe443afd8a0437390973fbd206db9fd7fd4 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 6 Feb 2023 23:53:24 +0000 Subject: Deny some late-bound ty/ct in some positions, add tests --- compiler/rustc_hir_analysis/src/astconv/mod.rs | 50 ++++++++++++++++++++-- compiler/rustc_privacy/src/lib.rs | 3 +- tests/ui/traits/non_lifetime_binders/basic.rs | 19 ++++++++ tests/ui/traits/non_lifetime_binders/basic.stderr | 11 +++++ tests/ui/traits/non_lifetime_binders/fail.rs | 23 ++++++++++ tests/ui/traits/non_lifetime_binders/fail.stderr | 43 +++++++++++++++++++ tests/ui/traits/non_lifetime_binders/on-dyn.rs | 13 ++++++ tests/ui/traits/non_lifetime_binders/on-dyn.stderr | 17 ++++++++ tests/ui/traits/non_lifetime_binders/on-ptr.rs | 13 ++++++ tests/ui/traits/non_lifetime_binders/on-ptr.stderr | 17 ++++++++ 10 files changed, 205 insertions(+), 4 deletions(-) create mode 100644 tests/ui/traits/non_lifetime_binders/basic.rs create mode 100644 tests/ui/traits/non_lifetime_binders/basic.stderr create mode 100644 tests/ui/traits/non_lifetime_binders/fail.rs create mode 100644 tests/ui/traits/non_lifetime_binders/fail.stderr create mode 100644 tests/ui/traits/non_lifetime_binders/on-dyn.rs create mode 100644 tests/ui/traits/non_lifetime_binders/on-dyn.stderr create mode 100644 tests/ui/traits/non_lifetime_binders/on-ptr.rs create mode 100644 tests/ui/traits/non_lifetime_binders/on-ptr.stderr diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index ae738177d76..b3f6649a5ae 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -2883,14 +2883,22 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { hir::TyKind::BareFn(bf) => { require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span); - tcx.mk_fn_ptr(self.ty_of_fn( + let fn_ptr_ty = tcx.mk_fn_ptr(self.ty_of_fn( ast_ty.hir_id, bf.unsafety, bf.abi, bf.decl, None, Some(ast_ty), - )) + )); + + if let Some(guar) = + deny_non_region_late_bound(tcx, bf.generic_params, "function pointer") + { + tcx.ty_error_with_guaranteed(guar) + } else { + fn_ptr_ty + } } hir::TyKind::TraitObject(bounds, lifetime, repr) => { self.maybe_lint_bare_trait(ast_ty, in_path); @@ -2898,7 +2906,22 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { TraitObjectSyntax::Dyn | TraitObjectSyntax::None => ty::Dyn, TraitObjectSyntax::DynStar => ty::DynStar, }; - self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed, repr) + + let object_ty = self.conv_object_ty_poly_trait_ref( + ast_ty.span, + bounds, + lifetime, + borrowed, + repr, + ); + + if let Some(guar) = bounds.iter().find_map(|trait_ref| { + deny_non_region_late_bound(tcx, trait_ref.bound_generic_params, "trait object") + }) { + tcx.ty_error_with_guaranteed(guar) + } else { + object_ty + } } hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => { debug!(?maybe_qself, ?path); @@ -3359,3 +3382,24 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { } } } + +fn deny_non_region_late_bound( + tcx: TyCtxt<'_>, + params: &[hir::GenericParam<'_>], + where_: &str, +) -> Option { + params.iter().find_map(|bad_param| { + let what = match bad_param.kind { + hir::GenericParamKind::Type { .. } => "type", + hir::GenericParamKind::Const { .. } => "const", + hir::GenericParamKind::Lifetime { .. } => return None, + }; + + let mut diag = tcx.sess.struct_span_err( + bad_param.span, + format!("late-bound {what} parameter not allowed on {where_} types"), + ); + + Some(if tcx.features().non_lifetime_binders { diag.emit() } else { diag.delay_as_bug() }) + }) +} diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 4675bd79c46..0a0c94e1dfb 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -270,10 +270,11 @@ where | ty::Ref(..) | ty::FnPtr(..) | ty::Param(..) + | ty::Bound(..) | ty::Error(_) | ty::GeneratorWitness(..) | ty::GeneratorWitnessMIR(..) => {} - ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => { + ty::Placeholder(..) | ty::Infer(..) => { bug!("unexpected type: {:?}", ty) } } diff --git a/tests/ui/traits/non_lifetime_binders/basic.rs b/tests/ui/traits/non_lifetime_binders/basic.rs new file mode 100644 index 00000000000..a797aae65db --- /dev/null +++ b/tests/ui/traits/non_lifetime_binders/basic.rs @@ -0,0 +1,19 @@ +// check-pass +// Basic test that show's we can succesfully typeck a `for` where clause. + +#![feature(non_lifetime_binders)] +//~^ WARN the feature `non_lifetime_binders` is incomplete + +trait Trait {} + +impl Trait for T {} + +fn foo() +where + for T: Trait, +{ +} + +fn main() { + foo(); +} diff --git a/tests/ui/traits/non_lifetime_binders/basic.stderr b/tests/ui/traits/non_lifetime_binders/basic.stderr new file mode 100644 index 00000000000..fddc5d9fc25 --- /dev/null +++ b/tests/ui/traits/non_lifetime_binders/basic.stderr @@ -0,0 +1,11 @@ +warning: the feature `non_lifetime_binders` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/basic.rs:4:12 + | +LL | #![feature(non_lifetime_binders)] + | ^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #1 for more information + = note: `#[warn(incomplete_features)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/traits/non_lifetime_binders/fail.rs b/tests/ui/traits/non_lifetime_binders/fail.rs new file mode 100644 index 00000000000..460f68907e8 --- /dev/null +++ b/tests/ui/traits/non_lifetime_binders/fail.rs @@ -0,0 +1,23 @@ +// Error reporting for where `for T: Trait` doesn't hold + +#![feature(non_lifetime_binders)] +//~^ WARN the feature `non_lifetime_binders` is incomplete + +trait Trait {} + +fn fail() +where + for T: Trait, +{} + +fn auto_trait() +where + for T: Send, +{} + +fn main() { + fail(); + //~^ ERROR the trait bound `T: Trait` is not satisfied + auto_trait(); + //~^ ERROR `T` cannot be sent between threads safely +} diff --git a/tests/ui/traits/non_lifetime_binders/fail.stderr b/tests/ui/traits/non_lifetime_binders/fail.stderr new file mode 100644 index 00000000000..ba5953193a4 --- /dev/null +++ b/tests/ui/traits/non_lifetime_binders/fail.stderr @@ -0,0 +1,43 @@ +warning: the feature `non_lifetime_binders` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/fail.rs:3:12 + | +LL | #![feature(non_lifetime_binders)] + | ^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #1 for more information + = note: `#[warn(incomplete_features)]` on by default + +error[E0277]: the trait bound `T: Trait` is not satisfied + --> $DIR/fail.rs:19:5 + | +LL | fail(); + | ^^^^ the trait `Trait` is not implemented for `T` + | +note: required by a bound in `fail` + --> $DIR/fail.rs:10:15 + | +LL | fn fail() + | ---- required by a bound in this +LL | where +LL | for T: Trait, + | ^^^^^ required by this bound in `fail` + +error[E0277]: `T` cannot be sent between threads safely + --> $DIR/fail.rs:21:5 + | +LL | auto_trait(); + | ^^^^^^^^^^ `T` cannot be sent between threads safely + | + = help: the trait `Send` is not implemented for `T` +note: required by a bound in `auto_trait` + --> $DIR/fail.rs:15:15 + | +LL | fn auto_trait() + | ---------- required by a bound in this +LL | where +LL | for T: Send, + | ^^^^ required by this bound in `auto_trait` + +error: aborting due to 2 previous errors; 1 warning emitted + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/traits/non_lifetime_binders/on-dyn.rs b/tests/ui/traits/non_lifetime_binders/on-dyn.rs new file mode 100644 index 00000000000..8fb7dd27605 --- /dev/null +++ b/tests/ui/traits/non_lifetime_binders/on-dyn.rs @@ -0,0 +1,13 @@ +// Tests to make sure that we reject polymorphic dyn trait. + +#![feature(non_lifetime_binders)] +//~^ WARN the feature `non_lifetime_binders` is incomplete + +trait Test {} + +fn foo() -> &'static dyn for Test { + //~^ ERROR late-bound type parameter not allowed on trait object types + todo!() +} + +fn main() {} diff --git a/tests/ui/traits/non_lifetime_binders/on-dyn.stderr b/tests/ui/traits/non_lifetime_binders/on-dyn.stderr new file mode 100644 index 00000000000..44071107de4 --- /dev/null +++ b/tests/ui/traits/non_lifetime_binders/on-dyn.stderr @@ -0,0 +1,17 @@ +warning: the feature `non_lifetime_binders` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/on-dyn.rs:3:12 + | +LL | #![feature(non_lifetime_binders)] + | ^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #1 for more information + = note: `#[warn(incomplete_features)]` on by default + +error: late-bound type parameter not allowed on trait object types + --> $DIR/on-dyn.rs:8:30 + | +LL | fn foo() -> &'static dyn for Test { + | ^ + +error: aborting due to previous error; 1 warning emitted + diff --git a/tests/ui/traits/non_lifetime_binders/on-ptr.rs b/tests/ui/traits/non_lifetime_binders/on-ptr.rs new file mode 100644 index 00000000000..0aaff52b6d8 --- /dev/null +++ b/tests/ui/traits/non_lifetime_binders/on-ptr.rs @@ -0,0 +1,13 @@ +// Tests to make sure that we reject polymorphic fn ptrs. + +#![feature(non_lifetime_binders)] +//~^ WARN the feature `non_lifetime_binders` is incomplete + +fn foo() -> for fn(T) { + //~^ ERROR late-bound type parameter not allowed on function pointer types + todo!() +} + +fn main() { + foo()(1i32); +} diff --git a/tests/ui/traits/non_lifetime_binders/on-ptr.stderr b/tests/ui/traits/non_lifetime_binders/on-ptr.stderr new file mode 100644 index 00000000000..bb7dccaf07d --- /dev/null +++ b/tests/ui/traits/non_lifetime_binders/on-ptr.stderr @@ -0,0 +1,17 @@ +warning: the feature `non_lifetime_binders` is incomplete and may not be safe to use and/or cause compiler crashes + --> $DIR/on-ptr.rs:3:12 + | +LL | #![feature(non_lifetime_binders)] + | ^^^^^^^^^^^^^^^^^^^^ + | + = note: see issue #1 for more information + = note: `#[warn(incomplete_features)]` on by default + +error: late-bound type parameter not allowed on function pointer types + --> $DIR/on-ptr.rs:6:17 + | +LL | fn foo() -> for fn(T) { + | ^ + +error: aborting due to previous error; 1 warning emitted + -- cgit 1.4.1-3-g733a5 From d75e43c37137c1df80d5fee19eee19803918bd44 Mon Sep 17 00:00:00 2001 From: Caio Date: Thu, 16 Feb 2023 11:42:35 -0300 Subject: Move tests --- src/tools/tidy/src/ui_tests.rs | 2 +- tests/ui/associated-types/issue-38821.rs | 33 +++++ tests/ui/associated-types/issue-38821.stderr | 22 +++ tests/ui/borrowck/issue-83924.fixed | 20 +++ tests/ui/borrowck/issue-83924.rs | 20 +++ tests/ui/borrowck/issue-83924.stderr | 22 +++ tests/ui/consts/issue-33903.rs | 10 ++ tests/ui/consts/issue-54582.rs | 16 ++ tests/ui/drop/issue-2735-2.rs | 27 ++++ tests/ui/drop/issue-2735-3.rs | 27 ++++ tests/ui/drop/issue-2735.rs | 22 +++ tests/ui/fmt/issue-75307.rs | 3 + tests/ui/fmt/issue-75307.stderr | 8 + tests/ui/higher-rank-trait-bounds/issue-39292.rs | 17 +++ tests/ui/issues/issue-22536-copy-mustnt-zero.rs | 28 ---- tests/ui/issues/issue-2735-2.rs | 27 ---- tests/ui/issues/issue-2735-3.rs | 27 ---- tests/ui/issues/issue-2735.rs | 22 --- tests/ui/issues/issue-27583.rs | 47 ------ tests/ui/issues/issue-33903.rs | 10 -- tests/ui/issues/issue-38821.rs | 33 ----- tests/ui/issues/issue-38821.stderr | 22 --- tests/ui/issues/issue-39292.rs | 17 --- tests/ui/issues/issue-40003.rs | 178 ----------------------- tests/ui/issues/issue-48179.rs | 38 ----- tests/ui/issues/issue-50576.rs | 6 - tests/ui/issues/issue-50576.stderr | 22 --- tests/ui/issues/issue-53712.rs | 9 -- tests/ui/issues/issue-53712.stderr | 11 -- tests/ui/issues/issue-54582.rs | 16 -- tests/ui/issues/issue-75307.rs | 3 - tests/ui/issues/issue-75307.stderr | 8 - tests/ui/issues/issue-75777.rs | 15 -- tests/ui/issues/issue-75777.stderr | 11 -- tests/ui/issues/issue-7813.rs | 4 - tests/ui/issues/issue-7813.stderr | 14 -- tests/ui/issues/issue-83924.fixed | 20 --- tests/ui/issues/issue-83924.rs | 20 --- tests/ui/issues/issue-83924.stderr | 22 --- tests/ui/loops/issue-50576.rs | 6 + tests/ui/loops/issue-50576.stderr | 22 +++ tests/ui/moves/issue-22536-copy-mustnt-zero.rs | 28 ++++ tests/ui/nll/issue-27583.rs | 47 ++++++ tests/ui/nll/issue-48179.rs | 38 +++++ tests/ui/nll/issue-75777.rs | 15 ++ tests/ui/nll/issue-75777.stderr | 11 ++ tests/ui/recursion_limit/issue-40003.rs | 178 +++++++++++++++++++++++ tests/ui/typeck/issue-53712.rs | 9 ++ tests/ui/typeck/issue-53712.stderr | 11 ++ tests/ui/typeck/issue-7813.rs | 4 + tests/ui/typeck/issue-7813.stderr | 14 ++ 51 files changed, 631 insertions(+), 631 deletions(-) create mode 100644 tests/ui/associated-types/issue-38821.rs create mode 100644 tests/ui/associated-types/issue-38821.stderr create mode 100644 tests/ui/borrowck/issue-83924.fixed create mode 100644 tests/ui/borrowck/issue-83924.rs create mode 100644 tests/ui/borrowck/issue-83924.stderr create mode 100644 tests/ui/consts/issue-33903.rs create mode 100644 tests/ui/consts/issue-54582.rs create mode 100644 tests/ui/drop/issue-2735-2.rs create mode 100644 tests/ui/drop/issue-2735-3.rs create mode 100644 tests/ui/drop/issue-2735.rs create mode 100644 tests/ui/fmt/issue-75307.rs create mode 100644 tests/ui/fmt/issue-75307.stderr create mode 100644 tests/ui/higher-rank-trait-bounds/issue-39292.rs delete mode 100644 tests/ui/issues/issue-22536-copy-mustnt-zero.rs delete mode 100644 tests/ui/issues/issue-2735-2.rs delete mode 100644 tests/ui/issues/issue-2735-3.rs delete mode 100644 tests/ui/issues/issue-2735.rs delete mode 100644 tests/ui/issues/issue-27583.rs delete mode 100644 tests/ui/issues/issue-33903.rs delete mode 100644 tests/ui/issues/issue-38821.rs delete mode 100644 tests/ui/issues/issue-38821.stderr delete mode 100644 tests/ui/issues/issue-39292.rs delete mode 100644 tests/ui/issues/issue-40003.rs delete mode 100644 tests/ui/issues/issue-48179.rs delete mode 100644 tests/ui/issues/issue-50576.rs delete mode 100644 tests/ui/issues/issue-50576.stderr delete mode 100644 tests/ui/issues/issue-53712.rs delete mode 100644 tests/ui/issues/issue-53712.stderr delete mode 100644 tests/ui/issues/issue-54582.rs delete mode 100644 tests/ui/issues/issue-75307.rs delete mode 100644 tests/ui/issues/issue-75307.stderr delete mode 100644 tests/ui/issues/issue-75777.rs delete mode 100644 tests/ui/issues/issue-75777.stderr delete mode 100644 tests/ui/issues/issue-7813.rs delete mode 100644 tests/ui/issues/issue-7813.stderr delete mode 100644 tests/ui/issues/issue-83924.fixed delete mode 100644 tests/ui/issues/issue-83924.rs delete mode 100644 tests/ui/issues/issue-83924.stderr create mode 100644 tests/ui/loops/issue-50576.rs create mode 100644 tests/ui/loops/issue-50576.stderr create mode 100644 tests/ui/moves/issue-22536-copy-mustnt-zero.rs create mode 100644 tests/ui/nll/issue-27583.rs create mode 100644 tests/ui/nll/issue-48179.rs create mode 100644 tests/ui/nll/issue-75777.rs create mode 100644 tests/ui/nll/issue-75777.stderr create mode 100644 tests/ui/recursion_limit/issue-40003.rs create mode 100644 tests/ui/typeck/issue-53712.rs create mode 100644 tests/ui/typeck/issue-53712.stderr create mode 100644 tests/ui/typeck/issue-7813.rs create mode 100644 tests/ui/typeck/issue-7813.stderr diff --git a/src/tools/tidy/src/ui_tests.rs b/src/tools/tidy/src/ui_tests.rs index ef3abb9514f..409f7563184 100644 --- a/src/tools/tidy/src/ui_tests.rs +++ b/src/tools/tidy/src/ui_tests.rs @@ -10,7 +10,7 @@ use std::path::Path; const ENTRY_LIMIT: usize = 1000; // FIXME: The following limits should be reduced eventually. const ROOT_ENTRY_LIMIT: usize = 940; -const ISSUES_ENTRY_LIMIT: usize = 2001; +const ISSUES_ENTRY_LIMIT: usize = 1978; fn check_entries(path: &Path, bad: &mut bool) { for dir in Walk::new(&path.join("ui")) { diff --git a/tests/ui/associated-types/issue-38821.rs b/tests/ui/associated-types/issue-38821.rs new file mode 100644 index 00000000000..6753860e9ff --- /dev/null +++ b/tests/ui/associated-types/issue-38821.rs @@ -0,0 +1,33 @@ +pub struct Nullable(T); + +pub trait NotNull {} + +pub trait IntoNullable { + type Nullable; +} + +impl IntoNullable for T { + type Nullable = Nullable; +} + +impl IntoNullable for Nullable { + type Nullable = Nullable; +} + +pub trait Expression { + type SqlType; +} + +pub trait Column: Expression {} + +#[derive(Debug, Copy, Clone)] +//~^ ERROR the trait bound `::SqlType: NotNull` is not satisfied +pub enum ColumnInsertValue where + Col: Column, + Expr: Expression::Nullable>, +{ + Expression(Col, Expr), + Default(Col), +} + +fn main() {} diff --git a/tests/ui/associated-types/issue-38821.stderr b/tests/ui/associated-types/issue-38821.stderr new file mode 100644 index 00000000000..a52a9c138f1 --- /dev/null +++ b/tests/ui/associated-types/issue-38821.stderr @@ -0,0 +1,22 @@ +error[E0277]: the trait bound `::SqlType: NotNull` is not satisfied + --> $DIR/issue-38821.rs:23:17 + | +LL | #[derive(Debug, Copy, Clone)] + | ^^^^ the trait `NotNull` is not implemented for `::SqlType` + | +note: required for `::SqlType` to implement `IntoNullable` + --> $DIR/issue-38821.rs:9:18 + | +LL | impl IntoNullable for T { + | ------- ^^^^^^^^^^^^ ^ + | | + | unsatisfied trait bound introduced here + = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider further restricting the associated type + | +LL | Expr: Expression::Nullable>, ::SqlType: NotNull, + | +++++++++++++++++++++++++++++++++++++++ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/borrowck/issue-83924.fixed b/tests/ui/borrowck/issue-83924.fixed new file mode 100644 index 00000000000..aa40da12b87 --- /dev/null +++ b/tests/ui/borrowck/issue-83924.fixed @@ -0,0 +1,20 @@ +// run-rustfix + +fn main() { + let mut values = vec![10, 11, 12]; + let v = &mut values; + + let mut max = 0; + + for n in &mut *v { + max = std::cmp::max(max, *n); + } + + println!("max is {}", max); + println!("Converting to percentages of maximum value..."); + for n in v { + //~^ ERROR: use of moved value: `v` [E0382] + *n = 100 * (*n) / max; + } + println!("values: {:#?}", values); +} diff --git a/tests/ui/borrowck/issue-83924.rs b/tests/ui/borrowck/issue-83924.rs new file mode 100644 index 00000000000..22b80fe2f38 --- /dev/null +++ b/tests/ui/borrowck/issue-83924.rs @@ -0,0 +1,20 @@ +// run-rustfix + +fn main() { + let mut values = vec![10, 11, 12]; + let v = &mut values; + + let mut max = 0; + + for n in v { + max = std::cmp::max(max, *n); + } + + println!("max is {}", max); + println!("Converting to percentages of maximum value..."); + for n in v { + //~^ ERROR: use of moved value: `v` [E0382] + *n = 100 * (*n) / max; + } + println!("values: {:#?}", values); +} diff --git a/tests/ui/borrowck/issue-83924.stderr b/tests/ui/borrowck/issue-83924.stderr new file mode 100644 index 00000000000..572414df2bf --- /dev/null +++ b/tests/ui/borrowck/issue-83924.stderr @@ -0,0 +1,22 @@ +error[E0382]: use of moved value: `v` + --> $DIR/issue-83924.rs:15:14 + | +LL | let v = &mut values; + | - move occurs because `v` has type `&mut Vec`, which does not implement the `Copy` trait +... +LL | for n in v { + | - `v` moved due to this implicit call to `.into_iter()` +... +LL | for n in v { + | ^ value used here after move + | +note: `into_iter` takes ownership of the receiver `self`, which moves `v` + --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL +help: consider creating a fresh reborrow of `v` here + | +LL | for n in &mut *v { + | ++++++ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. diff --git a/tests/ui/consts/issue-33903.rs b/tests/ui/consts/issue-33903.rs new file mode 100644 index 00000000000..613aa121a47 --- /dev/null +++ b/tests/ui/consts/issue-33903.rs @@ -0,0 +1,10 @@ +// check-pass +#![allow(dead_code)] +// Issue 33903: +// Built-in indexing should be used even when the index is not +// trivially an integer +// Only built-in indexing can be used in constant expressions + +const FOO: i32 = [12, 34][0 + 1]; + +fn main() {} diff --git a/tests/ui/consts/issue-54582.rs b/tests/ui/consts/issue-54582.rs new file mode 100644 index 00000000000..8c50cac67f8 --- /dev/null +++ b/tests/ui/consts/issue-54582.rs @@ -0,0 +1,16 @@ +// run-pass + +pub trait Stage: Sync {} + +pub enum Enum { + A, + B, +} + +impl Stage for Enum {} + +pub static ARRAY: [(&dyn Stage, &str); 1] = [ + (&Enum::A, ""), +]; + +fn main() {} diff --git a/tests/ui/drop/issue-2735-2.rs b/tests/ui/drop/issue-2735-2.rs new file mode 100644 index 00000000000..70ebce9d35a --- /dev/null +++ b/tests/ui/drop/issue-2735-2.rs @@ -0,0 +1,27 @@ +// run-pass +#![allow(non_camel_case_types)] + +use std::cell::Cell; + +// This test should behave exactly like issue-2735-3 +struct defer<'a> { + b: &'a Cell, +} + +impl<'a> Drop for defer<'a> { + fn drop(&mut self) { + self.b.set(true); + } +} + +fn defer(b: &Cell) -> defer { + defer { + b: b + } +} + +pub fn main() { + let dtor_ran = &Cell::new(false); + let _ = defer(dtor_ran); + assert!(dtor_ran.get()); +} diff --git a/tests/ui/drop/issue-2735-3.rs b/tests/ui/drop/issue-2735-3.rs new file mode 100644 index 00000000000..23301537835 --- /dev/null +++ b/tests/ui/drop/issue-2735-3.rs @@ -0,0 +1,27 @@ +// run-pass +#![allow(non_camel_case_types)] + +use std::cell::Cell; + +// This test should behave exactly like issue-2735-2 +struct defer<'a> { + b: &'a Cell, +} + +impl<'a> Drop for defer<'a> { + fn drop(&mut self) { + self.b.set(true); + } +} + +fn defer(b: &Cell) -> defer { + defer { + b: b + } +} + +pub fn main() { + let dtor_ran = &Cell::new(false); + defer(dtor_ran); + assert!(dtor_ran.get()); +} diff --git a/tests/ui/drop/issue-2735.rs b/tests/ui/drop/issue-2735.rs new file mode 100644 index 00000000000..20d3949a9f9 --- /dev/null +++ b/tests/ui/drop/issue-2735.rs @@ -0,0 +1,22 @@ +// run-pass +#![allow(dead_code)] +#![allow(non_camel_case_types)] + +// pretty-expanded FIXME #23616 + +trait hax { + fn dummy(&self) { } +} +impl hax for A { } + +fn perform_hax(x: Box) -> Box { + Box::new(x) as Box +} + +fn deadcode() { + perform_hax(Box::new("deadcode".to_string())); +} + +pub fn main() { + perform_hax(Box::new(42)); +} diff --git a/tests/ui/fmt/issue-75307.rs b/tests/ui/fmt/issue-75307.rs new file mode 100644 index 00000000000..cffa6bea8ed --- /dev/null +++ b/tests/ui/fmt/issue-75307.rs @@ -0,0 +1,3 @@ +fn main() { + format!(r"{}{}{}", named_arg=1); //~ ERROR 3 positional arguments in format string, but there is 1 argument +} diff --git a/tests/ui/fmt/issue-75307.stderr b/tests/ui/fmt/issue-75307.stderr new file mode 100644 index 00000000000..c5b0b11e7d0 --- /dev/null +++ b/tests/ui/fmt/issue-75307.stderr @@ -0,0 +1,8 @@ +error: 3 positional arguments in format string, but there is 1 argument + --> $DIR/issue-75307.rs:2:15 + | +LL | format!(r"{}{}{}", named_arg=1); + | ^^^^^^ - + +error: aborting due to previous error + diff --git a/tests/ui/higher-rank-trait-bounds/issue-39292.rs b/tests/ui/higher-rank-trait-bounds/issue-39292.rs new file mode 100644 index 00000000000..968cf08916f --- /dev/null +++ b/tests/ui/higher-rank-trait-bounds/issue-39292.rs @@ -0,0 +1,17 @@ +// run-pass +// Regression test for issue #39292. The object vtable was being +// incorrectly left with a null pointer. + +trait Foo { + fn print<'a>(&'a self) where T: 'a { println!("foo"); } +} + +impl<'a> Foo<&'a ()> for () { } + +trait Bar: for<'a> Foo<&'a ()> { } + +impl Bar for () {} + +fn main() { + (&() as &dyn Bar).print(); // Segfault +} diff --git a/tests/ui/issues/issue-22536-copy-mustnt-zero.rs b/tests/ui/issues/issue-22536-copy-mustnt-zero.rs deleted file mode 100644 index 017f36484c1..00000000000 --- a/tests/ui/issues/issue-22536-copy-mustnt-zero.rs +++ /dev/null @@ -1,28 +0,0 @@ -// run-pass -// Regression test for Issue #22536: If a type implements Copy, then -// moving it must not zero the original memory. - - -trait Resources { - type Buffer: Copy; - fn foo(&self) {} -} - -struct BufferHandle { - raw: ::Buffer, -} -impl Copy for BufferHandle {} -impl Clone for BufferHandle { - fn clone(&self) -> BufferHandle { *self } -} - -enum Res {} -impl Resources for Res { - type Buffer = u32; -} - -fn main() { - let b: BufferHandle = BufferHandle { raw: 1 }; - let c = b; - assert_eq!(c.raw, b.raw) -} diff --git a/tests/ui/issues/issue-2735-2.rs b/tests/ui/issues/issue-2735-2.rs deleted file mode 100644 index 70ebce9d35a..00000000000 --- a/tests/ui/issues/issue-2735-2.rs +++ /dev/null @@ -1,27 +0,0 @@ -// run-pass -#![allow(non_camel_case_types)] - -use std::cell::Cell; - -// This test should behave exactly like issue-2735-3 -struct defer<'a> { - b: &'a Cell, -} - -impl<'a> Drop for defer<'a> { - fn drop(&mut self) { - self.b.set(true); - } -} - -fn defer(b: &Cell) -> defer { - defer { - b: b - } -} - -pub fn main() { - let dtor_ran = &Cell::new(false); - let _ = defer(dtor_ran); - assert!(dtor_ran.get()); -} diff --git a/tests/ui/issues/issue-2735-3.rs b/tests/ui/issues/issue-2735-3.rs deleted file mode 100644 index 23301537835..00000000000 --- a/tests/ui/issues/issue-2735-3.rs +++ /dev/null @@ -1,27 +0,0 @@ -// run-pass -#![allow(non_camel_case_types)] - -use std::cell::Cell; - -// This test should behave exactly like issue-2735-2 -struct defer<'a> { - b: &'a Cell, -} - -impl<'a> Drop for defer<'a> { - fn drop(&mut self) { - self.b.set(true); - } -} - -fn defer(b: &Cell) -> defer { - defer { - b: b - } -} - -pub fn main() { - let dtor_ran = &Cell::new(false); - defer(dtor_ran); - assert!(dtor_ran.get()); -} diff --git a/tests/ui/issues/issue-2735.rs b/tests/ui/issues/issue-2735.rs deleted file mode 100644 index 20d3949a9f9..00000000000 --- a/tests/ui/issues/issue-2735.rs +++ /dev/null @@ -1,22 +0,0 @@ -// run-pass -#![allow(dead_code)] -#![allow(non_camel_case_types)] - -// pretty-expanded FIXME #23616 - -trait hax { - fn dummy(&self) { } -} -impl hax for A { } - -fn perform_hax(x: Box) -> Box { - Box::new(x) as Box -} - -fn deadcode() { - perform_hax(Box::new("deadcode".to_string())); -} - -pub fn main() { - perform_hax(Box::new(42)); -} diff --git a/tests/ui/issues/issue-27583.rs b/tests/ui/issues/issue-27583.rs deleted file mode 100644 index 84c94c7c905..00000000000 --- a/tests/ui/issues/issue-27583.rs +++ /dev/null @@ -1,47 +0,0 @@ -// check-pass -// Regression test for issue #27583. Unclear how useful this will be -// going forward, since the issue in question was EXTREMELY sensitive -// to compiler internals (like the precise numbering of nodes), but -// what the hey. - -#![allow(warnings)] - -use std::cell::Cell; -use std::marker::PhantomData; - -pub trait Delegate<'tcx> { } - -pub struct InferCtxt<'a, 'tcx: 'a> { - x: PhantomData<&'a Cell<&'tcx ()>> -} - -pub struct MemCategorizationContext<'t, 'a: 't, 'tcx : 'a> { - x: &'t InferCtxt<'a, 'tcx>, -} - -pub struct ExprUseVisitor<'d, 't, 'a: 't, 'tcx:'a+'d> { - typer: &'t InferCtxt<'a, 'tcx>, - mc: MemCategorizationContext<'t, 'a, 'tcx>, - delegate: &'d mut (Delegate<'tcx>+'d), -} - -impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> { - pub fn new(delegate: &'d mut Delegate<'tcx>, - typer: &'t InferCtxt<'a, 'tcx>) - -> ExprUseVisitor<'d,'t,'a,'tcx> - { - ExprUseVisitor { - typer: typer, - mc: MemCategorizationContext::new(typer), - delegate: delegate, - } - } -} - -impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> { - pub fn new(typer: &'t InferCtxt<'a, 'tcx>) -> MemCategorizationContext<'t, 'a, 'tcx> { - MemCategorizationContext { x: typer } - } -} - -fn main() { } diff --git a/tests/ui/issues/issue-33903.rs b/tests/ui/issues/issue-33903.rs deleted file mode 100644 index 613aa121a47..00000000000 --- a/tests/ui/issues/issue-33903.rs +++ /dev/null @@ -1,10 +0,0 @@ -// check-pass -#![allow(dead_code)] -// Issue 33903: -// Built-in indexing should be used even when the index is not -// trivially an integer -// Only built-in indexing can be used in constant expressions - -const FOO: i32 = [12, 34][0 + 1]; - -fn main() {} diff --git a/tests/ui/issues/issue-38821.rs b/tests/ui/issues/issue-38821.rs deleted file mode 100644 index 6753860e9ff..00000000000 --- a/tests/ui/issues/issue-38821.rs +++ /dev/null @@ -1,33 +0,0 @@ -pub struct Nullable(T); - -pub trait NotNull {} - -pub trait IntoNullable { - type Nullable; -} - -impl IntoNullable for T { - type Nullable = Nullable; -} - -impl IntoNullable for Nullable { - type Nullable = Nullable; -} - -pub trait Expression { - type SqlType; -} - -pub trait Column: Expression {} - -#[derive(Debug, Copy, Clone)] -//~^ ERROR the trait bound `::SqlType: NotNull` is not satisfied -pub enum ColumnInsertValue where - Col: Column, - Expr: Expression::Nullable>, -{ - Expression(Col, Expr), - Default(Col), -} - -fn main() {} diff --git a/tests/ui/issues/issue-38821.stderr b/tests/ui/issues/issue-38821.stderr deleted file mode 100644 index a52a9c138f1..00000000000 --- a/tests/ui/issues/issue-38821.stderr +++ /dev/null @@ -1,22 +0,0 @@ -error[E0277]: the trait bound `::SqlType: NotNull` is not satisfied - --> $DIR/issue-38821.rs:23:17 - | -LL | #[derive(Debug, Copy, Clone)] - | ^^^^ the trait `NotNull` is not implemented for `::SqlType` - | -note: required for `::SqlType` to implement `IntoNullable` - --> $DIR/issue-38821.rs:9:18 - | -LL | impl IntoNullable for T { - | ------- ^^^^^^^^^^^^ ^ - | | - | unsatisfied trait bound introduced here - = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) -help: consider further restricting the associated type - | -LL | Expr: Expression::Nullable>, ::SqlType: NotNull, - | +++++++++++++++++++++++++++++++++++++++ - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/issues/issue-39292.rs b/tests/ui/issues/issue-39292.rs deleted file mode 100644 index 968cf08916f..00000000000 --- a/tests/ui/issues/issue-39292.rs +++ /dev/null @@ -1,17 +0,0 @@ -// run-pass -// Regression test for issue #39292. The object vtable was being -// incorrectly left with a null pointer. - -trait Foo { - fn print<'a>(&'a self) where T: 'a { println!("foo"); } -} - -impl<'a> Foo<&'a ()> for () { } - -trait Bar: for<'a> Foo<&'a ()> { } - -impl Bar for () {} - -fn main() { - (&() as &dyn Bar).print(); // Segfault -} diff --git a/tests/ui/issues/issue-40003.rs b/tests/ui/issues/issue-40003.rs deleted file mode 100644 index 5e61361f987..00000000000 --- a/tests/ui/issues/issue-40003.rs +++ /dev/null @@ -1,178 +0,0 @@ -// run-pass -#![allow(unused_must_use)] -fn main() { - if false { test(); } -} - -fn test() { - let rx = Err::, u32>(1).into_future(); - - rx.map(|l: Vec| stream::iter(l.into_iter().map(|i| Ok(i)))) - .flatten_stream() - .chunks(50) - .buffer_unordered(5); -} - -use future::{Future, IntoFuture}; -mod future { - use std::result; - - use {stream, Stream}; - - pub trait Future { - type Item; - type Error; - - fn map(self, _: F) -> Map - where F: FnOnce(Self::Item) -> U, - Self: Sized, - { - panic!() - } - - fn flatten_stream(self) -> FlattenStream - where ::Item: stream::Stream, - Self: Sized - { - panic!() - } - } - - pub trait IntoFuture { - type Future: Future; - type Item; - type Error; - fn into_future(self) -> Self::Future; - } - - impl IntoFuture for F { - type Future = F; - type Item = F::Item; - type Error = F::Error; - - fn into_future(self) -> F { - panic!() - } - } - - impl IntoFuture for result::Result { - type Future = FutureResult; - type Item = T; - type Error = E; - - fn into_future(self) -> FutureResult { - panic!() - } - } - - pub struct Map { - _a: (A, F), - } - - impl Future for Map - where A: Future, - F: FnOnce(A::Item) -> U, - { - type Item = U; - type Error = A::Error; - } - - pub struct FlattenStream { - _f: F, - } - - impl Stream for FlattenStream - where F: Future, - ::Item: Stream, - { - type Item = ::Item; - type Error = ::Error; - } - - pub struct FutureResult { - _inner: (T, E), - } - - impl Future for FutureResult { - type Item = T; - type Error = E; - } -} - -mod stream { - use IntoFuture; - - pub trait Stream { - type Item; - type Error; - - fn buffer_unordered(self, amt: usize) -> BufferUnordered - where Self::Item: IntoFuture::Error>, - Self: Sized - { - new(self, amt) - } - - fn chunks(self, _capacity: usize) -> Chunks - where Self: Sized - { - panic!() - } - } - - pub struct IterStream { - _iter: I, - } - - pub fn iter(_: J) -> IterStream - where J: IntoIterator>, - { - panic!() - } - - impl Stream for IterStream - where I: Iterator>, - { - type Item = T; - type Error = E; - } - - pub struct Chunks { - _stream: S - } - - impl Stream for Chunks - where S: Stream - { - type Item = Result::Item>, u32>; - type Error = ::Error; - } - - pub struct BufferUnordered { - _stream: S, - } - - enum Slot { - Next(#[allow(unused_tuple_struct_fields)] usize), - _Data { _a: T }, - } - - fn new(_s: S, _amt: usize) -> BufferUnordered - where S: Stream, - S::Item: IntoFuture::Error>, - { - (0..0).map(|_| { - Slot::Next::<::Future>(1) - }).collect::>(); - panic!() - } - - impl Stream for BufferUnordered - where S: Stream, - S::Item: IntoFuture::Error>, - { - type Item = ::Item; - type Error = ::Error; - } -} -use stream::Stream; diff --git a/tests/ui/issues/issue-48179.rs b/tests/ui/issues/issue-48179.rs deleted file mode 100644 index f81203dc412..00000000000 --- a/tests/ui/issues/issue-48179.rs +++ /dev/null @@ -1,38 +0,0 @@ -// Regression test for #48132. This was failing due to problems around -// the projection caching and dropck type enumeration. - -// check-pass - -pub struct Container { - value: Option, -} - -impl Container { - pub fn new(iter: T) -> Self { - panic!() - } -} - -pub struct Wrapper<'a> { - content: &'a Content, -} - -impl<'a, 'de> Wrapper<'a> { - pub fn new(content: &'a Content) -> Self { - Wrapper { - content: content, - } - } -} - -pub struct Content; - -fn crash_it(content: Content) { - let items = vec![content]; - let map = items.iter().map(|ref o| Wrapper::new(o)); - - let mut map_visitor = Container::new(map); - -} - -fn main() {} diff --git a/tests/ui/issues/issue-50576.rs b/tests/ui/issues/issue-50576.rs deleted file mode 100644 index e0c36b8273a..00000000000 --- a/tests/ui/issues/issue-50576.rs +++ /dev/null @@ -1,6 +0,0 @@ -fn main() { - |bool: [u8; break 'L]| 0; - //~^ ERROR [E0426] - //~| ERROR [E0268] - Vec::<[u8; break]>::new(); //~ ERROR [E0268] -} diff --git a/tests/ui/issues/issue-50576.stderr b/tests/ui/issues/issue-50576.stderr deleted file mode 100644 index 4ec22fde910..00000000000 --- a/tests/ui/issues/issue-50576.stderr +++ /dev/null @@ -1,22 +0,0 @@ -error[E0426]: use of undeclared label `'L` - --> $DIR/issue-50576.rs:2:23 - | -LL | |bool: [u8; break 'L]| 0; - | ^^ undeclared label `'L` - -error[E0268]: `break` outside of a loop or labeled block - --> $DIR/issue-50576.rs:2:17 - | -LL | |bool: [u8; break 'L]| 0; - | ^^^^^^^^ cannot `break` outside of a loop or labeled block - -error[E0268]: `break` outside of a loop or labeled block - --> $DIR/issue-50576.rs:5:16 - | -LL | Vec::<[u8; break]>::new(); - | ^^^^^ cannot `break` outside of a loop or labeled block - -error: aborting due to 3 previous errors - -Some errors have detailed explanations: E0268, E0426. -For more information about an error, try `rustc --explain E0268`. diff --git a/tests/ui/issues/issue-53712.rs b/tests/ui/issues/issue-53712.rs deleted file mode 100644 index 2353904d79d..00000000000 --- a/tests/ui/issues/issue-53712.rs +++ /dev/null @@ -1,9 +0,0 @@ -// issue #53712: make the error generated by using tuple indexing on an array more specific - -fn main() { - let arr = [10, 20, 30, 40, 50]; - arr.0; - //~^ ERROR no field `0` on type `[{integer}; 5]` [E0609] - //~| HELP instead of using tuple indexing, use array indexing - //~| SUGGESTION arr[0] -} diff --git a/tests/ui/issues/issue-53712.stderr b/tests/ui/issues/issue-53712.stderr deleted file mode 100644 index db85919afcb..00000000000 --- a/tests/ui/issues/issue-53712.stderr +++ /dev/null @@ -1,11 +0,0 @@ -error[E0609]: no field `0` on type `[{integer}; 5]` - --> $DIR/issue-53712.rs:5:9 - | -LL | arr.0; - | ----^ - | | - | help: instead of using tuple indexing, use array indexing: `arr[0]` - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0609`. diff --git a/tests/ui/issues/issue-54582.rs b/tests/ui/issues/issue-54582.rs deleted file mode 100644 index 8c50cac67f8..00000000000 --- a/tests/ui/issues/issue-54582.rs +++ /dev/null @@ -1,16 +0,0 @@ -// run-pass - -pub trait Stage: Sync {} - -pub enum Enum { - A, - B, -} - -impl Stage for Enum {} - -pub static ARRAY: [(&dyn Stage, &str); 1] = [ - (&Enum::A, ""), -]; - -fn main() {} diff --git a/tests/ui/issues/issue-75307.rs b/tests/ui/issues/issue-75307.rs deleted file mode 100644 index cffa6bea8ed..00000000000 --- a/tests/ui/issues/issue-75307.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - format!(r"{}{}{}", named_arg=1); //~ ERROR 3 positional arguments in format string, but there is 1 argument -} diff --git a/tests/ui/issues/issue-75307.stderr b/tests/ui/issues/issue-75307.stderr deleted file mode 100644 index c5b0b11e7d0..00000000000 --- a/tests/ui/issues/issue-75307.stderr +++ /dev/null @@ -1,8 +0,0 @@ -error: 3 positional arguments in format string, but there is 1 argument - --> $DIR/issue-75307.rs:2:15 - | -LL | format!(r"{}{}{}", named_arg=1); - | ^^^^^^ - - -error: aborting due to previous error - diff --git a/tests/ui/issues/issue-75777.rs b/tests/ui/issues/issue-75777.rs deleted file mode 100644 index a1e438bc617..00000000000 --- a/tests/ui/issues/issue-75777.rs +++ /dev/null @@ -1,15 +0,0 @@ -// Regression test for #75777. -// Checks that a boxed future can be properly constructed. - -use std::future::{self, Future}; -use std::pin::Pin; - -type BoxFuture<'a, T> = Pin + 'a + Send>>; - -fn inject<'a, Env: 'a, A: 'a + Send>(v: A) -> Box BoxFuture<'a, A>> { - let fut: BoxFuture<'a, A> = Box::pin(future::ready(v)); - Box::new(move |_| fut) - //~^ ERROR: lifetime may not live long enough -} - -fn main() {} diff --git a/tests/ui/issues/issue-75777.stderr b/tests/ui/issues/issue-75777.stderr deleted file mode 100644 index 370cd72fd55..00000000000 --- a/tests/ui/issues/issue-75777.stderr +++ /dev/null @@ -1,11 +0,0 @@ -error: lifetime may not live long enough - --> $DIR/issue-75777.rs:11:5 - | -LL | fn inject<'a, Env: 'a, A: 'a + Send>(v: A) -> Box BoxFuture<'a, A>> { - | -- lifetime `'a` defined here -LL | let fut: BoxFuture<'a, A> = Box::pin(future::ready(v)); -LL | Box::new(move |_| fut) - | ^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'a` must outlive `'static` - -error: aborting due to previous error - diff --git a/tests/ui/issues/issue-7813.rs b/tests/ui/issues/issue-7813.rs deleted file mode 100644 index ce549bde601..00000000000 --- a/tests/ui/issues/issue-7813.rs +++ /dev/null @@ -1,4 +0,0 @@ -fn main() { - let v = &[]; //~ ERROR type annotations needed - let it = v.iter(); -} diff --git a/tests/ui/issues/issue-7813.stderr b/tests/ui/issues/issue-7813.stderr deleted file mode 100644 index 2a747f679a8..00000000000 --- a/tests/ui/issues/issue-7813.stderr +++ /dev/null @@ -1,14 +0,0 @@ -error[E0282]: type annotations needed for `&[_; 0]` - --> $DIR/issue-7813.rs:2:9 - | -LL | let v = &[]; - | ^ --- type must be known at this point - | -help: consider giving `v` an explicit type, where the placeholders `_` are specified - | -LL | let v: &[_; 0] = &[]; - | +++++++++ - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0282`. diff --git a/tests/ui/issues/issue-83924.fixed b/tests/ui/issues/issue-83924.fixed deleted file mode 100644 index aa40da12b87..00000000000 --- a/tests/ui/issues/issue-83924.fixed +++ /dev/null @@ -1,20 +0,0 @@ -// run-rustfix - -fn main() { - let mut values = vec![10, 11, 12]; - let v = &mut values; - - let mut max = 0; - - for n in &mut *v { - max = std::cmp::max(max, *n); - } - - println!("max is {}", max); - println!("Converting to percentages of maximum value..."); - for n in v { - //~^ ERROR: use of moved value: `v` [E0382] - *n = 100 * (*n) / max; - } - println!("values: {:#?}", values); -} diff --git a/tests/ui/issues/issue-83924.rs b/tests/ui/issues/issue-83924.rs deleted file mode 100644 index 22b80fe2f38..00000000000 --- a/tests/ui/issues/issue-83924.rs +++ /dev/null @@ -1,20 +0,0 @@ -// run-rustfix - -fn main() { - let mut values = vec![10, 11, 12]; - let v = &mut values; - - let mut max = 0; - - for n in v { - max = std::cmp::max(max, *n); - } - - println!("max is {}", max); - println!("Converting to percentages of maximum value..."); - for n in v { - //~^ ERROR: use of moved value: `v` [E0382] - *n = 100 * (*n) / max; - } - println!("values: {:#?}", values); -} diff --git a/tests/ui/issues/issue-83924.stderr b/tests/ui/issues/issue-83924.stderr deleted file mode 100644 index 572414df2bf..00000000000 --- a/tests/ui/issues/issue-83924.stderr +++ /dev/null @@ -1,22 +0,0 @@ -error[E0382]: use of moved value: `v` - --> $DIR/issue-83924.rs:15:14 - | -LL | let v = &mut values; - | - move occurs because `v` has type `&mut Vec`, which does not implement the `Copy` trait -... -LL | for n in v { - | - `v` moved due to this implicit call to `.into_iter()` -... -LL | for n in v { - | ^ value used here after move - | -note: `into_iter` takes ownership of the receiver `self`, which moves `v` - --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL -help: consider creating a fresh reborrow of `v` here - | -LL | for n in &mut *v { - | ++++++ - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0382`. diff --git a/tests/ui/loops/issue-50576.rs b/tests/ui/loops/issue-50576.rs new file mode 100644 index 00000000000..e0c36b8273a --- /dev/null +++ b/tests/ui/loops/issue-50576.rs @@ -0,0 +1,6 @@ +fn main() { + |bool: [u8; break 'L]| 0; + //~^ ERROR [E0426] + //~| ERROR [E0268] + Vec::<[u8; break]>::new(); //~ ERROR [E0268] +} diff --git a/tests/ui/loops/issue-50576.stderr b/tests/ui/loops/issue-50576.stderr new file mode 100644 index 00000000000..4ec22fde910 --- /dev/null +++ b/tests/ui/loops/issue-50576.stderr @@ -0,0 +1,22 @@ +error[E0426]: use of undeclared label `'L` + --> $DIR/issue-50576.rs:2:23 + | +LL | |bool: [u8; break 'L]| 0; + | ^^ undeclared label `'L` + +error[E0268]: `break` outside of a loop or labeled block + --> $DIR/issue-50576.rs:2:17 + | +LL | |bool: [u8; break 'L]| 0; + | ^^^^^^^^ cannot `break` outside of a loop or labeled block + +error[E0268]: `break` outside of a loop or labeled block + --> $DIR/issue-50576.rs:5:16 + | +LL | Vec::<[u8; break]>::new(); + | ^^^^^ cannot `break` outside of a loop or labeled block + +error: aborting due to 3 previous errors + +Some errors have detailed explanations: E0268, E0426. +For more information about an error, try `rustc --explain E0268`. diff --git a/tests/ui/moves/issue-22536-copy-mustnt-zero.rs b/tests/ui/moves/issue-22536-copy-mustnt-zero.rs new file mode 100644 index 00000000000..017f36484c1 --- /dev/null +++ b/tests/ui/moves/issue-22536-copy-mustnt-zero.rs @@ -0,0 +1,28 @@ +// run-pass +// Regression test for Issue #22536: If a type implements Copy, then +// moving it must not zero the original memory. + + +trait Resources { + type Buffer: Copy; + fn foo(&self) {} +} + +struct BufferHandle { + raw: ::Buffer, +} +impl Copy for BufferHandle {} +impl Clone for BufferHandle { + fn clone(&self) -> BufferHandle { *self } +} + +enum Res {} +impl Resources for Res { + type Buffer = u32; +} + +fn main() { + let b: BufferHandle = BufferHandle { raw: 1 }; + let c = b; + assert_eq!(c.raw, b.raw) +} diff --git a/tests/ui/nll/issue-27583.rs b/tests/ui/nll/issue-27583.rs new file mode 100644 index 00000000000..84c94c7c905 --- /dev/null +++ b/tests/ui/nll/issue-27583.rs @@ -0,0 +1,47 @@ +// check-pass +// Regression test for issue #27583. Unclear how useful this will be +// going forward, since the issue in question was EXTREMELY sensitive +// to compiler internals (like the precise numbering of nodes), but +// what the hey. + +#![allow(warnings)] + +use std::cell::Cell; +use std::marker::PhantomData; + +pub trait Delegate<'tcx> { } + +pub struct InferCtxt<'a, 'tcx: 'a> { + x: PhantomData<&'a Cell<&'tcx ()>> +} + +pub struct MemCategorizationContext<'t, 'a: 't, 'tcx : 'a> { + x: &'t InferCtxt<'a, 'tcx>, +} + +pub struct ExprUseVisitor<'d, 't, 'a: 't, 'tcx:'a+'d> { + typer: &'t InferCtxt<'a, 'tcx>, + mc: MemCategorizationContext<'t, 'a, 'tcx>, + delegate: &'d mut (Delegate<'tcx>+'d), +} + +impl<'d,'t,'a,'tcx> ExprUseVisitor<'d,'t,'a,'tcx> { + pub fn new(delegate: &'d mut Delegate<'tcx>, + typer: &'t InferCtxt<'a, 'tcx>) + -> ExprUseVisitor<'d,'t,'a,'tcx> + { + ExprUseVisitor { + typer: typer, + mc: MemCategorizationContext::new(typer), + delegate: delegate, + } + } +} + +impl<'t, 'a,'tcx> MemCategorizationContext<'t, 'a, 'tcx> { + pub fn new(typer: &'t InferCtxt<'a, 'tcx>) -> MemCategorizationContext<'t, 'a, 'tcx> { + MemCategorizationContext { x: typer } + } +} + +fn main() { } diff --git a/tests/ui/nll/issue-48179.rs b/tests/ui/nll/issue-48179.rs new file mode 100644 index 00000000000..f81203dc412 --- /dev/null +++ b/tests/ui/nll/issue-48179.rs @@ -0,0 +1,38 @@ +// Regression test for #48132. This was failing due to problems around +// the projection caching and dropck type enumeration. + +// check-pass + +pub struct Container { + value: Option, +} + +impl Container { + pub fn new(iter: T) -> Self { + panic!() + } +} + +pub struct Wrapper<'a> { + content: &'a Content, +} + +impl<'a, 'de> Wrapper<'a> { + pub fn new(content: &'a Content) -> Self { + Wrapper { + content: content, + } + } +} + +pub struct Content; + +fn crash_it(content: Content) { + let items = vec![content]; + let map = items.iter().map(|ref o| Wrapper::new(o)); + + let mut map_visitor = Container::new(map); + +} + +fn main() {} diff --git a/tests/ui/nll/issue-75777.rs b/tests/ui/nll/issue-75777.rs new file mode 100644 index 00000000000..a1e438bc617 --- /dev/null +++ b/tests/ui/nll/issue-75777.rs @@ -0,0 +1,15 @@ +// Regression test for #75777. +// Checks that a boxed future can be properly constructed. + +use std::future::{self, Future}; +use std::pin::Pin; + +type BoxFuture<'a, T> = Pin + 'a + Send>>; + +fn inject<'a, Env: 'a, A: 'a + Send>(v: A) -> Box BoxFuture<'a, A>> { + let fut: BoxFuture<'a, A> = Box::pin(future::ready(v)); + Box::new(move |_| fut) + //~^ ERROR: lifetime may not live long enough +} + +fn main() {} diff --git a/tests/ui/nll/issue-75777.stderr b/tests/ui/nll/issue-75777.stderr new file mode 100644 index 00000000000..370cd72fd55 --- /dev/null +++ b/tests/ui/nll/issue-75777.stderr @@ -0,0 +1,11 @@ +error: lifetime may not live long enough + --> $DIR/issue-75777.rs:11:5 + | +LL | fn inject<'a, Env: 'a, A: 'a + Send>(v: A) -> Box BoxFuture<'a, A>> { + | -- lifetime `'a` defined here +LL | let fut: BoxFuture<'a, A> = Box::pin(future::ready(v)); +LL | Box::new(move |_| fut) + | ^^^^^^^^^^^^^^^^^^^^^^ returning this value requires that `'a` must outlive `'static` + +error: aborting due to previous error + diff --git a/tests/ui/recursion_limit/issue-40003.rs b/tests/ui/recursion_limit/issue-40003.rs new file mode 100644 index 00000000000..5e61361f987 --- /dev/null +++ b/tests/ui/recursion_limit/issue-40003.rs @@ -0,0 +1,178 @@ +// run-pass +#![allow(unused_must_use)] +fn main() { + if false { test(); } +} + +fn test() { + let rx = Err::, u32>(1).into_future(); + + rx.map(|l: Vec| stream::iter(l.into_iter().map(|i| Ok(i)))) + .flatten_stream() + .chunks(50) + .buffer_unordered(5); +} + +use future::{Future, IntoFuture}; +mod future { + use std::result; + + use {stream, Stream}; + + pub trait Future { + type Item; + type Error; + + fn map(self, _: F) -> Map + where F: FnOnce(Self::Item) -> U, + Self: Sized, + { + panic!() + } + + fn flatten_stream(self) -> FlattenStream + where ::Item: stream::Stream, + Self: Sized + { + panic!() + } + } + + pub trait IntoFuture { + type Future: Future; + type Item; + type Error; + fn into_future(self) -> Self::Future; + } + + impl IntoFuture for F { + type Future = F; + type Item = F::Item; + type Error = F::Error; + + fn into_future(self) -> F { + panic!() + } + } + + impl IntoFuture for result::Result { + type Future = FutureResult; + type Item = T; + type Error = E; + + fn into_future(self) -> FutureResult { + panic!() + } + } + + pub struct Map { + _a: (A, F), + } + + impl Future for Map + where A: Future, + F: FnOnce(A::Item) -> U, + { + type Item = U; + type Error = A::Error; + } + + pub struct FlattenStream { + _f: F, + } + + impl Stream for FlattenStream + where F: Future, + ::Item: Stream, + { + type Item = ::Item; + type Error = ::Error; + } + + pub struct FutureResult { + _inner: (T, E), + } + + impl Future for FutureResult { + type Item = T; + type Error = E; + } +} + +mod stream { + use IntoFuture; + + pub trait Stream { + type Item; + type Error; + + fn buffer_unordered(self, amt: usize) -> BufferUnordered + where Self::Item: IntoFuture::Error>, + Self: Sized + { + new(self, amt) + } + + fn chunks(self, _capacity: usize) -> Chunks + where Self: Sized + { + panic!() + } + } + + pub struct IterStream { + _iter: I, + } + + pub fn iter(_: J) -> IterStream + where J: IntoIterator>, + { + panic!() + } + + impl Stream for IterStream + where I: Iterator>, + { + type Item = T; + type Error = E; + } + + pub struct Chunks { + _stream: S + } + + impl Stream for Chunks + where S: Stream + { + type Item = Result::Item>, u32>; + type Error = ::Error; + } + + pub struct BufferUnordered { + _stream: S, + } + + enum Slot { + Next(#[allow(unused_tuple_struct_fields)] usize), + _Data { _a: T }, + } + + fn new(_s: S, _amt: usize) -> BufferUnordered + where S: Stream, + S::Item: IntoFuture::Error>, + { + (0..0).map(|_| { + Slot::Next::<::Future>(1) + }).collect::>(); + panic!() + } + + impl Stream for BufferUnordered + where S: Stream, + S::Item: IntoFuture::Error>, + { + type Item = ::Item; + type Error = ::Error; + } +} +use stream::Stream; diff --git a/tests/ui/typeck/issue-53712.rs b/tests/ui/typeck/issue-53712.rs new file mode 100644 index 00000000000..2353904d79d --- /dev/null +++ b/tests/ui/typeck/issue-53712.rs @@ -0,0 +1,9 @@ +// issue #53712: make the error generated by using tuple indexing on an array more specific + +fn main() { + let arr = [10, 20, 30, 40, 50]; + arr.0; + //~^ ERROR no field `0` on type `[{integer}; 5]` [E0609] + //~| HELP instead of using tuple indexing, use array indexing + //~| SUGGESTION arr[0] +} diff --git a/tests/ui/typeck/issue-53712.stderr b/tests/ui/typeck/issue-53712.stderr new file mode 100644 index 00000000000..db85919afcb --- /dev/null +++ b/tests/ui/typeck/issue-53712.stderr @@ -0,0 +1,11 @@ +error[E0609]: no field `0` on type `[{integer}; 5]` + --> $DIR/issue-53712.rs:5:9 + | +LL | arr.0; + | ----^ + | | + | help: instead of using tuple indexing, use array indexing: `arr[0]` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0609`. diff --git a/tests/ui/typeck/issue-7813.rs b/tests/ui/typeck/issue-7813.rs new file mode 100644 index 00000000000..ce549bde601 --- /dev/null +++ b/tests/ui/typeck/issue-7813.rs @@ -0,0 +1,4 @@ +fn main() { + let v = &[]; //~ ERROR type annotations needed + let it = v.iter(); +} diff --git a/tests/ui/typeck/issue-7813.stderr b/tests/ui/typeck/issue-7813.stderr new file mode 100644 index 00000000000..2a747f679a8 --- /dev/null +++ b/tests/ui/typeck/issue-7813.stderr @@ -0,0 +1,14 @@ +error[E0282]: type annotations needed for `&[_; 0]` + --> $DIR/issue-7813.rs:2:9 + | +LL | let v = &[]; + | ^ --- type must be known at this point + | +help: consider giving `v` an explicit type, where the placeholders `_` are specified + | +LL | let v: &[_; 0] = &[]; + | +++++++++ + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0282`. -- cgit 1.4.1-3-g733a5 From a1a6588162ad586c48465d4a0c19dce4169ba33f Mon Sep 17 00:00:00 2001 From: Matthias Krüger Date: Thu, 16 Feb 2023 00:19:16 +0100 Subject: don't into self don't into()-convert types to themselves --- compiler/rustc_infer/src/infer/combine.rs | 4 ++-- compiler/rustc_mir_transform/src/ctfe_limit.rs | 3 +-- src/librustdoc/clean/utils.rs | 2 +- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_infer/src/infer/combine.rs b/compiler/rustc_infer/src/infer/combine.rs index 964222307bc..f5504b05dc4 100644 --- a/compiler/rustc_infer/src/infer/combine.rs +++ b/compiler/rustc_infer/src/infer/combine.rs @@ -125,11 +125,11 @@ impl<'tcx> InferCtxt<'tcx> { } (ty::Alias(AliasKind::Projection, _), _) if self.tcx.trait_solver_next() => { - relation.register_type_equate_obligation(a.into(), b.into()); + relation.register_type_equate_obligation(a, b); Ok(b) } (_, ty::Alias(AliasKind::Projection, _)) if self.tcx.trait_solver_next() => { - relation.register_type_equate_obligation(b.into(), a.into()); + relation.register_type_equate_obligation(b, a); Ok(a) } diff --git a/compiler/rustc_mir_transform/src/ctfe_limit.rs b/compiler/rustc_mir_transform/src/ctfe_limit.rs index 7d127032179..1b3ac78fbc6 100644 --- a/compiler/rustc_mir_transform/src/ctfe_limit.rs +++ b/compiler/rustc_mir_transform/src/ctfe_limit.rs @@ -47,8 +47,7 @@ fn has_back_edge( return false; } // Check if any of the dominators of the node are also the node's successor. - doms.dominators(node) - .any(|dom| node_data.terminator().successors().into_iter().any(|succ| succ == dom)) + doms.dominators(node).any(|dom| node_data.terminator().successors().any(|succ| succ == dom)) } fn insert_counter(basic_block_data: &mut BasicBlockData<'_>) { diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 4d8ce54dc5c..6fe665d7e40 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -129,7 +129,7 @@ fn external_generic_args<'tcx>( }); GenericArgs::Parenthesized { inputs, output } } else { - GenericArgs::AngleBracketed { args: args.into(), bindings: bindings.into() } + GenericArgs::AngleBracketed { args: args.into(), bindings } } } -- cgit 1.4.1-3-g733a5 From d659c7c343990e69c0270ce183f05700d40a4121 Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Tue, 14 Feb 2023 15:55:31 -0700 Subject: make issue33140_self_ty return Option> --- compiler/rustc_middle/src/query/mod.rs | 2 +- compiler/rustc_ty_utils/src/ty.rs | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 4b34f6b4881..000fa92fdd1 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -781,7 +781,7 @@ rustc_queries! { separate_provide_extern } - query issue33140_self_ty(key: DefId) -> Option> { + query issue33140_self_ty(key: DefId) -> Option>> { desc { |tcx| "computing Self type wrt issue #33140 `{}`", tcx.def_path_str(key) } } diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index 41e837e8b75..fc3d9fb067d 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -1,7 +1,9 @@ use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; use rustc_index::bit_set::BitSet; -use rustc_middle::ty::{self, Binder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt}; +use rustc_middle::ty::{ + self, Binder, EarlyBinder, Predicate, PredicateKind, ToPredicate, Ty, TyCtxt, +}; use rustc_session::config::TraitSolver; use rustc_span::def_id::{DefId, CRATE_DEF_ID}; use rustc_trait_selection::traits; @@ -355,7 +357,7 @@ fn instance_def_size_estimate<'tcx>( /// If `def_id` is an issue 33140 hack impl, returns its self type; otherwise, returns `None`. /// /// See [`ty::ImplOverlapKind::Issue33140`] for more details. -fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option> { +fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option>> { debug!("issue33140_self_ty({:?})", def_id); let trait_ref = tcx @@ -394,7 +396,7 @@ fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option> { if self_ty_matches { debug!("issue33140_self_ty - MATCHES!"); - Some(self_ty) + Some(EarlyBinder(self_ty)) } else { debug!("issue33140_self_ty - non-matching self type"); None -- cgit 1.4.1-3-g733a5 From 382ade6a6054fa84c581f1e40fe3db79312db369 Mon Sep 17 00:00:00 2001 From: Kyle Matsuda Date: Tue, 14 Feb 2023 15:55:54 -0700 Subject: fix ugly skip_binder --- compiler/rustc_metadata/src/rmeta/encoder.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 43047051f0f..e941dd45688 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1541,8 +1541,9 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { self.tables.impl_defaultness.set_some(def_id.index, *defaultness); self.tables.constness.set_some(def_id.index, *constness); - let trait_ref = self.tcx.impl_trait_ref(def_id).map(ty::EarlyBinder::skip_binder); + let trait_ref = self.tcx.impl_trait_ref(def_id); if let Some(trait_ref) = trait_ref { + let trait_ref = trait_ref.skip_binder(); let trait_def = self.tcx.trait_def(trait_ref.def_id); if let Ok(mut an) = trait_def.ancestors(self.tcx, def_id) { if let Some(specialization_graph::Node::Impl(parent)) = an.nth(1) { -- cgit 1.4.1-3-g733a5 From ced962975b5d42607ec50425e6b2d8d504784248 Mon Sep 17 00:00:00 2001 From: yancy Date: Sun, 6 Nov 2022 21:29:44 +0100 Subject: rustdoc: Update the description to include PartialOrd elements --- library/core/src/iter/traits/iterator.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index 83c7e8977e9..182ef241c45 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -3475,8 +3475,10 @@ pub trait Iterator { } } - /// [Lexicographically](Ord#lexicographical-comparison) compares the elements of this [`Iterator`] with those - /// of another. + /// [Lexicographically](Ord#lexicographical-comparison) compares the [`PartialOrd`] elements of + /// this [`Iterator`] with those of another. The comparison works like short-circuit + /// evaluation, returning a result without comparing the remaining elements. + /// As soon as an order can be determined, the evaluation stops and a result is returned. /// /// # Examples /// @@ -3486,9 +3488,25 @@ pub trait Iterator { /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal)); /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less)); /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater)); + /// ``` /// + /// For floating-point numbers, NaN does not have a total order and will result + /// in `None` when compared: + /// + /// ``` /// assert_eq!([f64::NAN].iter().partial_cmp([1.].iter()), None); /// ``` + /// + /// The results are determined by the order of evaluation. + /// + /// ``` + /// use std::cmp::Ordering; + /// + /// assert_eq!([1.0, f64::NAN].iter().partial_cmp([2.0, f64::NAN].iter()), Some(Ordering::Less)); + /// assert_eq!([2.0, f64::NAN].iter().partial_cmp([1.0, f64::NAN].iter()), Some(Ordering::Greater)); + /// assert_eq!([f64::NAN, 1.0].iter().partial_cmp([f64::NAN, 2.0].iter()), None); + /// ``` + /// #[stable(feature = "iter_order", since = "1.5.0")] fn partial_cmp(self, other: I) -> Option where -- cgit 1.4.1-3-g733a5 From a1468ae00d559e0647c98a6015a35c50e5551704 Mon Sep 17 00:00:00 2001 From: Alan Egerton Date: Thu, 16 Feb 2023 21:59:10 +0000 Subject: Do not ICE on unmet trait alias impl bounds --- compiler/rustc_hir_typeck/src/method/suggest.rs | 4 +++- ...8132-unmet-trait-alias-bound-on-generic-impl.rs | 15 +++++++++++++ ...-unmet-trait-alias-bound-on-generic-impl.stderr | 25 ++++++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 tests/ui/traits/alias/issue-108132-unmet-trait-alias-bound-on-generic-impl.rs create mode 100644 tests/ui/traits/alias/issue-108132-unmet-trait-alias-bound-on-generic-impl.stderr diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 54890489f8b..68d2b9c6428 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -714,7 +714,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); } Some(Node::Item(hir::Item { - ident, kind: hir::ItemKind::Trait(..), .. + ident, + kind: hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..), + .. })) => { skip_list.insert(p); let entry = spanned_predicates.entry(ident.span); diff --git a/tests/ui/traits/alias/issue-108132-unmet-trait-alias-bound-on-generic-impl.rs b/tests/ui/traits/alias/issue-108132-unmet-trait-alias-bound-on-generic-impl.rs new file mode 100644 index 00000000000..0b1f9ab57c9 --- /dev/null +++ b/tests/ui/traits/alias/issue-108132-unmet-trait-alias-bound-on-generic-impl.rs @@ -0,0 +1,15 @@ +// Regression test for #108132: do not ICE upon unmet trait alias constraint in generic impl + +#![feature(trait_alias)] + +trait IteratorAlias = Iterator; + +struct Foo(I); + +impl Foo { + fn f() {} +} + +fn main() { + Foo::<()>::f() //~ trait bounds were not satisfied +} diff --git a/tests/ui/traits/alias/issue-108132-unmet-trait-alias-bound-on-generic-impl.stderr b/tests/ui/traits/alias/issue-108132-unmet-trait-alias-bound-on-generic-impl.stderr new file mode 100644 index 00000000000..f1b259d5a65 --- /dev/null +++ b/tests/ui/traits/alias/issue-108132-unmet-trait-alias-bound-on-generic-impl.stderr @@ -0,0 +1,25 @@ +error[E0599]: the function or associated item `f` exists for struct `Foo<()>`, but its trait bounds were not satisfied + --> $DIR/issue-108132-unmet-trait-alias-bound-on-generic-impl.rs:14:16 + | +LL | struct Foo(I); + | ------------- function or associated item `f` not found for this struct +... +LL | Foo::<()>::f() + | ^ function or associated item cannot be called on `Foo<()>` due to unsatisfied trait bounds + | +note: trait bound `(): Iterator` was not satisfied + --> $DIR/issue-108132-unmet-trait-alias-bound-on-generic-impl.rs:5:23 + | +LL | trait IteratorAlias = Iterator; + | ------------- ^^^^^^^^ unsatisfied trait bound introduced here +note: trait bound `(): IteratorAlias` was not satisfied + --> $DIR/issue-108132-unmet-trait-alias-bound-on-generic-impl.rs:9:9 + | +LL | impl Foo { + | ^^^^^^^^^^^^^ ------ + | | + | unsatisfied trait bound introduced here + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0599`. -- cgit 1.4.1-3-g733a5 From 55d449fe0ac07f1462bd62e062054cde310e7883 Mon Sep 17 00:00:00 2001 From: Alan Egerton Date: Thu, 16 Feb 2023 21:55:53 +0000 Subject: Clarify `DerivedObligationCause` may hold alias id --- .../rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs | 10 +++++----- compiler/rustc_hir_typeck/src/method/probe.rs | 2 +- compiler/rustc_hir_typeck/src/method/suggest.rs | 2 +- compiler/rustc_infer/src/traits/util.rs | 2 +- compiler/rustc_middle/src/traits/mod.rs | 6 +++++- .../src/traits/error_reporting/suggestions.rs | 2 +- .../rustc_trait_selection/src/traits/select/confirmation.rs | 2 +- compiler/rustc_trait_selection/src/traits/select/mod.rs | 2 +- 8 files changed, 16 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs index d13d8ff8270..0aa5b075d19 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs @@ -477,14 +477,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // This is the "trait" (meaning, the predicate "proved" by this `impl`) which provides the `Self` type we care about. // For the purposes of this function, we hope that it is a `struct` type, and that our current `expr` is a literal of // that struct type. - let impl_trait_self_ref = if self.tcx.is_trait_alias(obligation.impl_def_id) { + let impl_trait_self_ref = if self.tcx.is_trait_alias(obligation.impl_or_alias_def_id) { self.tcx.mk_trait_ref( - obligation.impl_def_id, - ty::InternalSubsts::identity_for_item(self.tcx, obligation.impl_def_id), + obligation.impl_or_alias_def_id, + ty::InternalSubsts::identity_for_item(self.tcx, obligation.impl_or_alias_def_id), ) } else { self.tcx - .impl_trait_ref(obligation.impl_def_id) + .impl_trait_ref(obligation.impl_or_alias_def_id) .map(|impl_def| impl_def.skip_binder()) // It is possible that this is absent. In this case, we make no progress. .ok_or(expr)? @@ -494,7 +494,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let impl_self_ty: Ty<'tcx> = impl_trait_self_ref.self_ty(); let impl_predicates: ty::GenericPredicates<'tcx> = - self.tcx.predicates_of(obligation.impl_def_id); + self.tcx.predicates_of(obligation.impl_or_alias_def_id); let Some(impl_predicate_index) = obligation.impl_def_predicate_index else { // We don't have the index, so we can only guess. return Err(expr); diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index a35fa008a95..a805dad062e 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -1576,7 +1576,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { traits::ImplDerivedObligation(Box::new( traits::ImplDerivedObligationCause { derived, - impl_def_id, + impl_or_alias_def_id: impl_def_id, impl_def_predicate_index: None, span, }, diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 68d2b9c6428..ef30cd55c0e 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -616,7 +616,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ObligationCauseCode::ImplDerivedObligation(data) if matches!(p.kind().skip_binder(), ty::PredicateKind::Clause(_)) => { - Some((p, parent, data.impl_def_id, data)) + Some((p, parent, data.impl_or_alias_def_id, data)) } _ => None, }) diff --git a/compiler/rustc_infer/src/traits/util.rs b/compiler/rustc_infer/src/traits/util.rs index e617eb68d47..68b39c5f00f 100644 --- a/compiler/rustc_infer/src/traits/util.rs +++ b/compiler/rustc_infer/src/traits/util.rs @@ -158,7 +158,7 @@ impl<'tcx> Elaborator<'tcx> { traits::ImplDerivedObligation(Box::new( traits::ImplDerivedObligationCause { derived, - impl_def_id: data.def_id(), + impl_or_alias_def_id: data.def_id(), impl_def_predicate_index: Some(index), span, }, diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index c528929e756..6231dd9b6f5 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -474,7 +474,11 @@ pub enum WellFormedLoc { #[derive(TypeVisitable, TypeFoldable)] pub struct ImplDerivedObligationCause<'tcx> { pub derived: DerivedObligationCause<'tcx>, - pub impl_def_id: DefId, + /// The `DefId` of the `impl` that gave rise to the `derived` obligation. + /// If the `derived` obligation arose from a trait alias, which conceptually has a synthetic impl, + /// then this will be the `DefId` of that trait alias. Care should therefore be taken to handle + /// that exceptional case where appropriate. + pub impl_or_alias_def_id: DefId, /// The index of the derived predicate in the parent impl's predicates. pub impl_def_predicate_index: Option, pub span: Span, diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index 8041066d5d5..9f4adb44b93 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -3143,7 +3143,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { parent_trait_pred.print_modifiers_and_trait_path() ); let mut is_auto_trait = false; - match self.tcx.hir().get_if_local(data.impl_def_id) { + match self.tcx.hir().get_if_local(data.impl_or_alias_def_id) { Some(Node::Item(hir::Item { kind: hir::ItemKind::Trait(is_auto, ..), ident, diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 9770813e86d..0167f402610 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -1189,7 +1189,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let cause = obligation.derived_cause(|derived| { ImplDerivedObligation(Box::new(ImplDerivedObligationCause { derived, - impl_def_id, + impl_or_alias_def_id: impl_def_id, impl_def_predicate_index: None, span: obligation.cause.span, })) diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 27feedc48be..26f869ac1fe 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -2657,7 +2657,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let cause = cause.clone().derived_cause(parent_trait_pred, |derived| { ImplDerivedObligation(Box::new(ImplDerivedObligationCause { derived, - impl_def_id: def_id, + impl_or_alias_def_id: def_id, impl_def_predicate_index: Some(index), span, })) -- cgit 1.4.1-3-g733a5