Debian Codegraph @

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

raw
1 //! Methods for types and navigating lifetimes within methods.
2
3 use std::collections::BTreeSet;
4 use std::ops::Deref;
5
6 use super::{Attrs, Docs, Ident, IdentBuf, OutType, SelfType, Type, TypeContext};
7
8 use super::lifetimes::{Lifetime, LifetimeEnv, Lifetimes, MaybeStatic};
9
10 use borrowing_field::BorrowingFieldVisitor;
11 use borrowing_param::BorrowingParamVisitor;
12
13 pub mod borrowing_field;
14 pub mod borrowing_param;
15
16 /// A method exposed to Diplomat.
17 #[derive(Debug)]
18 #[non_exhaustive]
19 pub struct Method {
20 pub docs: Docs,
21 pub name: IdentBuf,
22 pub lifetime_env: LifetimeEnv,
23
24 pub param_self: Option<ParamSelf>,
25 pub params: Vec<Param>,
26 pub output: ReturnType,
27 pub attrs: Attrs,
28 }
29
30 /// Type that the method returns.
31 #[derive(Debug, Clone)]
32 #[non_exhaustive]
33 pub enum SuccessType {
34 Writeable,
35 OutType(OutType),
36 Unit,
37 }
38
39 /// Whether or not the method returns a value or a result.
40 #[derive(Debug)]
41 #[allow(clippy::exhaustive_enums)] // this only exists for fallible/infallible, breaking changes for more complex returns are ok
42 pub enum ReturnType {
43 Infallible(SuccessType),
44 Fallible(SuccessType, Option<OutType>),
45 Nullable(SuccessType),
46 }
47
48 /// The `self` parameter of a method.
49 #[derive(Debug)]
50 #[non_exhaustive]
51 pub struct ParamSelf {
52 pub ty: SelfType,
53 }
54
55 /// A parameter in a method.
56 #[derive(Debug)]
57 #[non_exhaustive]
58 pub struct Param {
59 pub name: IdentBuf,
60 pub ty: Type,
61 }
62
63 impl SuccessType {
64 /// Returns whether the variant is `Writeable`.
65 pub fn is_writeable(&self) -> bool {
66 matches!(self, SuccessType::Writeable)
67 }
68
69 /// Returns whether the variant is `Unit`.
70 pub fn is_unit(&self) -> bool {
71 matches!(self, SuccessType::Unit)
72 }
73
74 pub fn as_type(&self) -> Option<&OutType> {
75 match self {
76 SuccessType::OutType(ty) => Some(ty),
77 _ => None,
78 }
79 }
80 }
81
82 impl Deref for ReturnType {
83 type Target = SuccessType;
84
85 fn deref(&self) -> &Self::Target {
86 match self {
87 ReturnType::Infallible(ret) | ReturnType::Fallible(ret, _) | Self::Nullable(ret) => ret,
88 }
89 }
90 }
91
92 impl ReturnType {
93 /// Returns `true` if the FFI function returns `void`. Not that this is different from `is_unit`,
94 /// which will be true for `DiplomatResult<(), E>` and false for infallible writeable.
95 pub fn is_ffi_unit(&self) -> bool {
96 matches!(
97 self,
98 ReturnType::Infallible(SuccessType::Unit | SuccessType::Writeable)
99 )
100 }
101
102 /// The "main" return type of this function: the Ok, Some, or regular type
103 pub fn success_type(&self) -> &SuccessType {
104 match &self {
105 Self::Infallible(s) => s,
106 Self::Fallible(s, _) => s,
107 Self::Nullable(s) => s,
108 }
109 }
110
111 /// Get the list of method lifetimes actually used by the method return type
112 ///
113 /// Most input lifetimes aren't actually used. An input lifetime is generated
114 /// for each borrowing parameter but is only important if we use it in the return.
115 pub fn used_method_lifetimes(&self) -> BTreeSet<Lifetime> {
116 let mut set = BTreeSet::new();
117
118 let mut add_to_set = |ty: &OutType| {
119 for lt in ty.lifetimes() {
120 if let MaybeStatic::NonStatic(lt) = lt {
121 set.insert(lt);
122 }
123 }
124 };
125
126 match self {
127 ReturnType::Infallible(SuccessType::OutType(ref ty))
128 | ReturnType::Nullable(SuccessType::OutType(ref ty)) => add_to_set(ty),
129 ReturnType::Fallible(ref ok, ref err) => {
130 if let SuccessType::OutType(ref ty) = ok {
131 add_to_set(ty)
132 }
133 if let Some(ref ty) = err {
134 add_to_set(ty)
135 }
136 }
137 _ => (),
138 }
139
140 set
141 }
142
143 pub fn with_contained_types(&self, mut f: impl FnMut(&OutType)) {
144 match self {
145 Self::Infallible(SuccessType::OutType(o))
146 | Self::Nullable(SuccessType::OutType(o))
147 | Self::Fallible(SuccessType::OutType(o), None) => f(o),
148 Self::Fallible(SuccessType::OutType(o), Some(o2)) => {
149 f(o);
150 f(o2)
151 }
152 Self::Fallible(_, Some(o)) => f(o),
153 _ => (),
154 }
155 }
156 }
157
158 impl ParamSelf {
159 pub(super) fn new(ty: SelfType) -> Self {
160 Self { ty }
161 }
162
163 /// Return the number of fields and leaves that will show up in the [`BorrowingFieldVisitor`].
164 ///
165 /// This method is used to calculate how much space to allocate upfront.
166 fn field_leaf_lifetime_counts(&self, tcx: &TypeContext) -> (usize, usize) {
167 match self.ty {
168 SelfType::Opaque(_) => (1, 1),
169 SelfType::Struct(ref ty) => ty.resolve(tcx).fields.iter().fold((1, 0), |acc, field| {
170 let inner = field.ty.field_leaf_lifetime_counts(tcx);
171 (acc.0 + inner.0, acc.1 + inner.1)
172 }),
173 SelfType::Enum(_) => (0, 0),
174 }
175 }
176 }
177
178 impl Param {
179 pub(super) fn new(name: IdentBuf, ty: Type) -> Self {
180 Self { name, ty }
181 }
182 }
183
184 impl Method {
185 /// Returns a fresh [`Lifetimes`] corresponding to `self`.
186 pub fn method_lifetimes(&self) -> Lifetimes {
187 self.lifetime_env.lifetimes()
188 }
189
190 /// Returns a new [`BorrowingParamVisitor`], which can *shallowly* link output lifetimes
191 /// to the parameters they borrow from.
192 ///
193 /// This is useful for backends which wish to have lifetime codegen for methods only handle the local
194 /// method lifetime, and delegate to generated code on structs for handling the internals of struct lifetimes.
195 pub fn borrowing_param_visitor<'tcx>(
196 &'tcx self,
197 tcx: &'tcx TypeContext,
198 ) -> BorrowingParamVisitor<'tcx> {
199 BorrowingParamVisitor::new(self, tcx)
200 }
201
202 /// Returns a new [`BorrowingFieldVisitor`], which allocates memory to
203 /// efficiently represent all fields (and their paths!) of the inputs that
204 /// have a lifetime.
205 ///
206 /// This is useful for backends which wish to "splat out" lifetime edge codegen for methods,
207 /// linking each borrowed input param/field (however deep it may be in a struct) to a borrowed output param/field.
208 ///
209 /// ```ignore
210 /// # use std::collections::BTreeMap;
211 /// let visitor = method.borrowing_field_visitor(&tcx, "this".ck().unwrap());
212 /// let mut map = BTreeMap::new();
213 /// visitor.visit_borrowing_fields(|lifetime, field| {
214 /// map.entry(lifetime).or_default().push(field);
215 /// })
216 /// ```
217 pub fn borrowing_field_visitor<'m>(
218 &'m self,
219 tcx: &'m TypeContext,
220 self_name: &'m Ident,
221 ) -> BorrowingFieldVisitor<'m> {
222 BorrowingFieldVisitor::new(self, tcx, self_name)
223 }
224 }