Skip to content

Commit a055643

Browse files
authored
Merge pull request #19550 from Veykril/push-rsskztqzwuzk
refactor: Turn `LifetimeRef` into an enum
2 parents f4747f2 + 0721214 commit a055643

File tree

8 files changed

+104
-87
lines changed

8 files changed

+104
-87
lines changed

crates/hir-def/src/expr_store/lower.rs

+19-10
Original file line numberDiff line numberDiff line change
@@ -544,13 +544,19 @@ impl ExprCollector<'_> {
544544
}
545545

546546
pub fn lower_lifetime_ref(&mut self, lifetime: ast::Lifetime) -> LifetimeRef {
547-
LifetimeRef::new(&lifetime)
547+
// FIXME: Keyword check?
548+
match &*lifetime.text() {
549+
"" | "'" => LifetimeRef::Error,
550+
"'static" => LifetimeRef::Static,
551+
"'_" => LifetimeRef::Placeholder,
552+
text => LifetimeRef::Named(Name::new_lifetime(text)),
553+
}
548554
}
549555

550556
pub fn lower_lifetime_ref_opt(&mut self, lifetime: Option<ast::Lifetime>) -> LifetimeRef {
551557
match lifetime {
552-
Some(lifetime) => LifetimeRef::new(&lifetime),
553-
None => LifetimeRef::missing(),
558+
Some(lifetime) => self.lower_lifetime_ref(lifetime),
559+
None => LifetimeRef::Placeholder,
554560
}
555561
}
556562

@@ -590,7 +596,7 @@ impl ExprCollector<'_> {
590596
}
591597
ast::Type::RefType(inner) => {
592598
let inner_ty = self.lower_type_ref_opt(inner.ty(), impl_trait_lower_fn);
593-
let lifetime = inner.lifetime().map(|lt| LifetimeRef::new(&lt));
599+
let lifetime = inner.lifetime().map(|lt| self.lower_lifetime_ref(lt));
594600
let mutability = Mutability::from_mutable(inner.mut_token().is_some());
595601
TypeRef::Reference(Box::new(RefType { ty: inner_ty, lifetime, mutability }))
596602
}
@@ -824,7 +830,7 @@ impl ExprCollector<'_> {
824830
}
825831
ast::GenericArg::LifetimeArg(lifetime_arg) => {
826832
if let Some(lifetime) = lifetime_arg.lifetime() {
827-
let lifetime_ref = LifetimeRef::new(&lifetime);
833+
let lifetime_ref = self.lower_lifetime_ref(lifetime);
828834
args.push(GenericArg::Lifetime(lifetime_ref))
829835
}
830836
}
@@ -911,7 +917,7 @@ impl ExprCollector<'_> {
911917
let lt_refs = match for_type.generic_param_list() {
912918
Some(gpl) => gpl
913919
.lifetime_params()
914-
.flat_map(|lp| lp.lifetime().map(|lt| Name::new_lifetime(&lt)))
920+
.flat_map(|lp| lp.lifetime().map(|lt| Name::new_lifetime(&lt.text())))
915921
.collect(),
916922
None => Box::default(),
917923
};
@@ -932,14 +938,14 @@ impl ExprCollector<'_> {
932938
gal.use_bound_generic_args()
933939
.map(|p| match p {
934940
ast::UseBoundGenericArg::Lifetime(l) => {
935-
UseArgRef::Lifetime(LifetimeRef::new(&l))
941+
UseArgRef::Lifetime(self.lower_lifetime_ref(l))
936942
}
937943
ast::UseBoundGenericArg::NameRef(n) => UseArgRef::Name(n.as_name()),
938944
})
939945
.collect(),
940946
),
941947
ast::TypeBoundKind::Lifetime(lifetime) => {
942-
TypeBound::Lifetime(LifetimeRef::new(&lifetime))
948+
TypeBound::Lifetime(self.lower_lifetime_ref(lifetime))
943949
}
944950
}
945951
}
@@ -2491,7 +2497,10 @@ impl ExprCollector<'_> {
24912497

24922498
fn collect_label(&mut self, ast_label: ast::Label) -> LabelId {
24932499
let label = Label {
2494-
name: ast_label.lifetime().as_ref().map_or_else(Name::missing, Name::new_lifetime),
2500+
name: ast_label
2501+
.lifetime()
2502+
.as_ref()
2503+
.map_or_else(Name::missing, |lt| Name::new_lifetime(&lt.text())),
24952504
};
24962505
self.alloc_label(label, AstPtr::new(&ast_label))
24972506
}
@@ -2511,7 +2520,7 @@ impl ExprCollector<'_> {
25112520
(hygiene_id.lookup().parent(self.db), expansion.def)
25122521
})
25132522
};
2514-
let name = Name::new_lifetime(&lifetime);
2523+
let name = Name::new_lifetime(&lifetime.text());
25152524

25162525
for (rib_idx, rib) in self.label_ribs.iter().enumerate().rev() {
25172526
match &rib.kind {

crates/hir-def/src/expr_store/lower/generics.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -123,12 +123,14 @@ impl<'db, 'c> GenericParamsCollector<'db, 'c> {
123123
ast::GenericParam::LifetimeParam(lifetime_param) => {
124124
let lifetime_ref =
125125
self.expr_collector.lower_lifetime_ref_opt(lifetime_param.lifetime());
126-
let param = LifetimeParamData { name: lifetime_ref.name.clone() };
127-
let _idx = self.lifetimes.alloc(param);
128-
self.lower_bounds(
129-
lifetime_param.type_bound_list(),
130-
Either::Right(lifetime_ref),
131-
);
126+
if let LifetimeRef::Named(name) = &lifetime_ref {
127+
let param = LifetimeParamData { name: name.clone() };
128+
let _idx = self.lifetimes.alloc(param);
129+
self.lower_bounds(
130+
lifetime_param.type_bound_list(),
131+
Either::Right(lifetime_ref),
132+
);
133+
}
132134
}
133135
}
134136
}
@@ -151,7 +153,7 @@ impl<'db, 'c> GenericParamsCollector<'db, 'c> {
151153
.map(|lifetime_param| {
152154
lifetime_param
153155
.lifetime()
154-
.map_or_else(Name::missing, |lt| Name::new_lifetime(&lt))
156+
.map_or_else(Name::missing, |lt| Name::new_lifetime(&lt.text()))
155157
})
156158
.collect()
157159
});

crates/hir-def/src/expr_store/pretty.rs

+20-17
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ use crate::{
1919
},
2020
lang_item::LangItemTarget,
2121
signatures::{FnFlags, FunctionSignature, StructSignature},
22-
type_ref::{ConstRef, Mutability, TraitBoundModifier, TypeBound, UseArgRef},
22+
type_ref::{ConstRef, LifetimeRef, Mutability, TraitBoundModifier, TypeBound, UseArgRef},
2323
};
2424

2525
use super::*;
@@ -268,12 +268,9 @@ fn print_where_clauses(db: &dyn DefDatabase, generic_params: &GenericParams, p:
268268
}
269269
},
270270
WherePredicate::Lifetime { target, bound } => {
271-
w!(
272-
p,
273-
"{}: {}",
274-
target.name.display(db.upcast(), p.edition),
275-
bound.name.display(db.upcast(), p.edition)
276-
);
271+
p.print_lifetime_ref(target);
272+
w!(p, ": ");
273+
p.print_lifetime_ref(bound);
277274
}
278275
WherePredicate::ForLifetime { lifetimes, target, bound } => {
279276
w!(p, "for<");
@@ -1140,9 +1137,7 @@ impl Printer<'_> {
11401137
match arg {
11411138
GenericArg::Type(ty) => self.print_type_ref(*ty),
11421139
GenericArg::Const(ConstRef { expr }) => self.print_expr(*expr),
1143-
GenericArg::Lifetime(lt) => {
1144-
w!(self, "{}", lt.name.display(self.db.upcast(), self.edition))
1145-
}
1140+
GenericArg::Lifetime(lt) => self.print_lifetime_ref(lt),
11461141
}
11471142
}
11481143

@@ -1155,6 +1150,17 @@ impl Printer<'_> {
11551150
}
11561151
}
11571152

1153+
pub(crate) fn print_lifetime_ref(&mut self, lt_ref: &LifetimeRef) {
1154+
match lt_ref {
1155+
LifetimeRef::Static => w!(self, "'static"),
1156+
LifetimeRef::Named(lt) => {
1157+
w!(self, "{}", lt.display(self.db.upcast(), self.edition))
1158+
}
1159+
LifetimeRef::Placeholder => w!(self, "'_"),
1160+
LifetimeRef::Error => w!(self, "'{{error}}"),
1161+
}
1162+
}
1163+
11581164
pub(crate) fn print_type_ref(&mut self, type_ref: TypeRefId) {
11591165
// FIXME: deduplicate with `HirDisplay` impl
11601166
match &self.store[type_ref] {
@@ -1187,7 +1193,8 @@ impl Printer<'_> {
11871193
};
11881194
w!(self, "&");
11891195
if let Some(lt) = &ref_.lifetime {
1190-
w!(self, "{} ", lt.name.display(self.db.upcast(), self.edition));
1196+
self.print_lifetime_ref(lt);
1197+
w!(self, " ");
11911198
}
11921199
w!(self, "{mtbl}");
11931200
self.print_type_ref(ref_.ty);
@@ -1269,9 +1276,7 @@ impl Printer<'_> {
12691276
);
12701277
self.print_path(&self.store[*path]);
12711278
}
1272-
TypeBound::Lifetime(lt) => {
1273-
w!(self, "{}", lt.name.display(self.db.upcast(), self.edition))
1274-
}
1279+
TypeBound::Lifetime(lt) => self.print_lifetime_ref(lt),
12751280
TypeBound::Use(args) => {
12761281
w!(self, "use<");
12771282
let mut first = true;
@@ -1283,9 +1288,7 @@ impl Printer<'_> {
12831288
UseArgRef::Name(it) => {
12841289
w!(self, "{}", it.display(self.db.upcast(), self.edition))
12851290
}
1286-
UseArgRef::Lifetime(it) => {
1287-
w!(self, "{}", it.name.display(self.db.upcast(), self.edition))
1288-
}
1291+
UseArgRef::Lifetime(it) => self.print_lifetime_ref(it),
12891292
}
12901293
}
12911294
w!(self, ">")

crates/hir-def/src/hir/type_ref.rs

+5-13
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ use std::fmt::Write;
66
use hir_expand::name::Name;
77
use intern::Symbol;
88
use la_arena::Idx;
9-
use syntax::ast;
109
use thin_vec::ThinVec;
1110

1211
use crate::{
@@ -145,18 +144,11 @@ const _: () = assert!(size_of::<TypeRef>() == 16);
145144
pub type TypeRefId = Idx<TypeRef>;
146145

147146
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
148-
pub struct LifetimeRef {
149-
pub name: Name,
150-
}
151-
152-
impl LifetimeRef {
153-
pub(crate) fn new(lifetime: &ast::Lifetime) -> Self {
154-
LifetimeRef { name: Name::new_lifetime(lifetime) }
155-
}
156-
157-
pub fn missing() -> LifetimeRef {
158-
LifetimeRef { name: Name::missing() }
159-
}
147+
pub enum LifetimeRef {
148+
Named(Name),
149+
Static,
150+
Placeholder,
151+
Error,
160152
}
161153

162154
#[derive(Clone, PartialEq, Eq, Hash, Debug)]

crates/hir-def/src/resolver.rs

+9-9
Original file line numberDiff line numberDiff line change
@@ -501,16 +501,16 @@ impl Resolver {
501501
}
502502

503503
pub fn resolve_lifetime(&self, lifetime: &LifetimeRef) -> Option<LifetimeNs> {
504-
if lifetime.name == sym::tick_static.clone() {
505-
return Some(LifetimeNs::Static);
504+
match lifetime {
505+
LifetimeRef::Static => Some(LifetimeNs::Static),
506+
LifetimeRef::Named(name) => self.scopes().find_map(|scope| match scope {
507+
Scope::GenericParams { def, params } => {
508+
params.find_lifetime_by_name(name, *def).map(LifetimeNs::LifetimeParam)
509+
}
510+
_ => None,
511+
}),
512+
LifetimeRef::Placeholder | LifetimeRef::Error => None,
506513
}
507-
508-
self.scopes().find_map(|scope| match scope {
509-
Scope::GenericParams { def, params } => {
510-
params.find_lifetime_by_name(&lifetime.name, *def).map(LifetimeNs::LifetimeParam)
511-
}
512-
_ => None,
513-
})
514514
}
515515

516516
/// Returns a set of names available in the current scope.

crates/hir-expand/src/name.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -114,11 +114,10 @@ impl Name {
114114
Name { symbol, ctx: () }
115115
}
116116

117-
pub fn new_lifetime(lt: &ast::Lifetime) -> Name {
118-
let text = lt.text();
119-
match text.strip_prefix("'r#") {
120-
Some(text) => Self::new_text(&format_smolstr!("'{text}")),
121-
None => Self::new_text(text.as_str()),
117+
pub fn new_lifetime(lt: &str) -> Name {
118+
match lt.strip_prefix("'r#") {
119+
Some(lt) => Self::new_text(&format_smolstr!("'{lt}")),
120+
None => Self::new_text(lt),
122121
}
123122
}
124123

crates/hir-ty/src/display.rs

+32-19
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@ use hir_def::{
2424
lang_item::{LangItem, LangItemTarget},
2525
nameres::DefMap,
2626
signatures::VariantFields,
27-
type_ref::{ConstRef, TraitBoundModifier, TypeBound, TypeRef, TypeRefId, UseArgRef},
27+
type_ref::{
28+
ConstRef, LifetimeRef, TraitBoundModifier, TypeBound, TypeRef, TypeRefId, UseArgRef,
29+
},
2830
visibility::Visibility,
2931
};
3032
use hir_expand::{mod_path::PathKind, name::Name};
@@ -2100,7 +2102,20 @@ impl<T: HirDisplayWithExpressionStore> HirDisplay for ExpressionStoreAdapter<'_,
21002102
T::hir_fmt(&self.0, f, self.1)
21012103
}
21022104
}
2103-
2105+
impl HirDisplayWithExpressionStore for LifetimeRef {
2106+
fn hir_fmt(
2107+
&self,
2108+
f: &mut HirFormatter<'_>,
2109+
_store: &ExpressionStore,
2110+
) -> Result<(), HirDisplayError> {
2111+
match self {
2112+
LifetimeRef::Named(name) => write!(f, "{}", name.display(f.db.upcast(), f.edition())),
2113+
LifetimeRef::Static => write!(f, "'static"),
2114+
LifetimeRef::Placeholder => write!(f, "'_"),
2115+
LifetimeRef::Error => write!(f, "'{{error}}"),
2116+
}
2117+
}
2118+
}
21042119
impl HirDisplayWithExpressionStore for TypeRefId {
21052120
fn hir_fmt(
21062121
&self,
@@ -2161,7 +2176,8 @@ impl HirDisplayWithExpressionStore for TypeRefId {
21612176
};
21622177
write!(f, "&")?;
21632178
if let Some(lifetime) = &ref_.lifetime {
2164-
write!(f, "{} ", lifetime.name.display(f.db.upcast(), f.edition()))?;
2179+
lifetime.hir_fmt(f, store)?;
2180+
write!(f, " ")?;
21652181
}
21662182
write!(f, "{mutability}")?;
21672183
ref_.ty.hir_fmt(f, store)?;
@@ -2255,9 +2271,7 @@ impl HirDisplayWithExpressionStore for TypeBound {
22552271
}
22562272
store[path].hir_fmt(f, store)
22572273
}
2258-
TypeBound::Lifetime(lifetime) => {
2259-
write!(f, "{}", lifetime.name.display(f.db.upcast(), f.edition()))
2260-
}
2274+
TypeBound::Lifetime(lifetime) => lifetime.hir_fmt(f, store),
22612275
TypeBound::ForLifetime(lifetimes, path) => {
22622276
let edition = f.edition();
22632277
write!(
@@ -2269,16 +2283,17 @@ impl HirDisplayWithExpressionStore for TypeBound {
22692283
}
22702284
TypeBound::Use(args) => {
22712285
let edition = f.edition();
2272-
write!(
2273-
f,
2274-
"use<{}> ",
2275-
args.iter()
2276-
.map(|it| match it {
2277-
UseArgRef::Lifetime(lt) => lt.name.display(f.db.upcast(), edition),
2278-
UseArgRef::Name(n) => n.display(f.db.upcast(), edition),
2279-
})
2280-
.format(", ")
2281-
)
2286+
let last = args.len().saturating_sub(1);
2287+
for (idx, arg) in args.iter().enumerate() {
2288+
match arg {
2289+
UseArgRef::Lifetime(lt) => lt.hir_fmt(f, store)?,
2290+
UseArgRef::Name(n) => write!(f, "{}", n.display(f.db.upcast(), edition))?,
2291+
}
2292+
if idx != last {
2293+
write!(f, ", ")?;
2294+
}
2295+
}
2296+
write!(f, "> ")
22822297
}
22832298
TypeBound::Error => write!(f, "{{error}}"),
22842299
}
@@ -2449,9 +2464,7 @@ impl HirDisplayWithExpressionStore for hir_def::expr_store::path::GenericArg {
24492464
// write!(f, "{}", c.display(f.db.upcast(), f.edition()))
24502465
write!(f, "<expr>")
24512466
}
2452-
hir_def::expr_store::path::GenericArg::Lifetime(lifetime) => {
2453-
write!(f, "{}", lifetime.name.display(f.db.upcast(), f.edition()))
2454-
}
2467+
hir_def::expr_store::path::GenericArg::Lifetime(lifetime) => lifetime.hir_fmt(f, store),
24552468
}
24562469
}
24572470
}

0 commit comments

Comments
 (0)