use crate::diagnostics::{ImportSuggestion, LabelSuggestion, TypoSuggestion};
use crate::late::lifetimes::{ElisionFailureInfo, LifetimeContext};
use crate::late::{AliasPossibility, LateResolutionVisitor, RibKind};
+use crate::late::{LifetimeBinderKind, LifetimeRibKind};
use crate::path_names_to_string;
-use crate::{Finalize, Module, ModuleKind, ModuleOrUniformRoot};
+use crate::{Module, ModuleKind, ModuleOrUniformRoot};
use crate::{PathResult, PathSource, Segment};
-use rustc_ast::visit::FnKind;
+use rustc_ast::visit::{FnCtxt, FnKind};
use rustc_ast::{
self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind,
NodeId, Path, Ty, TyKind,
use rustc_hir as hir;
use rustc_hir::def::Namespace::{self, *};
use rustc_hir::def::{self, CtorKind, CtorOf, DefKind};
-use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
+use rustc_hir::def_id::{DefId, CRATE_DEF_ID, LOCAL_CRATE};
use rustc_hir::PrimTy;
use rustc_session::parse::feature_err;
use rustc_span::edition::Edition;
}
}
-impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &'tcx hir::Generics<'tcx> {
+impl<'tcx> Into<MissingLifetimeSpot<'tcx>> for &&'tcx hir::Generics<'tcx> {
fn into(self) -> MissingLifetimeSpot<'tcx> {
MissingLifetimeSpot::Generics(self)
}
let is_enum_variant = &|res| matches!(res, Res::Def(DefKind::Variant, _));
// Make the base error.
+ struct BaseError<'a> {
+ msg: String,
+ fallback_label: String,
+ span: Span,
+ could_be_expr: bool,
+ suggestion: Option<(Span, &'a str, String)>,
+ }
let mut expected = source.descr_expected();
let path_str = Segment::names_to_string(path);
let item_str = path.last().unwrap().ident;
- let (base_msg, fallback_label, base_span, could_be_expr) = if let Some(res) = res {
- (
- format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
- format!("not a {}", expected),
+ let base_error = if let Some(res) = res {
+ BaseError {
+ msg: format!("expected {}, found {} `{}`", expected, res.descr(), path_str),
+ fallback_label: format!("not a {expected}"),
span,
- match res {
+ could_be_expr: match res {
Res::Def(DefKind::Fn, _) => {
// Verify whether this is a fn call or an Fn used as a type.
self.r
| Res::Local(_) => true,
_ => false,
},
- )
+ suggestion: None,
+ }
} else {
let item_span = path.last().unwrap().ident.span;
- let (mod_prefix, mod_str) = if path.len() == 1 {
- (String::new(), "this scope".to_string())
+ let (mod_prefix, mod_str, suggestion) = if path.len() == 1 {
+ debug!(?self.diagnostic_metadata.current_impl_items);
+ debug!(?self.diagnostic_metadata.current_function);
+ let suggestion = if let Some(items) = self.diagnostic_metadata.current_impl_items
+ && let Some((fn_kind, _)) = self.diagnostic_metadata.current_function
+ && self.current_trait_ref.is_none()
+ && let Some(FnCtxt::Assoc(_)) = fn_kind.ctxt()
+ && let Some(item) = items.iter().find(|i| {
+ if let AssocItemKind::Fn(fn_) = &i.kind
+ && !fn_.sig.decl.has_self()
+ && i.ident.name == item_str.name
+ {
+ debug!(?item_str.name);
+ debug!(?fn_.sig.decl.inputs);
+ return true
+ }
+ false
+ })
+ {
+ Some((
+ item_span,
+ "consider using the associated function",
+ format!("Self::{}", item.ident)
+ ))
+ } else {
+ None
+ };
+ (String::new(), "this scope".to_string(), suggestion)
} else if path.len() == 2 && path[0].ident.name == kw::PathRoot {
if self.r.session.edition() > Edition::Edition2015 {
// In edition 2018 onwards, the `::foo` syntax may only pull from the extern prelude
// which overrides all other expectations of item type
expected = "crate";
- (String::new(), "the list of imported crates".to_string())
+ (String::new(), "the list of imported crates".to_string(), None)
} else {
- (String::new(), "the crate root".to_string())
+ (String::new(), "the crate root".to_string(), None)
}
} else if path.len() == 2 && path[0].ident.name == kw::Crate {
- (String::new(), "the crate root".to_string())
+ (String::new(), "the crate root".to_string(), None)
} else {
let mod_path = &path[..path.len() - 1];
- let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), Finalize::No) {
+ let mod_prefix = match self.resolve_path(mod_path, Some(TypeNS), None) {
PathResult::Module(ModuleOrUniformRoot::Module(module)) => module.res(),
_ => None,
}
.map_or_else(String::new, |res| format!("{} ", res.descr()));
- (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)))
+ (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), None)
};
- (
- format!("cannot find {} `{}` in {}{}", expected, item_str, mod_prefix, mod_str),
- if path_str == "async" && expected.starts_with("struct") {
+ BaseError {
+ msg: format!("cannot find {expected} `{item_str}` in {mod_prefix}{mod_str}"),
+ fallback_label: if path_str == "async" && expected.starts_with("struct") {
"`async` blocks are only allowed in Rust 2018 or later".to_string()
} else {
- format!("not found in {}", mod_str)
+ format!("not found in {mod_str}")
},
- item_span,
- false,
- )
+ span: item_span,
+ could_be_expr: false,
+ suggestion,
+ }
};
let code = source.error_code(res.is_some());
- let mut err = self.r.session.struct_span_err_with_code(base_span, &base_msg, code);
+ let mut err =
+ self.r.session.struct_span_err_with_code(base_error.span, &base_error.msg, code);
+
+ if let Some(sugg) = base_error.suggestion {
+ err.span_suggestion_verbose(sugg.0, sugg.1, sugg.2, Applicability::MaybeIncorrect);
+ }
if let Some(span) = self.diagnostic_metadata.current_block_could_be_bare_struct_literal {
err.multipart_suggestion(
}
}
- self.detect_assoct_type_constraint_meant_as_path(base_span, &mut err);
+ self.detect_assoct_type_constraint_meant_as_path(base_error.span, &mut err);
// Emit special messages for unresolved `Self` and `self`.
if is_self_type(path, ns) {
}
})
.collect::<Vec<_>>();
- let crate_def_id = DefId::local(CRATE_DEF_INDEX);
+ let crate_def_id = CRATE_DEF_ID.to_def_id();
if candidates.is_empty() && is_expected(Res::Def(DefKind::Enum, crate_def_id)) {
let mut enum_candidates: Vec<_> = self
.r
source,
res,
&path_str,
- &fallback_label,
+ &base_error.fallback_label,
) {
// We do this to avoid losing a secondary span when we override the main error span.
self.r.add_typo_suggestion(&mut err, typo_sugg, ident_span);
}
}
- let is_macro = base_span.from_expansion() && base_span.desugaring_kind().is_none();
- if !self.type_ascription_suggestion(&mut err, base_span) {
+ let is_macro =
+ base_error.span.from_expansion() && base_error.span.desugaring_kind().is_none();
+ if !self.type_ascription_suggestion(&mut err, base_error.span) {
let mut fallback = false;
if let (
PathSource::Trait(AliasPossibility::Maybe),
let spans: Vec<Span> = bounds
.iter()
.map(|bound| bound.span())
- .filter(|&sp| sp != base_span)
+ .filter(|&sp| sp != base_error.span)
.collect();
let start_span = bounds.iter().map(|bound| bound.span()).next().unwrap();
multi_span.push_span_label(sp, msg);
}
multi_span.push_span_label(
- base_span,
+ base_error.span,
"expected this type to be a trait...".to_string(),
);
err.span_help(
);
if bounds.iter().all(|bound| match bound {
ast::GenericBound::Outlives(_) => true,
- ast::GenericBound::Trait(tr, _) => tr.span == base_span,
+ ast::GenericBound::Trait(tr, _) => tr.span == base_error.span,
}) {
let mut sugg = vec![];
- if base_span != start_span {
- sugg.push((start_span.until(base_span), String::new()));
+ if base_error.span != start_span {
+ sugg.push((start_span.until(base_error.span), String::new()));
}
- if base_span != end_span {
- sugg.push((base_span.shrink_to_hi().to(end_span), String::new()));
+ if base_error.span != end_span {
+ sugg.push((base_error.span.shrink_to_hi().to(end_span), String::new()));
}
err.multipart_suggestion(
fallback = true;
match self.diagnostic_metadata.current_let_binding {
Some((pat_sp, Some(ty_sp), None))
- if ty_sp.contains(base_span) && could_be_expr =>
+ if ty_sp.contains(base_error.span) && base_error.could_be_expr =>
{
err.span_suggestion_short(
pat_sp.between(ty_sp),
}
if fallback {
// Fallback label.
- err.span_label(base_span, fallback_label);
+ err.span_label(base_error.span, base_error.fallback_label);
}
}
if let Some(err_code) = &err.code {
if let crate::PathSource::TraitItem(_) = source {
let mod_path = &path[..path.len() - 1];
if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
- self.resolve_path(mod_path, None, Finalize::No)
+ self.resolve_path(mod_path, None, None)
{
let resolutions = self.r.resolutions(module).borrow();
let targets: Vec<_> =
ident: Symbol,
kind: &AssocItemKind,
) -> Option<Symbol> {
- let Some((module, _)) = &self.current_trait_ref else {
- return None;
- };
+ let (module, _) = self.current_trait_ref.as_ref()?;
if ident == kw::Underscore {
// We do nothing for `_`.
return None;
names.extend(extern_prelude.iter().flat_map(|(ident, _)| {
self.r.crate_loader.maybe_process_path_extern(ident.name).and_then(
|crate_id| {
- let crate_mod = Res::Def(
- DefKind::Mod,
- DefId { krate: crate_id, index: CRATE_DEF_INDEX },
- );
+ let crate_mod =
+ Res::Def(DefKind::Mod, crate_id.as_def_id());
if filter_fn(crate_mod) {
Some(TypoSuggestion::typo_from_res(
// Search in module.
let mod_path = &path[..path.len() - 1];
if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
- self.resolve_path(mod_path, Some(TypeNS), Finalize::No)
+ self.resolve_path(mod_path, Some(TypeNS), None)
{
self.r.add_module_candidates(module, &mut names, &filter_fn);
}
(*ident, within_scope)
})
}
-}
-impl<'tcx> LifetimeContext<'_, 'tcx> {
- crate fn report_missing_lifetime_specifiers(
+ crate fn emit_undeclared_lifetime_error(
&self,
- spans: Vec<Span>,
- count: usize,
- ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
- struct_span_err!(
- self.tcx.sess,
- spans,
- E0106,
- "missing lifetime specifier{}",
- pluralize!(count)
- )
- }
+ lifetime_ref: &ast::Lifetime,
+ outer_lifetime_ref: Option<Ident>,
+ ) {
+ debug_assert_ne!(lifetime_ref.ident.name, kw::UnderscoreLifetime);
+ let mut err = if let Some(outer) = outer_lifetime_ref {
+ let mut err = struct_span_err!(
+ self.r.session,
+ lifetime_ref.ident.span,
+ E0401,
+ "can't use generic parameters from outer item",
+ );
+ err.span_label(lifetime_ref.ident.span, "use of generic parameter from outer item");
+ err.span_label(outer.span, "lifetime parameter from outer item");
+ err
+ } else {
+ let mut err = struct_span_err!(
+ self.r.session,
+ lifetime_ref.ident.span,
+ E0261,
+ "use of undeclared lifetime name `{}`",
+ lifetime_ref.ident
+ );
+ err.span_label(lifetime_ref.ident.span, "undeclared lifetime");
+ err
+ };
+ let mut suggest_note = true;
- crate fn emit_undeclared_lifetime_error(&self, lifetime_ref: &hir::Lifetime) {
- let mut err = struct_span_err!(
- self.tcx.sess,
- lifetime_ref.span,
- E0261,
- "use of undeclared lifetime name `{}`",
- lifetime_ref
- );
- err.span_label(lifetime_ref.span, "undeclared lifetime");
- let mut suggested_spans = vec![];
- for missing in &self.missing_named_lifetime_spots {
- match missing {
- MissingLifetimeSpot::Generics(generics) => {
- let (span, sugg) = if let Some(param) = generics.params.iter().find(|p| {
- !matches!(
- p.kind,
- hir::GenericParamKind::Type { synthetic: true, .. }
- | hir::GenericParamKind::Lifetime {
- kind: hir::LifetimeParamKind::Elided,
- }
- )
- }) {
- (param.span.shrink_to_lo(), format!("{}, ", lifetime_ref))
- } else {
- (generics.span, format!("<{}>", lifetime_ref))
- };
- if suggested_spans.contains(&span) {
+ for rib in self.lifetime_ribs.iter().rev() {
+ match rib.kind {
+ LifetimeRibKind::Generics { parent: _, span, kind } => {
+ if !span.can_be_used_for_suggestions() && suggest_note {
+ suggest_note = false; // Avoid displaying the same help multiple times.
+ err.span_label(
+ span,
+ &format!(
+ "lifetime `{}` is missing in item created through this procedural macro",
+ lifetime_ref.ident,
+ ),
+ );
continue;
}
- suggested_spans.push(span);
- if span.can_be_used_for_suggestions() {
+
+ let higher_ranked = matches!(
+ kind,
+ LifetimeBinderKind::BareFnType
+ | LifetimeBinderKind::PolyTrait
+ | LifetimeBinderKind::WhereBound
+ );
+ let (span, sugg) = if span.is_empty() {
+ let sugg = format!(
+ "{}<{}>{}",
+ if higher_ranked { "for" } else { "" },
+ lifetime_ref.ident,
+ if higher_ranked { " " } else { "" },
+ );
+ (span, sugg)
+ } else {
+ let span =
+ self.r.session.source_map().span_through_char(span, '<').shrink_to_hi();
+ let sugg = format!("{}, ", lifetime_ref.ident);
+ (span, sugg)
+ };
+ if higher_ranked {
err.span_suggestion(
span,
- &format!("consider introducing lifetime `{}` here", lifetime_ref),
+ &format!(
+ "consider making the {} lifetime-generic with a new `{}` lifetime",
+ kind.descr(),
+ lifetime_ref
+ ),
+ sugg,
+ Applicability::MaybeIncorrect,
+ );
+ err.note_once(
+ "for more information on higher-ranked polymorphism, visit \
+ https://doc.rust-lang.org/nomicon/hrtb.html",
+ );
+ } else {
+ err.span_suggestion(
+ span,
+ &format!("consider introducing lifetime `{}` here", lifetime_ref.ident),
sugg,
Applicability::MaybeIncorrect,
);
}
}
- MissingLifetimeSpot::HigherRanked { span, span_type } => {
- err.span_suggestion(
- *span,
- &format!(
- "consider making the {} lifetime-generic with a new `{}` lifetime",
- span_type.descr(),
- lifetime_ref
- ),
- span_type.suggestion(&lifetime_ref.to_string()),
- Applicability::MaybeIncorrect,
- );
- err.note(
- "for more information on higher-ranked polymorphism, visit \
- https://doc.rust-lang.org/nomicon/hrtb.html",
- );
- }
+ LifetimeRibKind::Item => break,
_ => {}
}
}
+
err.emit();
}
+ crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &ast::Lifetime) {
+ struct_span_err!(
+ self.r.session,
+ lifetime_ref.ident.span,
+ E0771,
+ "use of non-static lifetime `{}` in const generic",
+ lifetime_ref.ident
+ )
+ .note(
+ "for more information, see issue #74052 \
+ <https://github.com/rust-lang/rust/issues/74052>",
+ )
+ .emit();
+ }
+
+ /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
+ /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
+ /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
+ crate fn maybe_emit_forbidden_non_static_lifetime_error(&self, lifetime_ref: &ast::Lifetime) {
+ let feature_active = self.r.session.features_untracked().generic_const_exprs;
+ if !feature_active {
+ feature_err(
+ &self.r.session.parse_sess,
+ sym::generic_const_exprs,
+ lifetime_ref.ident.span,
+ "a non-static lifetime is not allowed in a `const`",
+ )
+ .emit();
+ }
+ }
+}
+
+impl<'tcx> LifetimeContext<'_, 'tcx> {
+ crate fn report_missing_lifetime_specifiers(
+ &self,
+ spans: Vec<Span>,
+ count: usize,
+ ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
+ struct_span_err!(
+ self.tcx.sess,
+ spans,
+ E0106,
+ "missing lifetime specifier{}",
+ pluralize!(count)
+ )
+ }
+
/// Returns whether to add `'static` lifetime to the suggested lifetime list.
crate fn report_elision_failure(
&mut self,
}
}
- crate fn report_elided_lifetime_in_ty(&self, lifetime_refs: &[&hir::Lifetime]) {
- let Some(missing_lifetime) = lifetime_refs.iter().find(|lt| {
- lt.name == hir::LifetimeName::Implicit(true)
- }) else { return };
-
- let mut spans: Vec<_> = lifetime_refs.iter().map(|lt| lt.span).collect();
- spans.sort();
- let mut spans_dedup = spans.clone();
- spans_dedup.dedup();
- let spans_with_counts: Vec<_> = spans_dedup
- .into_iter()
- .map(|sp| (sp, spans.iter().filter(|nsp| *nsp == &sp).count()))
- .collect();
-
- self.tcx.struct_span_lint_hir(
- rustc_session::lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
- missing_lifetime.hir_id,
- spans,
- |lint| {
- let mut db = lint.build("hidden lifetime parameters in types are deprecated");
- self.add_missing_lifetime_specifiers_label(
- &mut db,
- spans_with_counts,
- &FxHashSet::from_iter([kw::UnderscoreLifetime]),
- Vec::new(),
- &[],
- );
- db.emit();
- },
- );
- }
-
- // FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
- // generics. We are disallowing this until we can decide on how we want to handle non-'static
- // lifetimes in const generics. See issue #74052 for discussion.
- crate fn emit_non_static_lt_in_const_generic_error(&self, lifetime_ref: &hir::Lifetime) {
- let mut err = struct_span_err!(
- self.tcx.sess,
- lifetime_ref.span,
- E0771,
- "use of non-static lifetime `{}` in const generic",
- lifetime_ref
- );
- err.note(
- "for more information, see issue #74052 \
- <https://github.com/rust-lang/rust/issues/74052>",
- );
- err.emit();
- }
-
crate fn is_trait_ref_fn_scope(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) -> bool {
if let def::Res::Def(_, did) = trait_ref.trait_ref.path.res {
if [
_ => unreachable!(),
}
}
-
- /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
- /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
- /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
- crate fn maybe_emit_forbidden_non_static_lifetime_error(
- &self,
- body_id: hir::BodyId,
- lifetime_ref: &'tcx hir::Lifetime,
- ) {
- let is_anon_const = matches!(
- self.tcx.def_kind(self.tcx.hir().body_owner_def_id(body_id)),
- hir::def::DefKind::AnonConst
- );
- let is_allowed_lifetime = matches!(
- lifetime_ref.name,
- hir::LifetimeName::Implicit(_)
- | hir::LifetimeName::Static
- | hir::LifetimeName::Underscore
- );
-
- if !self.tcx.lazy_normalization() && is_anon_const && !is_allowed_lifetime {
- feature_err(
- &self.tcx.sess.parse_sess,
- sym::generic_const_exprs,
- lifetime_ref.span,
- "a non-static lifetime is not allowed in a `const`",
- )
- .emit();
- }
- }
}