Debian Codegraph @

third_party/rust/diplomat_core/src/hir/lifetimes.rs

raw
1 //! Lifetime information for types.
2 #![allow(dead_code)]
3
4 use super::IdentBuf;
5 use crate::ast;
6 use core::fmt::Debug;
7 use core::hash::Hash;
8
9 use smallvec::{smallvec, SmallVec};
10 use std::borrow::{Borrow, Cow};
11
12 /// Convenience const representing the number of lifetimes a [`LifetimeEnv`]
13 /// can hold inline before needing to dynamically allocate.
14 pub(crate) const INLINE_NUM_LIFETIMES: usize = 4;
15
16 /// The lifetimes and bounds found on a method or type definition
17 #[derive(Debug)]
18 pub struct LifetimeEnv {
19 /// List of named lifetimes in scope of the method, and their bounds
20 nodes: SmallVec<[BoundedLifetime; INLINE_NUM_LIFETIMES]>,
21
22 /// Only relevant for method LifetimeEnvs (otherwise this is nodes.len())
23 ///
24 /// The number of named _and_ anonymous lifetimes in the method.
25 /// We store the sum since it represents the upper bound on what indices
26 /// are in range of the graph. If we make a [`Lifetimes`] with
27 /// `num_lifetimes` entries, then `Lifetime`s that convert into
28 /// `Lifetime`s will fall into this range, and we'll know that it's
29 /// a named lifetime if it's < `nodes.len()`, or that it's an anonymous
30 /// lifetime if it's < `num_lifetimes`. Otherwise, we'd have to make a
31 /// distinction in `Lifetime` about which context it's in.
32 num_lifetimes: usize,
33 }
34
35 impl LifetimeEnv {
36 /// Format a lifetime indexing this env for use in code
37 pub fn fmt_lifetime(&self, lt: impl Borrow<Lifetime>) -> Cow<str> {
38 // we use Borrow here so that this can be used in templates where there's autoborrowing
39 let lt = *lt.borrow();
40 if let Some(lt) = self.nodes.get(lt.0) {
41 Cow::from(lt.ident.as_str())
42 } else if lt.0 < self.num_lifetimes {
43 format!("anon_{}", lt.0 - self.nodes.len()).into()
44 } else {
45 panic!("Found out of range lifetime: Got {lt:?} for env with {} nodes and {} total lifetimes", self.nodes.len(), self.num_lifetimes);
46 }
47 }
48
49 /// Get an iterator of all lifetimes that this must live as long as (including itself)
50 /// with the first lifetime always being returned first
51
52 pub fn all_shorter_lifetimes(
53 &self,
54 lt: impl Borrow<Lifetime>,
55 ) -> impl Iterator<Item = Lifetime> + '_ {
56 // we use Borrow here so that this can be used in templates where there's autoborrowing
57 let lt = *lt.borrow();
58 // longer = true, since we are looking for lifetimes this is longer than
59 LifetimeTransitivityIterator::new(self, lt.0, false)
60 }
61
62 /// Same as all_shorter_lifetimes but the other way
63 pub fn all_longer_lifetimes(
64 &self,
65 lt: impl Borrow<Lifetime>,
66 ) -> impl Iterator<Item = Lifetime> + '_ {
67 // we use Borrow here so that this can be used in templates where there's autoborrowing
68 let lt = *lt.borrow();
69 LifetimeTransitivityIterator::new(self, lt.0, true)
70 }
71
72 // List all named and unnamed lifetimes
73 pub fn num_lifetimes(&self) -> usize {
74 self.num_lifetimes
75 }
76
77 pub fn all_lifetimes(&self) -> impl ExactSizeIterator<Item = Lifetime> {
78 (0..self.num_lifetimes()).map(Lifetime::new)
79 }
80
81 /// Get the bounds for a named lifetime (none for unnamed lifetimes)
82 pub(super) fn get_bounds(&self, named_lifetime: Lifetime) -> Option<&BoundedLifetime> {
83 self.nodes.get(named_lifetime.0)
84 }
85
86 /// Returns a new [`LifetimeEnv`].
87 pub(super) fn new(
88 nodes: SmallVec<[BoundedLifetime; INLINE_NUM_LIFETIMES]>,
89 num_lifetimes: usize,
90 ) -> Self {
91 Self {
92 nodes,
93 num_lifetimes,
94 }
95 }
96
97 /// Returns a fresh [`Lifetimes`] corresponding to `self`.
98 pub fn lifetimes(&self) -> Lifetimes {
99 let indices = (0..self.num_lifetimes)
100 .map(|index| MaybeStatic::NonStatic(Lifetime::new(index)))
101 .collect();
102
103 Lifetimes { indices }
104 }
105
106 /// Returns a new [`SubtypeLifetimeVisitor`], which can visit all reachable
107 /// lifetimes
108 pub fn subtype_lifetimes_visitor<F>(&self, visit_fn: F) -> SubtypeLifetimeVisitor<'_, F>
109 where
110 F: FnMut(Lifetime),
111 {
112 SubtypeLifetimeVisitor::new(self, visit_fn)
113 }
114 }
115
116 /// A lifetime in a [`LifetimeEnv`], which keeps track of which lifetimes it's
117 /// longer and shorter than.
118 ///
119 /// Invariant: for a BoundedLifetime found inside a LifetimeEnv, all short/long connections
120 /// should be bidirectional.
121 #[derive(Debug)]
122 pub(super) struct BoundedLifetime {
123 pub(super) ident: IdentBuf,
124 /// Lifetimes longer than this (not transitive)
125 ///
126 /// These are the inverse graph edges compared to `shorter`
127 pub(super) longer: SmallVec<[Lifetime; 2]>,
128 /// Lifetimes this is shorter than (not transitive)
129 ///
130 /// These match `'a: 'b + 'c` bounds
131 pub(super) shorter: SmallVec<[Lifetime; 2]>,
132 }
133
134 impl BoundedLifetime {
135 /// Returns a new [`BoundedLifetime`].
136 pub(super) fn new(
137 ident: IdentBuf,
138 longer: SmallVec<[Lifetime; 2]>,
139 shorter: SmallVec<[Lifetime; 2]>,
140 ) -> Self {
141 Self {
142 ident,
143 longer,
144 shorter,
145 }
146 }
147 }
148
149 /// Visit subtype lifetimes recursively, keeping track of which have already
150 /// been visited.
151 pub struct SubtypeLifetimeVisitor<'lt, F> {
152 lifetime_env: &'lt LifetimeEnv,
153 visited: SmallVec<[bool; INLINE_NUM_LIFETIMES]>,
154 visit_fn: F,
155 }
156
157 impl<'lt, F> SubtypeLifetimeVisitor<'lt, F>
158 where
159 F: FnMut(Lifetime),
160 {
161 fn new(lifetime_env: &'lt LifetimeEnv, visit_fn: F) -> Self {
162 Self {
163 lifetime_env,
164 visited: smallvec![false; lifetime_env.nodes.len()],
165 visit_fn,
166 }
167 }
168
169 /// Visit more sublifetimes. This method tracks which lifetimes have already
170 /// been visited, and uses this to not visit the same lifetime twice.
171 pub fn visit_subtypes(&mut self, method_lifetime: Lifetime) {
172 if let Some(visited @ false) = self.visited.get_mut(method_lifetime.0) {
173 *visited = true;
174
175 (self.visit_fn)(method_lifetime);
176
177 for longer in self.lifetime_env.nodes[method_lifetime.0].longer.iter() {
178 self.visit_subtypes(*longer)
179 }
180 } else {
181 debug_assert!(
182 method_lifetime.0 > self.lifetime_env.num_lifetimes,
183 "method lifetime has an internal index that's not in range of the lifetime env"
184 );
185 }
186 }
187 }
188
189 /// Wrapper type for `Lifetime` and `Lifetime`, indicating that it may
190 /// be the `'static` lifetime.
191 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
192 #[allow(clippy::exhaustive_enums)] // this will only ever have two variants
193 pub enum MaybeStatic<T> {
194 Static,
195 NonStatic(T),
196 }
197
198 impl<T> MaybeStatic<T> {
199 /// Maps the lifetime, if it's not the `'static` lifetime, to another
200 /// non-static lifetime.
201 pub(super) fn map_nonstatic<F, R>(self, f: F) -> MaybeStatic<R>
202 where
203 F: FnOnce(T) -> R,
204 {
205 match self {
206 MaybeStatic::Static => MaybeStatic::Static,
207 MaybeStatic::NonStatic(lifetime) => MaybeStatic::NonStatic(f(lifetime)),
208 }
209 }
210
211 /// Maps the lifetime, if it's not the `'static` lifetime, to a potentially
212 /// static lifetime.
213 pub(super) fn flat_map_nonstatic<R, F>(self, f: F) -> MaybeStatic<R>
214 where
215 F: FnOnce(T) -> MaybeStatic<R>,
216 {
217 match self {
218 MaybeStatic::Static => MaybeStatic::Static,
219 MaybeStatic::NonStatic(lifetime) => f(lifetime),
220 }
221 }
222 }
223
224 /// A lifetime that exists as part of a type name, struct signature, or method signature.
225 ///
226 /// This index only makes sense in the context of a surrounding type or method; since
227 /// this is essentially an index into that type/method's lifetime list.
228 #[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Debug)]
229 pub struct Lifetime(usize);
230
231 /// A set of lifetimes found on a type name, struct signature, or method signature
232 #[derive(Clone, Debug)]
233 pub struct Lifetimes {
234 indices: SmallVec<[MaybeStatic<Lifetime>; 2]>,
235 }
236
237 impl Lifetime {
238 pub(super) const fn new(index: usize) -> Self {
239 Self(index)
240 }
241 }
242
243 impl Lifetimes {
244 /// Returns an iterator over the contained [`Lifetime`]s.
245 pub fn lifetimes(&self) -> impl ExactSizeIterator<Item = MaybeStatic<Lifetime>> + '_ {
246 self.indices.iter().copied()
247 }
248
249 pub(super) fn as_slice(&self) -> &[MaybeStatic<Lifetime>] {
250 self.indices.as_slice()
251 }
252 }
253
254 impl Lifetime {
255 /// Returns a [`Lifetime`] from its AST counterparts.
256 pub(super) fn from_ast(named: &ast::NamedLifetime, lifetime_env: &ast::LifetimeEnv) -> Self {
257 let index = lifetime_env
258 .id(named)
259 .unwrap_or_else(|| panic!("lifetime `{named}` not found in lifetime env"));
260 Self::new(index)
261 }
262
263 /// Returns a new [`MaybeStatic<Lifetime>`] representing `self` in the
264 /// scope of the method that it appears in.
265 ///
266 /// For example, if we have some `Foo<'a>` type with a field `&'a Bar`, then
267 /// we can call this on the `'a` on the field. If `Foo` was `Foo<'static>`
268 /// in the method, then this will return `MaybeStatic::Static`. But if it
269 /// was `Foo<'b>`, then this will return `MaybeStatic::NonStatic` containing
270 /// the `Lifetime` corresponding to `'b`.
271 pub fn as_method_lifetime(self, method_lifetimes: &Lifetimes) -> MaybeStatic<Lifetime> {
272 method_lifetimes.indices[self.0]
273 }
274 }
275
276 impl Lifetimes {
277 pub(super) fn from_fn<F>(lifetimes: &[ast::Lifetime], lower_fn: F) -> Self
278 where
279 F: FnMut(&ast::Lifetime) -> MaybeStatic<Lifetime>,
280 {
281 Self {
282 indices: lifetimes.iter().map(lower_fn).collect(),
283 }
284 }
285
286 /// Append an additional lifetime. Used to tack on anon lifetimes
287 pub(super) fn append_lifetime(&mut self, lifetime: MaybeStatic<Lifetime>) {
288 self.indices.push(lifetime)
289 }
290
291 /// Returns a new [`Lifetimes`] representing the lifetimes in the scope
292 /// of the method this type appears in.
293 ///
294 /// # Examples
295 ///
296 /// ```rust
297 /// # struct Alice<'a>(&'a ());
298 /// # struct Bob<'b>(&'b ());
299 /// struct Foo<'a, 'b> {
300 /// alice: Alice<'a>,
301 /// bob: Bob<'b>,
302 /// }
303 ///
304 /// fn bar<'x, 'y>(arg: Foo<'x, 'y>) {}
305 /// ```
306 /// Here, `Foo` will have a [`Lifetimes`] containing `['a, 'b]`,
307 /// and `bar` will have a [`Lifetimes`] containing `{'x: 'x, 'y: 'y}`.
308 /// When we enter the scope of `Foo` as a type, we use this method to combine
309 /// the two to get a new [`Lifetimes`] representing the mapping from
310 /// lifetimes in `Foo`'s scope to lifetimes in `bar`s scope: `{'a: 'x, 'b: 'y}`.
311 ///
312 /// This tells us that `arg.alice` has lifetime `'x` in the method, and
313 /// that `arg.bob` has lifetime `'y`.
314 pub fn as_method_lifetimes(&self, method_lifetimes: &Lifetimes) -> Lifetimes {
315 let indices = self
316 .indices
317 .iter()
318 .map(|maybe_static_lt| {
319 maybe_static_lt.flat_map_nonstatic(|lt| lt.as_method_lifetime(method_lifetimes))
320 })
321 .collect();
322
323 Lifetimes { indices }
324 }
325 }
326
327 struct LifetimeTransitivityIterator<'env> {
328 env: &'env LifetimeEnv,
329 visited: Vec<bool>,
330 queue: Vec<usize>,
331 longer: bool,
332 }
333
334 impl<'env> LifetimeTransitivityIterator<'env> {
335 // Longer is whether we are looking for lifetimes longer or shorter than this
336 fn new(env: &'env LifetimeEnv, starting: usize, longer: bool) -> Self {
337 Self {
338 env,
339 visited: vec![false; env.num_lifetimes()],
340 queue: vec![starting],
341 longer,
342 }
343 }
344 }
345
346 impl<'env> Iterator for LifetimeTransitivityIterator<'env> {
347 type Item = Lifetime;
348
349 fn next(&mut self) -> Option<Lifetime> {
350 while let Some(next) = self.queue.pop() {
351 if self.visited[next] {
352 continue;
353 }
354 self.visited[next] = true;
355
356 if let Some(named) = self.env.nodes.get(next) {
357 let edge_dir = if self.longer {
358 &named.longer
359 } else {
360 &named.shorter
361 };
362 self.queue.extend(edge_dir.iter().map(|i| i.0));
363 }
364
365 return Some(Lifetime::new(next));
366 }
367 None
368 }
369 }
370
371 /// Convenience type for linking the lifetimes found at a type *use* site (e.g. `&'c Foo<'a, 'b>`)
372 /// with the lifetimes found at its *def* site (e.g. `struct Foo<'x, 'y>`).
373 ///
374 /// Construct this by calling `.linked_lifetimes()` on a StructPath or OpaquePath
375 pub struct LinkedLifetimes<'def, 'tcx> {
376 env: &'tcx LifetimeEnv,
377 self_lt: Option<MaybeStatic<Lifetime>>,
378 lifetimes: &'def Lifetimes,
379 }
380
381 impl<'def, 'tcx> LinkedLifetimes<'def, 'tcx> {
382 pub(crate) fn new(
383 env: &'tcx LifetimeEnv,
384 self_lt: Option<MaybeStatic<Lifetime>>,
385 lifetimes: &'def Lifetimes,
386 ) -> Self {
387 debug_assert_eq!(
388 lifetimes.lifetimes().len(),
389 env.all_lifetimes().len(),
390 "Should only link lifetimes between a type and its def"
391 );
392 Self {
393 env,
394 self_lt,
395 lifetimes,
396 }
397 }
398
399 /// Takes a lifetime at the def site and produces one at the use site
400 pub fn def_to_use(&self, def_lt: Lifetime) -> MaybeStatic<Lifetime> {
401 *self
402 .lifetimes
403 .as_slice()
404 .get(def_lt.0)
405 .expect("All def site lifetimes must be used!")
406 }
407
408 /// The lifetime env at the def site. Def lifetimes should be resolved
409 /// against this.
410 pub fn def_env(&self) -> &'tcx LifetimeEnv {
411 self.env
412 }
413
414 /// Link lifetimes from the use site to lifetimes from the def site, only including
415 /// lifetimes found at the def site.
416 ///
417 /// This will *not* include the self-lifetime, i.e. for an opaque use site `&'c Foo<'a, 'b>`
418 /// this will not include `'c` (but you can obtain it from [`Self::self_lifetime()`]))
419 ///
420 /// The return iterator returns pairs of (use_lt, def_lt), in order.
421 ///
422 /// This behaves identically to [`Self::lifetimes_all()`] for `LinkedLifetimes` constructed
423 /// from anything other than a borrowing opaque.
424 pub fn lifetimes_def_only(
425 &self,
426 ) -> impl Iterator<Item = (MaybeStatic<Lifetime>, Lifetime)> + '_ {
427 self.lifetimes.lifetimes().zip(self.env.all_lifetimes())
428 }
429
430 /// If there is a self-lifetime (e.g. `'c` on `&'c Foo<'a, 'b>`), return it. This lifetime
431 /// isn't found at the def site.
432 pub fn self_lifetime(&self) -> Option<MaybeStatic<Lifetime>> {
433 self.self_lt
434 }
435
436 /// Link lifetimes from the use site to lifetimes from the def site, including self lifetimes.
437 ///
438 /// This returns Options since self-lifetimes do not map to anything at the def site.
439 ///
440 /// The return iterator returns pairs of (use_lt, def_lt), in order, with the first entry potentially being
441 /// the self lifetime (which has a def_lt of None).
442 ///
443 /// This behaves identically to [`Self::lifetimes_all()`] for `LinkedLifetimes` constructed
444 /// from anything other than a borrowing opaque.
445 pub fn lifetimes_all(
446 &self,
447 ) -> impl Iterator<Item = (MaybeStatic<Lifetime>, Option<Lifetime>)> + '_ {
448 self.self_lt.iter().map(|i| (*i, None)).chain(
449 self.lifetimes
450 .lifetimes()
451 .zip(self.env.all_lifetimes().map(Some)),
452 )
453 }
454 }