Skip to content

Add a new mismatched-lifetime-syntaxes lint #138677

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1405,7 +1405,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
};
let span = self.tcx.sess.source_map().start_point(t.span).shrink_to_hi();
let region = Lifetime { ident: Ident::new(kw::UnderscoreLifetime, span), id };
(region, LifetimeSyntax::Hidden)
(region, LifetimeSyntax::Implicit)
}
};
self.lower_lifetime(&region, LifetimeSource::Reference, syntax)
Expand Down Expand Up @@ -1789,7 +1789,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
id,
Ident::new(kw::UnderscoreLifetime, span),
LifetimeSource::Path { angle_brackets },
LifetimeSyntax::Hidden,
LifetimeSyntax::Implicit,
)
}

Expand Down Expand Up @@ -2421,7 +2421,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
Ident::new(kw::UnderscoreLifetime, self.lower_span(span)),
hir::LifetimeKind::ImplicitObjectLifetimeDefault,
LifetimeSource::Other,
LifetimeSyntax::Hidden,
LifetimeSyntax::Implicit,
);
debug!("elided_dyn_bound: r={:?}", r);
self.arena.alloc(r)
Expand Down
7 changes: 1 addition & 6 deletions compiler/rustc_hir/src/def.rs
Original file line number Diff line number Diff line change
Expand Up @@ -842,12 +842,7 @@ pub enum LifetimeRes {
/// late resolution. Those lifetimes will be inferred by typechecking.
Infer,
/// `'static` lifetime.
Static {
/// We do not want to emit `elided_named_lifetimes`
/// when we are inside of a const item or a static,
/// because it would get too annoying.
suppress_elision_warning: bool,
},
Static,
/// Resolution failure.
Error,
/// HACK: This is used to recover the NodeId of an elided lifetime.
Expand Down
74 changes: 35 additions & 39 deletions compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,13 @@ pub enum LifetimeSource {
#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
pub enum LifetimeSyntax {
/// E.g. `&Type`, `ContainsLifetime`
Hidden,
Implicit,

/// E.g. `&'_ Type`, `ContainsLifetime<'_>`, `impl Trait + '_`, `impl Trait + use<'_>`
Anonymous,
ExplicitAnonymous,

/// E.g. `&'a Type`, `ContainsLifetime<'a>`, `impl Trait + 'a`, `impl Trait + use<'a>`
Named,
ExplicitBound,
}

impl From<Ident> for LifetimeSyntax {
Expand All @@ -88,10 +88,10 @@ impl From<Ident> for LifetimeSyntax {
if name == kw::Empty {
unreachable!("A lifetime name should never be empty");
} else if name == kw::UnderscoreLifetime {
LifetimeSyntax::Anonymous
LifetimeSyntax::ExplicitAnonymous
} else {
debug_assert!(name.as_str().starts_with('\''));
LifetimeSyntax::Named
LifetimeSyntax::ExplicitBound
}
}
}
Expand All @@ -102,48 +102,48 @@ impl From<Ident> for LifetimeSyntax {
///
/// ```
/// #[repr(C)]
/// struct S<'a>(&'a u32); // res=Param, name='a, source=Reference, syntax=Named
/// struct S<'a>(&'a u32); // res=Param, name='a, source=Reference, syntax=ExplicitBound
/// unsafe extern "C" {
/// fn f1(s: S); // res=Param, name='_, source=Path, syntax=Hidden
/// fn f2(s: S<'_>); // res=Param, name='_, source=Path, syntax=Anonymous
/// fn f3<'a>(s: S<'a>); // res=Param, name='a, source=Path, syntax=Named
/// fn f1(s: S); // res=Param, name='_, source=Path, syntax=Implicit
/// fn f2(s: S<'_>); // res=Param, name='_, source=Path, syntax=ExplicitAnonymous
/// fn f3<'a>(s: S<'a>); // res=Param, name='a, source=Path, syntax=ExplicitBound
/// }
///
/// struct St<'a> { x: &'a u32 } // res=Param, name='a, source=Reference, syntax=Named
/// struct St<'a> { x: &'a u32 } // res=Param, name='a, source=Reference, syntax=ExplicitBound
/// fn f() {
/// _ = St { x: &0 }; // res=Infer, name='_, source=Path, syntax=Hidden
/// _ = St::<'_> { x: &0 }; // res=Infer, name='_, source=Path, syntax=Anonymous
/// _ = St { x: &0 }; // res=Infer, name='_, source=Path, syntax=Implicit
/// _ = St::<'_> { x: &0 }; // res=Infer, name='_, source=Path, syntax=ExplicitAnonymous
/// }
///
/// struct Name<'a>(&'a str); // res=Param, name='a, source=Reference, syntax=Named
/// const A: Name = Name("a"); // res=Static, name='_, source=Path, syntax=Hidden
/// const B: &str = ""; // res=Static, name='_, source=Reference, syntax=Hidden
/// static C: &'_ str = ""; // res=Static, name='_, source=Reference, syntax=Anonymous
/// static D: &'static str = ""; // res=Static, name='static, source=Reference, syntax=Named
/// struct Name<'a>(&'a str); // res=Param, name='a, source=Reference, syntax=ExplicitBound
/// const A: Name = Name("a"); // res=Static, name='_, source=Path, syntax=Implicit
/// const B: &str = ""; // res=Static, name='_, source=Reference, syntax=Implicit
/// static C: &'_ str = ""; // res=Static, name='_, source=Reference, syntax=ExplicitAnonymous
/// static D: &'static str = ""; // res=Static, name='static, source=Reference, syntax=ExplicitBound
///
/// trait Tr {}
/// fn tr(_: Box<dyn Tr>) {} // res=ImplicitObjectLifetimeDefault, name='_, source=Other, syntax=Hidden
/// fn tr(_: Box<dyn Tr>) {} // res=ImplicitObjectLifetimeDefault, name='_, source=Other, syntax=Implicit
///
/// fn capture_outlives<'a>() ->
/// impl FnOnce() + 'a // res=Param, ident='a, source=OutlivesBound, syntax=Named
/// impl FnOnce() + 'a // res=Param, ident='a, source=OutlivesBound, syntax=ExplicitBound
/// {
/// || {}
/// }
///
/// fn capture_precise<'a>() ->
/// impl FnOnce() + use<'a> // res=Param, ident='a, source=PreciseCapturing, syntax=Named
/// impl FnOnce() + use<'a> // res=Param, ident='a, source=PreciseCapturing, syntax=ExplicitBound
/// {
/// || {}
/// }
///
/// // (commented out because these cases trigger errors)
/// // struct S1<'a>(&'a str); // res=Param, name='a, source=Reference, syntax=Named
/// // struct S2(S1); // res=Error, name='_, source=Path, syntax=Hidden
/// // struct S3(S1<'_>); // res=Error, name='_, source=Path, syntax=Anonymous
/// // struct S4(S1<'a>); // res=Error, name='a, source=Path, syntax=Named
/// // struct S1<'a>(&'a str); // res=Param, name='a, source=Reference, syntax=ExplicitBound
/// // struct S2(S1); // res=Error, name='_, source=Path, syntax=Implicit
/// // struct S3(S1<'_>); // res=Error, name='_, source=Path, syntax=ExplicitAnonymous
/// // struct S4(S1<'a>); // res=Error, name='a, source=Path, syntax=ExplicitBound
/// ```
///
/// Some combinations that cannot occur are `LifetimeSyntax::Hidden` with
/// Some combinations that cannot occur are `LifetimeSyntax::Implicit` with
/// `LifetimeSource::OutlivesBound` or `LifetimeSource::PreciseCapturing`
/// — there's no way to "elide" these lifetimes.
#[derive(Debug, Copy, Clone, HashStable_Generic)]
Expand Down Expand Up @@ -206,7 +206,7 @@ impl ParamName {
}
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable_Generic)]
pub enum LifetimeKind {
/// User-given names or fresh (synthetic) names.
Param(LocalDefId),
Expand Down Expand Up @@ -287,12 +287,8 @@ impl Lifetime {
self.ident.name == kw::UnderscoreLifetime
}

pub fn is_syntactically_hidden(&self) -> bool {
matches!(self.syntax, LifetimeSyntax::Hidden)
}

pub fn is_syntactically_anonymous(&self) -> bool {
matches!(self.syntax, LifetimeSyntax::Anonymous)
pub fn is_implicit(&self) -> bool {
matches!(self.syntax, LifetimeSyntax::Implicit)
}

pub fn is_static(&self) -> bool {
Expand All @@ -307,28 +303,28 @@ impl Lifetime {

match (self.syntax, self.source) {
// The user wrote `'a` or `'_`.
(Named | Anonymous, _) => (self.ident.span, format!("{new_lifetime}")),
(ExplicitBound | ExplicitAnonymous, _) => (self.ident.span, format!("{new_lifetime}")),

// The user wrote `Path<T>`, and omitted the `'_,`.
(Hidden, Path { angle_brackets: AngleBrackets::Full }) => {
(Implicit, Path { angle_brackets: AngleBrackets::Full }) => {
(self.ident.span, format!("{new_lifetime}, "))
}

// The user wrote `Path<>`, and omitted the `'_`..
(Hidden, Path { angle_brackets: AngleBrackets::Empty }) => {
(Implicit, Path { angle_brackets: AngleBrackets::Empty }) => {
(self.ident.span, format!("{new_lifetime}"))
}

// The user wrote `Path` and omitted the `<'_>`.
(Hidden, Path { angle_brackets: AngleBrackets::Missing }) => {
(Implicit, Path { angle_brackets: AngleBrackets::Missing }) => {
(self.ident.span.shrink_to_hi(), format!("<{new_lifetime}>"))
}

// The user wrote `&type` or `&mut type`.
(Hidden, Reference) => (self.ident.span, format!("{new_lifetime} ")),
(Implicit, Reference) => (self.ident.span, format!("{new_lifetime} ")),

(Hidden, source) => {
unreachable!("can't suggest for a hidden lifetime of {source:?}")
(Implicit, source) => {
unreachable!("can't suggest for a implicit lifetime of {source:?}")
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir/src/hir/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ fn trait_object_roundtrips_impl(syntax: TraitObjectSyntax) {
ident: Ident::new(sym::name, DUMMY_SP),
kind: LifetimeKind::Static,
source: LifetimeSource::Other,
syntax: LifetimeSyntax::Hidden,
syntax: LifetimeSyntax::Implicit,
};
let unambig = TyKind::TraitObject::<'_, ()>(&[], TaggedRef::new(&lt, syntax));
let unambig_to_ambig = unsafe { std::mem::transmute::<_, TyKind<'_, AmbigArg>>(unambig) };
Expand Down
27 changes: 22 additions & 5 deletions compiler/rustc_lint/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -251,11 +251,6 @@ lint_duplicate_macro_attribute =

lint_duplicate_matcher_binding = duplicate matcher binding

lint_elided_named_lifetime = elided lifetime has a name
.label_elided = this elided lifetime gets resolved as `{$name}`
.label_named = lifetime `{$name}` declared here
.suggestion = consider specifying it explicitly

lint_enum_intrinsics_mem_discriminant =
the return value of `mem::discriminant` is unspecified when called with a non-enum type
.note = the argument to `discriminant` should be a reference to an enum, but it was passed a reference to a `{$ty_param}`, which is not an enum
Expand Down Expand Up @@ -512,6 +507,28 @@ lint_metavariable_still_repeating = variable `{$name}` is still repeating at thi

lint_metavariable_wrong_operator = meta-variable repeats with different Kleene operator

lint_mismatched_lifetime_syntaxes =
lifetime flowing from input to output with different syntax
.label_mismatched_lifetime_syntaxes_inputs =
{$n_inputs ->
[one] this lifetime flows
*[other] these lifetimes flow
} to the output
.label_mismatched_lifetime_syntaxes_outputs =
the elided {$n_outputs ->
[one] lifetime gets
*[other] lifetimes get
} resolved as `{$lifetime_name}`

lint_mismatched_lifetime_syntaxes_suggestion_explicit =
one option is to consistently use `{$lifetime_name}`

lint_mismatched_lifetime_syntaxes_suggestion_implicit =
one option is to consistently hide the lifetime

lint_mismatched_lifetime_syntaxes_suggestion_mixed =
one option is to hide the lifetime for references and use the anonymous lifetime for paths

lint_missing_fragment_specifier = missing fragment specifier

lint_missing_unsafe_on_extern = extern blocks should be unsafe
Expand Down
17 changes: 3 additions & 14 deletions compiler/rustc_lint/src/early/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ use rustc_errors::{
use rustc_middle::middle::stability;
use rustc_middle::ty::TyCtxt;
use rustc_session::Session;
use rustc_session::lint::{BuiltinLintDiag, ElidedLifetimeResolution};
use rustc_span::{BytePos, kw};
use rustc_session::lint::BuiltinLintDiag;
use rustc_span::BytePos;
use tracing::debug;

use crate::lints::{self, ElidedNamedLifetime};
use crate::lints;

mod check_cfg;

Expand Down Expand Up @@ -450,16 +450,5 @@ pub(super) fn decorate_lint(
BuiltinLintDiag::UnexpectedBuiltinCfg { cfg, cfg_name, controlled_by } => {
lints::UnexpectedBuiltinCfg { cfg, cfg_name, controlled_by }.decorate_lint(diag)
}
BuiltinLintDiag::ElidedNamedLifetimes { elided: (span, kind), resolution } => {
match resolution {
ElidedLifetimeResolution::Static => {
ElidedNamedLifetime { span, kind, name: kw::StaticLifetime, declaration: None }
}
ElidedLifetimeResolution::Param(name, declaration) => {
ElidedNamedLifetime { span, kind, name, declaration: Some(declaration) }
}
}
.decorate_lint(diag)
}
}
}
4 changes: 4 additions & 0 deletions compiler/rustc_lint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ mod invalid_from_utf8;
mod late;
mod let_underscore;
mod levels;
mod lifetime_style;
mod lints;
mod macro_expr_fragment_specifier_2024_migration;
mod map_unit_fn;
Expand Down Expand Up @@ -98,6 +99,7 @@ use impl_trait_overcaptures::ImplTraitOvercaptures;
use internal::*;
use invalid_from_utf8::*;
use let_underscore::*;
use lifetime_style::*;
use macro_expr_fragment_specifier_2024_migration::*;
use map_unit_fn::*;
use multiple_supertrait_upcastable::*;
Expand Down Expand Up @@ -246,6 +248,7 @@ late_lint_methods!(
IfLetRescope: IfLetRescope::default(),
StaticMutRefs: StaticMutRefs,
UnqualifiedLocalImports: UnqualifiedLocalImports,
LifetimeStyle: LifetimeStyle,
]
]
);
Expand Down Expand Up @@ -353,6 +356,7 @@ fn register_builtins(store: &mut LintStore) {
store.register_renamed("unused_tuple_struct_fields", "dead_code");
store.register_renamed("static_mut_ref", "static_mut_refs");
store.register_renamed("temporary_cstring_as_ptr", "dangling_pointers_from_temporaries");
store.register_renamed("elided_named_lifetimes", "mismatched_lifetime_syntaxes");

// These were moved to tool lints, but rustc still sees them when compiling normally, before
// tool lints are registered, so `check_tool_name_for_backwards_compat` doesn't work. Use
Expand Down
Loading
Loading