Debian Codegraph @

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

raw
1 //! This module provides the functionality for lowering lifetimes from the AST
2 //! to the HIR, while simultaneously inferencing elided lifetimes.
3 //!
4 //! Full elision rules can be found in the [Nomicon].
5 //!
6 //! The key factor about lifetime elision is that all elision in the output of
7 //! the method (if there is any) corresponds to exactly one lifetime in the method
8 //! arguments, which may or may not be elided. Therefore, our task is to find this
9 //! potential lifetime first, so that if we encounter an elided lifetime while
10 //! lowering the output, we know which lifetime it corresponds to.
11 //!
12 //! # Unspoken Rules of Elision.
13 //!
14 //! Broadly speaking, the Nomicon defines the elision rules are such:
15 //! 1. If there's a `&self` or `&mut self`, the lifetime of that borrow
16 //! corresponds to elision in the output.
17 //! 2. Otherwise, if there's exactly one lifetime in the input, then that lifetime
18 //! corresponds to elision in the output.
19 //! 3. If neither of these cases hold, then the output cannot contain elision.
20 //!
21 //! What the Nomicon doesn't tell you is that there are weird corner cases around
22 //! using the `Self` type. Specifically, lifetimes in the `Self` type and in the
23 //! type of the `self` argument (optional) aren't considered when figuring out
24 //! which lifetime should correspond to elision in the output.
25 //!
26 //! Check out the following code:
27 //! ```compile_fail
28 //! struct Foo<'a>(&'a str);
29 //!
30 //! impl<'a> Foo<'a> {
31 //! fn get(self) -> &str { self.0 }
32 //! }
33 //! ```
34 //! This code will fail to compile because it doesn't look at the `'a` in the
35 //! `Foo<'a>`, which is what the type of `self` expands to. Therefore, it will
36 //! conclude that there's nothing for the output to borrow from.
37 //! This can be fixed by returning `&'a str` though. Many of the design
38 //! decisions in this module were made to be able to replicate this behavior.
39 //!
40 //! You may be asking "why would we care about rejecting code that rustc rejects
41 //! before it reaches us?" And the answer is this:
42 //! ```rust
43 //! # struct Foo<'a>(&'a str);
44 //! impl<'a> Foo<'a> {
45 //! fn get(self, s: &str) -> &str { s }
46 //! }
47 //! ```
48 //! This code is accepted by rustc, since it only considers the lifetime of `s`
49 //! when searching for a lifetime that corresponds to output elision. If we were
50 //! to naively look at all the lifetimes, we would see the lifetime in the `self`
51 //! argument and the lifetime of `s`, making us reject this method. Therefore, we
52 //! have to be extremely careful when traversing lifetimes, and make sure that
53 //! lifetimes of `Self` are lowered but _not_ considered for elision, while other
54 //! lifetimes are lowered while also being considered for elision.
55 //!
56 //! # Lowering and Inference
57 //!
58 //! Lowering and elision inference is broken into three distinct stages:
59 //! 1. Lowering the borrow in `&self` or `&mut self`, if there is one.
60 //! 2. Lowering lifetimes of other params.
61 //! 3. Lowering lifetimes of the output.
62 //!
63 //! Although each stage fundementally lowers lifetimes, they behave differently
64 //! when lowering elided lifetimes. Naturally, this module represents each stage
65 //! as a state in a state machine.
66 //!
67 //! The first state is represented by the [`SelfParamLifetimeLowerer`] type.
68 //! Since there is either zero or one occurrences of `&self` or `&mut self`, it
69 //! exposes the `.no_self_ref()` and `.lower_self_ref(lt)` methods respectively,
70 //! which consume the `SelfParamLifetimeLowerer` and return the next state,
71 //! [`ParamLifetimeLowerer`], as well as the lowered lifetime. The reason these
72 //! are two distinct types is that the lifetime in `&self` and `&mut self` takes
73 //! precedence over any other lifetimes in the input, so `.lower_self_ref(lt)`
74 //! tells the next state that the candidate lifetime is already found, and to
75 //! generate fresh anonymous lifetimes for any elided lifetimes.
76 //!
77 //! The second state is represented by the [`ParamLifetimeLowerer`] type.
78 //! It implements a helper trait, [`LifetimeLowerer`], which abstracts the lowering
79 //! of references and generic lifetimes. Internally, it wraps an [`ElisionSource`],
80 //! which acts as a state machine for tracking candidate lifetimes to correspond
81 //! to elision in the output. When a lifetime that's not in the type of the `self`
82 //! argument or in the expanded generics of the `Self` type is visited, this
83 //! state machine is potentially updated to another state. If the lifetime is
84 //! anonymous, it's added to the internal list of nodes that go into the final
85 //! [`LifetimeEnv`] after lowering. Once all the lifetimes in the input are
86 //! lowered, the `into_return_ltl()` method is called to transition into the
87 //! final state.
88 //!
89 //! The third and final state is represented by the [`ReturnLifetimeLowerer`] type.
90 //! Similar to `ParamLifetimeLowerer`, it also implements the [`LifetimeLowerer`]
91 //! helper trait. However, it differs from `ParamLifetimeLowerer` since instead
92 //! of potentially updating the internal `ElisionSource` when visiting a lifetime,
93 //! it instead reads from it when an elided lifetime occurs. Once all the output
94 //! lifetimes are lowered, `.finish()` is called to return the finalized
95 //! [`LifetimeEnv`].
96 //!
97 //! [Nomicon]: https://doc.rust-lang.org/nomicon/lifetime-elision.html
98
99 use super::lifetimes::{BoundedLifetime, Lifetime, LifetimeEnv, Lifetimes, MaybeStatic};
100 use super::LoweringContext;
101 use crate::ast;
102 use smallvec::SmallVec;
103
104 /// Lower [`ast::Lifetime`]s to [`Lifetime`]s.
105 ///
106 /// This helper traits allows the [`lower_type`] and [`lower_out_type`] methods
107 /// to abstractly lower lifetimes without concern for what sort of tracking
108 /// goes on. In particular, elision inference requires updating internal state
109 /// when visiting lifetimes in the input.
110 pub trait LifetimeLowerer {
111 /// Lowers an [`ast::Lifetime`].
112 fn lower_lifetime(&mut self, lifetime: &ast::Lifetime) -> MaybeStatic<Lifetime>;
113
114 /// Lowers a slice of [`ast::Lifetime`]s by calling
115 /// [`LifetimeLowerer::lower_lifetime`] repeatedly.
116 ///
117
118 /// `type_generics` is the full list of generics on the type definition of the type
119 /// this lifetimes list is found on (needed for generating anon lifetimes)
120 fn lower_lifetimes(
121 &mut self,
122 lifetimes: &[ast::Lifetime],
123 type_generics: &ast::LifetimeEnv,
124 ) -> Lifetimes {
125 let mut lifetimes = Lifetimes::from_fn(lifetimes, |lifetime| self.lower_lifetime(lifetime));
126
127 for _ in lifetimes.as_slice().len()..type_generics.nodes.len() {
128 lifetimes.append_lifetime(self.lower_lifetime(&ast::Lifetime::Anonymous))
129 }
130 lifetimes
131 }
132
133 /// Lowers a slice of [`ast::Lifetime`], where the strategy may vary depending
134 /// on whether or not the lifetimes are expanded from the `Self` type.
135 ///
136 /// The distinction between this and [`LifetimeLowerer::lower_lifetimes`] is
137 /// that if `Self` expands to a type with anonymous lifetimes like `Foo<'_>`,
138 /// then multiple instances of `Self` should expand to have the same anonymous
139 /// lifetime, and this lifetime can be cached inside of the `self` argument.
140 /// Additionally, elision inferences knows to not search inside the generics
141 /// of `Self` types for candidate lifetimes to correspond to elided lifetimes
142 /// in the output.
143 ///
144 /// `type_generics` is the full list of generics on the type definition of the type
145 /// this generics list is found on (needed for generating anon lifetimes)
146
147 fn lower_generics(
148 &mut self,
149 lifetimes: &[ast::Lifetime],
150 type_generics: &ast::LifetimeEnv,
151 is_self: bool,
152 ) -> Lifetimes;
153 }
154
155 /// A state machine for tracking which lifetime in a function's parameters
156 /// may correspond to elided lifetimes in the output.
157 #[derive(Copy, Clone)]
158 enum ElisionSource {
159 /// No borrows in the input, no elision.
160 NoBorrows,
161 /// `&self` or `&mut self`, elision allowed.
162 SelfParam(MaybeStatic<Lifetime>),
163 /// One param contains a borrow, elision allowed.
164 OneParam(MaybeStatic<Lifetime>),
165 /// Multiple borrows and no self borrow, no elision.
166 MultipleBorrows,
167 }
168
169 impl ElisionSource {
170 /// Potentially transition to a new state.
171 fn visit_lifetime(&mut self, lifetime: MaybeStatic<Lifetime>) {
172 match self {
173 ElisionSource::NoBorrows => *self = ElisionSource::OneParam(lifetime),
174 ElisionSource::SelfParam(_) => {
175 // References to self have the highest precedence, do nothing.
176 }
177 ElisionSource::OneParam(_) => *self = ElisionSource::MultipleBorrows,
178 ElisionSource::MultipleBorrows => {
179 // There's ambiguity. This is valid when there's no elision in
180 // the output.
181 }
182 };
183 }
184 }
185
186 /// A type for storing shared information between the different states of elision
187 /// inference.
188 ///
189 /// This contains data for generating fresh elided lifetimes, looking up named
190 /// lifetimes, and caching lifetimes of `Self`.
191 pub(super) struct BaseLifetimeLowerer<'ast> {
192 lifetime_env: &'ast ast::LifetimeEnv,
193 self_lifetimes: Option<Lifetimes>,
194 nodes: SmallVec<[BoundedLifetime; super::lifetimes::INLINE_NUM_LIFETIMES]>,
195 num_lifetimes: usize,
196 }
197
198 /// The first phase of output elision inference.
199 ///
200 /// In the first phase, the type signature of the `&self` or `&mut self` type
201 /// is lowered into its HIR representation, if present. According to elision
202 /// rules, this reference has the highest precedence as the lifetime that
203 /// goes into elision in the output, and so it's checked first.
204 pub(super) struct SelfParamLifetimeLowerer<'ast> {
205 base: BaseLifetimeLowerer<'ast>,
206 }
207
208 /// The second phase of output elision inference.
209 ///
210 /// In the second phase, all lifetimes in the parameter type signatures
211 /// (besides the lifetime of self, if present) are lowered. If a self param
212 /// didn't claim the potential output elided lifetime, then if there's a
213 /// single lifetime (elided or not) in the inputs, it will claim the
214 /// potential output elided lifetime.
215 pub(super) struct ParamLifetimeLowerer<'ast> {
216 elision_source: ElisionSource,
217 base: BaseLifetimeLowerer<'ast>,
218 }
219
220 /// The third and final phase of output elision inference.
221 ///
222 /// In the third phase, the type signature of the output type is lowered into
223 /// its HIR representation. If one of the input lifetimes were marked as
224 /// responsible for any elision in the output, then anonymous lifetimes get
225 /// that lifetime. If none did and there is elision in the output, then
226 /// rustc should have errored and said the elision was ambiguous, meaning
227 /// that state should be impossible so it panics.
228 pub(super) struct ReturnLifetimeLowerer<'ast> {
229 elision_source: ElisionSource,
230 base: BaseLifetimeLowerer<'ast>,
231 }
232
233 impl<'ast> BaseLifetimeLowerer<'ast> {
234 /// Returns a [`Lifetime`] representing a new anonymous lifetime, and
235 /// pushes it to the nodes vector.
236 fn new_elided(&mut self) -> Lifetime {
237 let index = self.num_lifetimes;
238 self.num_lifetimes += 1;
239 Lifetime::new(index)
240 }
241
242 /// Lowers a single [`ast::Lifetime`]. If the lifetime is elided, then a fresh
243 /// [`ImplicitLifetime`] is generated.
244 fn lower_lifetime(&mut self, lifetime: &ast::Lifetime) -> MaybeStatic<Lifetime> {
245 match lifetime {
246 ast::Lifetime::Static => MaybeStatic::Static,
247 ast::Lifetime::Named(named) => {
248 MaybeStatic::NonStatic(Lifetime::from_ast(named, self.lifetime_env))
249 }
250 ast::Lifetime::Anonymous => MaybeStatic::NonStatic(self.new_elided()),
251 }
252 }
253
254 /// Retrieves the cached `Self` lifetimes, or caches newly generated
255 /// lifetimes and returns those.
256 fn self_lifetimes_or_new(&mut self, ast_lifetimes: &[ast::Lifetime]) -> Lifetimes {
257 if let Some(lifetimes) = &self.self_lifetimes {
258 lifetimes.clone()
259 } else {
260 let lifetimes = Lifetimes::from_fn(ast_lifetimes, |lt| self.lower_lifetime(lt));
261 self.self_lifetimes = Some(lifetimes.clone());
262 lifetimes
263 }
264 }
265 }
266
267 impl<'ast> SelfParamLifetimeLowerer<'ast> {
268 /// Returns a new [`SelfParamLifetimeLowerer`].
269 pub fn new(
270 lifetime_env: &'ast ast::LifetimeEnv,
271 ctx: &mut LoweringContext,
272 ) -> Result<Self, ()> {
273 let mut hir_nodes = Ok(SmallVec::new());
274
275 for ast_node in lifetime_env.nodes.iter() {
276 let lifetime = ctx.lower_ident(ast_node.lifetime.name(), "named lifetime");
277 match (lifetime, &mut hir_nodes) {
278 (Ok(lifetime), Ok(hir_nodes)) => {
279 hir_nodes.push(BoundedLifetime::new(
280 lifetime,
281 ast_node.longer.iter().map(|i| Lifetime::new(*i)).collect(),
282 ast_node.shorter.iter().map(|i| Lifetime::new(*i)).collect(),
283 ));
284 }
285 _ => hir_nodes = Err(()),
286 }
287 }
288
289 hir_nodes.map(|nodes| Self {
290 base: BaseLifetimeLowerer {
291 lifetime_env,
292 self_lifetimes: None,
293 num_lifetimes: nodes.len(),
294 nodes,
295 },
296 })
297 }
298
299 /// Lowers the lifetime of `&self` or `&mut self`.
300 ///
301 /// The lifetimes of `&self` and `&mut self` are special, because they
302 /// automatically take priority over any other lifetime in the input for
303 /// being tied to any elided lifetimes in the output.
304 ///
305 /// Along with returning the lowered lifetime, this method also returns the
306 /// next state in elision inference, the [`ParamLifetimeLowerer`].
307 pub fn lower_self_ref(
308 mut self,
309 lifetime: &ast::Lifetime,
310 ) -> (MaybeStatic<Lifetime>, ParamLifetimeLowerer<'ast>) {
311 let self_lifetime = self.base.lower_lifetime(lifetime);
312
313 (
314 self_lifetime,
315 self.into_param_ltl(ElisionSource::SelfParam(self_lifetime)),
316 )
317 }
318
319 /// Acknowledges that there's no `&self` or `&mut self`, and transitions
320 /// to the next state, [`ParamLifetimeLowerer`].
321 pub fn no_self_ref(self) -> ParamLifetimeLowerer<'ast> {
322 self.into_param_ltl(ElisionSource::NoBorrows)
323 }
324
325 /// Transition into the next state, [`ParamLifetimeLowerer`].
326 fn into_param_ltl(self, elision_source: ElisionSource) -> ParamLifetimeLowerer<'ast> {
327 ParamLifetimeLowerer {
328 elision_source,
329 base: self.base,
330 }
331 }
332 }
333
334 impl<'ast> ParamLifetimeLowerer<'ast> {
335 /// Once all lifetimes in the parameters are lowered, this function is
336 /// called to transition to the next state, [`ReturnLifetimeLowerer`].
337 pub fn into_return_ltl(self) -> ReturnLifetimeLowerer<'ast> {
338 ReturnLifetimeLowerer {
339 elision_source: self.elision_source,
340 base: self.base,
341 }
342 }
343 }
344
345 impl<'ast> LifetimeLowerer for ParamLifetimeLowerer<'ast> {
346 fn lower_lifetime(&mut self, borrow: &ast::Lifetime) -> MaybeStatic<Lifetime> {
347 let lifetime = self.base.lower_lifetime(borrow);
348 self.elision_source.visit_lifetime(lifetime);
349 lifetime
350 }
351
352 fn lower_generics(
353 &mut self,
354 lifetimes: &[ast::Lifetime],
355 type_generics: &ast::LifetimeEnv,
356 is_self: bool,
357 ) -> Lifetimes {
358 if is_self {
359 self.base.self_lifetimes_or_new(lifetimes)
360 } else {
361 self.lower_lifetimes(lifetimes, type_generics)
362 }
363 }
364 }
365
366 impl<'ast> ReturnLifetimeLowerer<'ast> {
367 /// Finalize the lifetimes in the method, returning the resulting [`LifetimeEnv`].
368 pub fn finish(self) -> LifetimeEnv {
369 LifetimeEnv::new(self.base.nodes, self.base.num_lifetimes)
370 }
371 }
372
373 impl<'ast> LifetimeLowerer for ReturnLifetimeLowerer<'ast> {
374 fn lower_lifetime(&mut self, borrow: &ast::Lifetime) -> MaybeStatic<Lifetime> {
375 match borrow {
376 ast::Lifetime::Static => MaybeStatic::Static,
377 ast::Lifetime::Named(named) => {
378 MaybeStatic::NonStatic(Lifetime::from_ast(named, self.base.lifetime_env))
379 }
380 ast::Lifetime::Anonymous => match self.elision_source {
381 ElisionSource::SelfParam(lifetime) | ElisionSource::OneParam(lifetime) => lifetime,
382 ElisionSource::NoBorrows => {
383 panic!("nothing to borrow from, this shouldn't pass rustc's checks")
384 }
385 ElisionSource::MultipleBorrows => {
386 panic!("source of elision is ambiguous, this shouldn't pass rustc's checks")
387 }
388 },
389 }
390 }
391
392 fn lower_generics(
393 &mut self,
394 lifetimes: &[ast::Lifetime],
395 type_generics: &ast::LifetimeEnv,
396 is_self: bool,
397 ) -> Lifetimes {
398 if is_self {
399 self.base.self_lifetimes_or_new(lifetimes)
400 } else {
401 self.lower_lifetimes(lifetimes, type_generics)
402 }
403 }
404 }
405
406 impl LifetimeLowerer for &ast::LifetimeEnv {
407 fn lower_lifetime(&mut self, lifetime: &ast::Lifetime) -> MaybeStatic<Lifetime> {
408 match lifetime {
409 ast::Lifetime::Static => MaybeStatic::Static,
410 ast::Lifetime::Named(named) => MaybeStatic::NonStatic(Lifetime::from_ast(named, self)),
411 ast::Lifetime::Anonymous => {
412 panic!("anonymous lifetime inside struct, this shouldn't pass rustc's checks")
413 }
414 }
415 }
416
417 fn lower_generics(
418 &mut self,
419 lifetimes: &[ast::Lifetime],
420 type_generics: &ast::LifetimeEnv,
421 _: bool,
422 ) -> Lifetimes {
423 self.lower_lifetimes(lifetimes, type_generics)
424 }
425 }
426
427 // Things to test:
428 // 1. ensure that if there are multiple inputs that are `Self`, where `Self` has
429 // an elided lifetime, all expansions of `Self` have the same anonymous lifetimes.
430
431 #[cfg(test)]
432 mod tests {
433 use strck_ident::IntoCk;
434
435 /// Convert a syntax tree into a [`TypeContext`].
436 macro_rules! tcx {
437 ($($tokens:tt)*) => {{
438 let m = crate::ast::Module::from_syn(&syn::parse_quote! { $($tokens)* }, true);
439
440 let mut env = crate::Env::default();
441 let mut top_symbols = crate::ModuleEnv::new(Default::default());
442
443 m.insert_all_types(crate::ast::Path::empty(), &mut env);
444 top_symbols.insert(m.name.clone(), crate::ast::ModSymbol::SubModule(m.name.clone()));
445
446 env.insert(crate::ast::Path::empty(), top_symbols);
447
448 // Don't run validation: it will error on elision. We want this code to support
449 // elision even if we don't actually allow it, since good diagnostics involve understanding
450 // broken code.
451 let (_, tcx) = crate::hir::TypeContext::from_ast_without_validation(&env, crate::hir::BasicAttributeValidator::new("test-backend")).unwrap();
452
453 tcx
454 }}
455 }
456
457 macro_rules! do_test {
458 ($($tokens:tt)*) => {{
459 let mut settings = insta::Settings::new();
460 settings.set_sort_maps(true);
461
462 settings.bind(|| {
463 let tcx = tcx! { $($tokens)* };
464
465 insta::assert_debug_snapshot!(tcx);
466 })
467 }}
468 }
469
470 #[test]
471 fn simple_mod() {
472 do_test! {
473 mod ffi {
474 #[diplomat::opaque]
475 struct Opaque<'a> {
476 s: &'a DiplomatStr,
477 }
478
479 struct Struct<'a> {
480 s: &'a DiplomatStr,
481 }
482
483 #[diplomat::out]
484 struct OutStruct<'a> {
485 inner: Box<Opaque<'a>>,
486 }
487
488 impl<'a> OutStruct<'a> {
489 pub fn new(s: &'a DiplomatStr) -> Self {
490 Self { inner: Box::new(Opaque { s }) }
491 }
492
493 }
494
495 impl<'a> Struct<'a> {
496 pub fn rustc_elision(self, s: &DiplomatStr) -> &DiplomatStr {
497 s
498 }
499 }
500 }
501 }
502 }
503
504 #[test]
505 fn test_elision_in_struct() {
506 let tcx = tcx! {
507 mod ffi {
508 #[diplomat::opaque]
509 struct Opaque;
510
511 #[diplomat::opaque]
512 struct Opaque2<'a>(&'a str);
513
514 impl Opaque {
515 // This should have two elided lifetimes
516 pub fn elided(&self, x: &Opaque2) {
517
518 }
519 }
520 }
521 };
522
523 let method = &tcx
524 .opaques()
525 .iter()
526 .find(|def| def.name == "Opaque")
527 .unwrap()
528 .methods[0];
529
530 assert_eq!(
531 method.lifetime_env.num_lifetimes(),
532 3,
533 "elided() must have three anon lifetimes"
534 );
535 insta::assert_debug_snapshot!(method);
536 }
537
538 #[test]
539 fn test_borrowing_fields() {
540 use std::collections::BTreeMap;
541 use std::fmt;
542
543 let tcx = tcx! {
544 mod ffi {
545 #[diplomat::opaque]
546 pub struct Opaque;
547
548 struct Input<'p, 'q> {
549 p_data: &'p Opaque,
550 q_data: &'q Opaque,
551 name: &'static DiplomatStr,
552 inner: Inner<'q>,
553 }
554
555 struct Inner<'a> {
556 more_data: &'a DiplomatStr,
557 }
558
559 struct Output<'p,'q> {
560 p_data: &'p Opaque,
561 q_data: &'q Opaque,
562 }
563
564 impl<'a, 'b> Input<'a, 'b> {
565 pub fn as_output(self, _s: &'static DiplomatStr) -> Output<'b, 'a> {
566 Output { data: self.data }
567 }
568
569 }
570 }
571 };
572
573 let method = &tcx
574 .structs()
575 .iter()
576 .find(|def| def.name == "Input")
577 .unwrap()
578 .methods[0];
579
580 let visitor = method.borrowing_field_visitor(&tcx, "this".ck().unwrap());
581 let mut lt_to_borrowing_fields: BTreeMap<_, Vec<_>> = BTreeMap::new();
582 visitor.visit_borrowing_fields(|lt, bf| {
583 lt_to_borrowing_fields
584 .entry(lt)
585 .or_default()
586 .push(DebugBorrowingField(bf));
587 });
588
589 struct DebugBorrowingField<'m>(crate::hir::borrowing_field::BorrowingField<'m>);
590
591 impl<'m> fmt::Debug for DebugBorrowingField<'m> {
592 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593 f.write_str("\"")?;
594 self.0.try_backtrace(|i, ident| {
595 if i != 0 {
596 f.write_str(".")?;
597 }
598 f.write_str(ident.as_str())
599 })?;
600 f.write_str("\"")
601 }
602 }
603
604 let mut settings = insta::Settings::new();
605 settings.set_sort_maps(true);
606
607 settings.bind(|| {
608 insta::assert_debug_snapshot!(lt_to_borrowing_fields);
609 })
610 }
611 }