wiggle_generate/
lifetimes.rs

1use proc_macro2::TokenStream;
2use quote::quote;
3
4pub trait LifetimeExt {
5    fn is_transparent(&self) -> bool;
6    fn needs_lifetime(&self) -> bool;
7}
8
9impl LifetimeExt for witx::TypeRef {
10    fn is_transparent(&self) -> bool {
11        self.type_().is_transparent()
12    }
13    fn needs_lifetime(&self) -> bool {
14        self.type_().needs_lifetime()
15    }
16}
17
18impl LifetimeExt for witx::Type {
19    fn is_transparent(&self) -> bool {
20        match self {
21            witx::Type::Builtin(b) => b.is_transparent(),
22            witx::Type::Record(s) => s.is_transparent(),
23            witx::Type::Handle { .. } => true,
24            witx::Type::Variant { .. }
25            | witx::Type::Pointer { .. }
26            | witx::Type::ConstPointer { .. }
27            | witx::Type::List { .. } => false,
28        }
29    }
30    fn needs_lifetime(&self) -> bool {
31        match self {
32            witx::Type::Builtin(b) => b.needs_lifetime(),
33            witx::Type::Record(s) => s.needs_lifetime(),
34            witx::Type::Variant(u) => u.needs_lifetime(),
35            witx::Type::Handle { .. } => false,
36            witx::Type::Pointer { .. }
37            | witx::Type::ConstPointer { .. }
38            | witx::Type::List { .. } => true,
39        }
40    }
41}
42
43impl LifetimeExt for witx::BuiltinType {
44    fn is_transparent(&self) -> bool {
45        true
46    }
47    fn needs_lifetime(&self) -> bool {
48        false
49    }
50}
51
52impl LifetimeExt for witx::RecordDatatype {
53    fn is_transparent(&self) -> bool {
54        self.members.iter().all(|m| m.tref.is_transparent())
55    }
56    fn needs_lifetime(&self) -> bool {
57        self.members.iter().any(|m| m.tref.needs_lifetime())
58    }
59}
60
61impl LifetimeExt for witx::Variant {
62    fn is_transparent(&self) -> bool {
63        false
64    }
65    fn needs_lifetime(&self) -> bool {
66        self.cases
67            .iter()
68            .any(|m| m.tref.as_ref().map(|t| t.needs_lifetime()).unwrap_or(false))
69    }
70}
71
72pub fn anon_lifetime() -> TokenStream {
73    quote!('_)
74}