1 use crate::{types::TypeInfo, Ownership};
2 use heck::*;
3 use wit_parser::*;
4 
5 #[derive(Debug, Copy, Clone, PartialEq)]
6 pub enum TypeMode {
7     Owned,
8     AllBorrowed(&'static str),
9 }
10 
11 pub trait RustGenerator<'a> {
12     fn resolve(&self) -> &'a Resolve;
13 
14     fn push_str(&mut self, s: &str);
15     fn info(&self, ty: TypeId) -> TypeInfo;
16     fn path_to_interface(&self, interface: InterfaceId) -> Option<String>;
17     fn is_imported_interface(&self, interface: InterfaceId) -> bool;
18     fn wasmtime_path(&self) -> String;
19 
20     /// This determines whether we generate owning types or (where appropriate)
21     /// borrowing types.
22     ///
23     /// For example, when generating a type which is only used as a parameter to
24     /// a guest-exported function, there is no need for it to own its fields.
25     /// However, constructing deeply-nested borrows (e.g. `&[&[&[&str]]]]` for
26     /// `list<list<list<string>>>`) can be very awkward, so by default we
27     /// generate owning types and use only shallow borrowing at the top level
28     /// inside function signatures.
29     fn ownership(&self) -> Ownership;
30 
31     fn print_ty(&mut self, ty: &Type, mode: TypeMode) {
32         match ty {
33             Type::Id(t) => self.print_tyid(*t, mode),
34             Type::Bool => self.push_str("bool"),
35             Type::U8 => self.push_str("u8"),
36             Type::U16 => self.push_str("u16"),
37             Type::U32 => self.push_str("u32"),
38             Type::U64 => self.push_str("u64"),
39             Type::S8 => self.push_str("i8"),
40             Type::S16 => self.push_str("i16"),
41             Type::S32 => self.push_str("i32"),
42             Type::S64 => self.push_str("i64"),
43             Type::F32 => self.push_str("f32"),
44             Type::F64 => self.push_str("f64"),
45             Type::Char => self.push_str("char"),
46             Type::String => match mode {
47                 TypeMode::AllBorrowed(lt) => {
48                     self.push_str("&");
49                     if lt != "'_" {
50                         self.push_str(lt);
51                         self.push_str(" ");
52                     }
53                     self.push_str("str");
54                 }
55                 TypeMode::Owned => {
56                     let wt = self.wasmtime_path();
57                     self.push_str(&format!("{wt}::component::__internal::String"))
58                 }
59             },
60         }
61     }
62 
63     fn print_optional_ty(&mut self, ty: Option<&Type>, mode: TypeMode) {
64         match ty {
65             Some(ty) => self.print_ty(ty, mode),
66             None => self.push_str("()"),
67         }
68     }
69 
70     fn print_tyid(&mut self, id: TypeId, mode: TypeMode) {
71         let info = self.info(id);
72         let lt = self.lifetime_for(&info, mode);
73         let ty = &self.resolve().types[id];
74         if ty.name.is_some() {
75             // If this type has a list internally, no lifetime is being printed,
76             // but we're in a borrowed mode, then that means we're in a borrowed
77             // context and don't want ownership of the type but we're using an
78             // owned type definition. Inject a `&` in front to indicate that, at
79             // the API level, ownership isn't required.
80             if info.has_list && lt.is_none() {
81                 if let TypeMode::AllBorrowed(lt) = mode {
82                     self.push_str("&");
83                     if lt != "'_" {
84                         self.push_str(lt);
85                         self.push_str(" ");
86                     }
87                 }
88             }
89             let name = if lt.is_some() {
90                 self.param_name(id)
91             } else {
92                 self.result_name(id)
93             };
94             self.print_type_name_in_interface(ty.owner, &name);
95 
96             // If the type recursively owns data and it's a
97             // variant/record/list, then we need to place the
98             // lifetime parameter on the type as well.
99             if info.has_list && needs_generics(self.resolve(), &ty.kind) {
100                 self.print_generics(lt);
101             }
102 
103             return;
104 
105             fn needs_generics(resolve: &Resolve, ty: &TypeDefKind) -> bool {
106                 match ty {
107                     TypeDefKind::Variant(_)
108                     | TypeDefKind::Record(_)
109                     | TypeDefKind::Option(_)
110                     | TypeDefKind::Result(_)
111                     | TypeDefKind::Future(_)
112                     | TypeDefKind::Stream(_)
113                     | TypeDefKind::List(_)
114                     | TypeDefKind::Flags(_)
115                     | TypeDefKind::Enum(_)
116                     | TypeDefKind::Tuple(_)
117                     | TypeDefKind::Handle(_)
118                     | TypeDefKind::Resource
119                     | TypeDefKind::ErrorContext => true,
120                     TypeDefKind::Type(Type::Id(t)) => {
121                         needs_generics(resolve, &resolve.types[*t].kind)
122                     }
123                     TypeDefKind::Type(Type::String) => true,
124                     TypeDefKind::Type(_) => false,
125                     TypeDefKind::Unknown => unreachable!(),
126                 }
127             }
128         }
129 
130         match &ty.kind {
131             TypeDefKind::List(t) => self.print_list(t, mode),
132 
133             TypeDefKind::Option(t) => {
134                 self.push_str("Option<");
135                 self.print_ty(t, mode);
136                 self.push_str(">");
137             }
138 
139             TypeDefKind::Result(r) => {
140                 self.push_str("Result<");
141                 self.print_optional_ty(r.ok.as_ref(), mode);
142                 self.push_str(",");
143                 self.print_optional_ty(r.err.as_ref(), mode);
144                 self.push_str(">");
145             }
146 
147             TypeDefKind::Variant(_) => panic!("unsupported anonymous variant"),
148 
149             // Tuple-like records are mapped directly to Rust tuples of
150             // types. Note the trailing comma after each member to
151             // appropriately handle 1-tuples.
152             TypeDefKind::Tuple(t) => {
153                 self.push_str("(");
154                 for ty in t.types.iter() {
155                     self.print_ty(ty, mode);
156                     self.push_str(",");
157                 }
158                 self.push_str(")");
159             }
160             TypeDefKind::Record(_) => {
161                 panic!("unsupported anonymous type reference: record")
162             }
163             TypeDefKind::Flags(_) => {
164                 panic!("unsupported anonymous type reference: flags")
165             }
166             TypeDefKind::Enum(_) => {
167                 panic!("unsupported anonymous type reference: enum")
168             }
169             TypeDefKind::Future(_) => todo!(),
170             TypeDefKind::Stream(_) => todo!(),
171             TypeDefKind::ErrorContext => todo!(),
172 
173             TypeDefKind::Handle(handle) => {
174                 self.print_handle(handle);
175             }
176             TypeDefKind::Resource => unreachable!(),
177 
178             TypeDefKind::Type(t) => self.print_ty(t, mode),
179             TypeDefKind::Unknown => unreachable!(),
180         }
181     }
182 
183     fn print_type_name_in_interface(&mut self, owner: TypeOwner, name: &str) {
184         if let TypeOwner::Interface(id) = owner {
185             if let Some(path) = self.path_to_interface(id) {
186                 self.push_str(&path);
187                 self.push_str("::");
188             }
189         }
190         self.push_str(name);
191     }
192 
193     fn print_list(&mut self, ty: &Type, mode: TypeMode) {
194         let next_mode = if matches!(self.ownership(), Ownership::Owning) {
195             TypeMode::Owned
196         } else {
197             mode
198         };
199         match mode {
200             TypeMode::AllBorrowed(lt) => {
201                 self.push_str("&");
202                 if lt != "'_" {
203                     self.push_str(lt);
204                     self.push_str(" ");
205                 }
206                 self.push_str("[");
207                 self.print_ty(ty, next_mode);
208                 self.push_str("]");
209             }
210             TypeMode::Owned => {
211                 let wt = self.wasmtime_path();
212                 self.push_str(&format!("{wt}::component::__internal::Vec<"));
213                 self.print_ty(ty, next_mode);
214                 self.push_str(">");
215             }
216         }
217     }
218 
219     fn print_handle(&mut self, handle: &Handle) {
220         // Handles are either printed as `ResourceAny` for any guest-defined
221         // resource or `Resource<T>` for all host-defined resources. This means
222         // that this function needs to determine if `handle` points to a host
223         // or a guest resource which is determined by:
224         //
225         // * For world-owned resources, they're always imported.
226         // * For interface-owned resources, it depends on the how bindings were
227         //   last generated for this interface.
228         //
229         // Additionally type aliases via `use` are "peeled" here to find the
230         // original definition of the resource since that's the one that we
231         // care about for determining whether it's imported or not.
232         let resource = match handle {
233             Handle::Own(t) | Handle::Borrow(t) => *t,
234         };
235         let ty = &self.resolve().types[resource];
236         let def_id = super::resolve_type_definition_id(self.resolve(), resource);
237         let ty_def = &self.resolve().types[def_id];
238         let is_host_defined = match ty_def.owner {
239             TypeOwner::Interface(i) => self.is_imported_interface(i),
240             _ => true,
241         };
242         let wt = self.wasmtime_path();
243         if is_host_defined {
244             self.push_str(&format!("{wt}::component::Resource<"));
245             self.print_type_name_in_interface(
246                 ty.owner,
247                 &ty.name.as_ref().unwrap().to_upper_camel_case(),
248             );
249             self.push_str(">");
250         } else {
251             self.push_str(&format!("{wt}::component::ResourceAny"));
252         }
253     }
254 
255     fn print_generics(&mut self, lifetime: Option<&str>) {
256         if lifetime.is_none() {
257             return;
258         }
259         self.push_str("<");
260         if let Some(lt) = lifetime {
261             self.push_str(lt);
262             self.push_str(",");
263         }
264         self.push_str(">");
265     }
266 
267     fn modes_of(&self, ty: TypeId) -> Vec<(String, TypeMode)> {
268         let info = self.info(ty);
269         if !info.owned && !info.borrowed {
270             return Vec::new();
271         }
272         let mut result = Vec::new();
273         let first_mode =
274             if info.owned || !info.borrowed || matches!(self.ownership(), Ownership::Owning) {
275                 TypeMode::Owned
276             } else {
277                 assert!(!self.uses_two_names(&info));
278                 TypeMode::AllBorrowed("'a")
279             };
280         result.push((self.result_name(ty), first_mode));
281         if self.uses_two_names(&info) {
282             result.push((self.param_name(ty), TypeMode::AllBorrowed("'a")));
283         }
284         result
285     }
286 
287     fn param_name(&self, ty: TypeId) -> String {
288         let info = self.info(ty);
289         let name = self.resolve().types[ty]
290             .name
291             .as_ref()
292             .unwrap()
293             .to_upper_camel_case();
294         if self.uses_two_names(&info) {
295             format!("{name}Param")
296         } else {
297             name
298         }
299     }
300 
301     fn result_name(&self, ty: TypeId) -> String {
302         let info = self.info(ty);
303         let name = self.resolve().types[ty]
304             .name
305             .as_ref()
306             .unwrap()
307             .to_upper_camel_case();
308         if self.uses_two_names(&info) {
309             format!("{name}Result")
310         } else {
311             name
312         }
313     }
314 
315     fn uses_two_names(&self, info: &TypeInfo) -> bool {
316         info.has_list
317             && info.borrowed
318             && info.owned
319             && matches!(
320                 self.ownership(),
321                 Ownership::Borrowing {
322                     duplicate_if_necessary: true
323                 }
324             )
325     }
326 
327     fn lifetime_for(&self, info: &TypeInfo, mode: TypeMode) -> Option<&'static str> {
328         if matches!(self.ownership(), Ownership::Owning) {
329             return None;
330         }
331         let lt = match mode {
332             TypeMode::AllBorrowed(s) => s,
333             _ => return None,
334         };
335         // No lifetimes needed unless this has a list.
336         if !info.has_list {
337             return None;
338         }
339         // If two names are used then this type will have an owned and a
340         // borrowed copy and the borrowed copy is being used, so it needs a
341         // lifetime. Otherwise if it's only borrowed and not owned then this can
342         // also use a lifetime since it's not needed in two contexts and only
343         // the borrowed version of the structure was generated.
344         if self.uses_two_names(info) || (info.borrowed && !info.owned) {
345             Some(lt)
346         } else {
347             None
348         }
349     }
350 }
351 
352 /// Translate `name` to a Rust `snake_case` identifier.
353 pub fn to_rust_ident(name: &str) -> String {
354     match name {
355         // Escape Rust keywords.
356         // Source: https://doc.rust-lang.org/reference/keywords.html
357         "as" => "as_".into(),
358         "break" => "break_".into(),
359         "const" => "const_".into(),
360         "continue" => "continue_".into(),
361         "crate" => "crate_".into(),
362         "else" => "else_".into(),
363         "enum" => "enum_".into(),
364         "extern" => "extern_".into(),
365         "false" => "false_".into(),
366         "fn" => "fn_".into(),
367         "for" => "for_".into(),
368         "if" => "if_".into(),
369         "impl" => "impl_".into(),
370         "in" => "in_".into(),
371         "let" => "let_".into(),
372         "loop" => "loop_".into(),
373         "match" => "match_".into(),
374         "mod" => "mod_".into(),
375         "move" => "move_".into(),
376         "mut" => "mut_".into(),
377         "pub" => "pub_".into(),
378         "ref" => "ref_".into(),
379         "return" => "return_".into(),
380         "self" => "self_".into(),
381         "static" => "static_".into(),
382         "struct" => "struct_".into(),
383         "super" => "super_".into(),
384         "trait" => "trait_".into(),
385         "true" => "true_".into(),
386         "type" => "type_".into(),
387         "unsafe" => "unsafe_".into(),
388         "use" => "use_".into(),
389         "where" => "where_".into(),
390         "while" => "while_".into(),
391         "async" => "async_".into(),
392         "await" => "await_".into(),
393         "dyn" => "dyn_".into(),
394         "abstract" => "abstract_".into(),
395         "become" => "become_".into(),
396         "box" => "box_".into(),
397         "do" => "do_".into(),
398         "final" => "final_".into(),
399         "macro" => "macro_".into(),
400         "override" => "override_".into(),
401         "priv" => "priv_".into(),
402         "typeof" => "typeof_".into(),
403         "unsized" => "unsized_".into(),
404         "virtual" => "virtual_".into(),
405         "yield" => "yield_".into(),
406         "try" => "try_".into(),
407         s => s.to_snake_case(),
408     }
409 }
410 
411 /// Translate `name` to a Rust `UpperCamelCase` identifier.
412 pub fn to_rust_upper_camel_case(name: &str) -> String {
413     match name {
414         // We use `Host` as the name of the trait for host implementations
415         // to fill in, so rename it if "Host" is used as a regular identifier.
416         "host" => "Host_".into(),
417         s => s.to_upper_camel_case(),
418     }
419 }
420