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 => true,
119                     TypeDefKind::Type(Type::Id(t)) => {
120                         needs_generics(resolve, &resolve.types[*t].kind)
121                     }
122                     TypeDefKind::Type(Type::String) => true,
123                     TypeDefKind::Type(_) => false,
124                     TypeDefKind::Unknown => unreachable!(),
125                 }
126             }
127         }
128 
129         match &ty.kind {
130             TypeDefKind::List(t) => self.print_list(t, mode),
131 
132             TypeDefKind::Option(t) => {
133                 self.push_str("Option<");
134                 self.print_ty(t, mode);
135                 self.push_str(">");
136             }
137 
138             TypeDefKind::Result(r) => {
139                 self.push_str("Result<");
140                 self.print_optional_ty(r.ok.as_ref(), mode);
141                 self.push_str(",");
142                 self.print_optional_ty(r.err.as_ref(), mode);
143                 self.push_str(">");
144             }
145 
146             TypeDefKind::Variant(_) => panic!("unsupported anonymous variant"),
147 
148             // Tuple-like records are mapped directly to Rust tuples of
149             // types. Note the trailing comma after each member to
150             // appropriately handle 1-tuples.
151             TypeDefKind::Tuple(t) => {
152                 self.push_str("(");
153                 for ty in t.types.iter() {
154                     self.print_ty(ty, mode);
155                     self.push_str(",");
156                 }
157                 self.push_str(")");
158             }
159             TypeDefKind::Record(_) => {
160                 panic!("unsupported anonymous type reference: record")
161             }
162             TypeDefKind::Flags(_) => {
163                 panic!("unsupported anonymous type reference: flags")
164             }
165             TypeDefKind::Enum(_) => {
166                 panic!("unsupported anonymous type reference: enum")
167             }
168             TypeDefKind::Future(ty) => {
169                 self.push_str("Future<");
170                 self.print_optional_ty(ty.as_ref(), mode);
171                 self.push_str(">");
172             }
173             TypeDefKind::Stream(stream) => {
174                 self.push_str("Stream<");
175                 self.print_optional_ty(stream.element.as_ref(), mode);
176                 self.push_str(",");
177                 self.print_optional_ty(stream.end.as_ref(), mode);
178                 self.push_str(">");
179             }
180 
181             TypeDefKind::Handle(handle) => {
182                 self.print_handle(handle);
183             }
184             TypeDefKind::Resource => unreachable!(),
185 
186             TypeDefKind::Type(t) => self.print_ty(t, mode),
187             TypeDefKind::Unknown => unreachable!(),
188         }
189     }
190 
191     fn print_type_name_in_interface(&mut self, owner: TypeOwner, name: &str) {
192         if let TypeOwner::Interface(id) = owner {
193             if let Some(path) = self.path_to_interface(id) {
194                 self.push_str(&path);
195                 self.push_str("::");
196             }
197         }
198         self.push_str(name);
199     }
200 
201     fn print_list(&mut self, ty: &Type, mode: TypeMode) {
202         let next_mode = if matches!(self.ownership(), Ownership::Owning) {
203             TypeMode::Owned
204         } else {
205             mode
206         };
207         match mode {
208             TypeMode::AllBorrowed(lt) => {
209                 self.push_str("&");
210                 if lt != "'_" {
211                     self.push_str(lt);
212                     self.push_str(" ");
213                 }
214                 self.push_str("[");
215                 self.print_ty(ty, next_mode);
216                 self.push_str("]");
217             }
218             TypeMode::Owned => {
219                 let wt = self.wasmtime_path();
220                 self.push_str(&format!("{wt}::component::__internal::Vec<"));
221                 self.print_ty(ty, next_mode);
222                 self.push_str(">");
223             }
224         }
225     }
226 
227     fn print_handle(&mut self, handle: &Handle) {
228         // Handles are either printed as `ResourceAny` for any guest-defined
229         // resource or `Resource<T>` for all host-defined resources. This means
230         // that this function needs to determine if `handle` points to a host
231         // or a guest resource which is determined by:
232         //
233         // * For world-owned resources, they're always imported.
234         // * For interface-owned resources, it depends on the how bindings were
235         //   last generated for this interface.
236         //
237         // Additionally type aliases via `use` are "peeled" here to find the
238         // original definition of the resource since that's the one that we
239         // care about for determining whether it's imported or not.
240         let resource = match handle {
241             Handle::Own(t) | Handle::Borrow(t) => *t,
242         };
243         let ty = &self.resolve().types[resource];
244         let def_id = super::resolve_type_definition_id(self.resolve(), resource);
245         let ty_def = &self.resolve().types[def_id];
246         let is_host_defined = match ty_def.owner {
247             TypeOwner::Interface(i) => self.is_imported_interface(i),
248             _ => true,
249         };
250         let wt = self.wasmtime_path();
251         if is_host_defined {
252             self.push_str(&format!("{wt}::component::Resource<"));
253             self.print_type_name_in_interface(
254                 ty.owner,
255                 &ty.name.as_ref().unwrap().to_upper_camel_case(),
256             );
257             self.push_str(">");
258         } else {
259             self.push_str(&format!("{wt}::component::ResourceAny"));
260         }
261     }
262 
263     fn print_generics(&mut self, lifetime: Option<&str>) {
264         if lifetime.is_none() {
265             return;
266         }
267         self.push_str("<");
268         if let Some(lt) = lifetime {
269             self.push_str(lt);
270             self.push_str(",");
271         }
272         self.push_str(">");
273     }
274 
275     fn modes_of(&self, ty: TypeId) -> Vec<(String, TypeMode)> {
276         let info = self.info(ty);
277         if !info.owned && !info.borrowed {
278             return Vec::new();
279         }
280         let mut result = Vec::new();
281         let first_mode =
282             if info.owned || !info.borrowed || matches!(self.ownership(), Ownership::Owning) {
283                 TypeMode::Owned
284             } else {
285                 assert!(!self.uses_two_names(&info));
286                 TypeMode::AllBorrowed("'a")
287             };
288         result.push((self.result_name(ty), first_mode));
289         if self.uses_two_names(&info) {
290             result.push((self.param_name(ty), TypeMode::AllBorrowed("'a")));
291         }
292         result
293     }
294 
295     fn param_name(&self, ty: TypeId) -> String {
296         let info = self.info(ty);
297         let name = self.resolve().types[ty]
298             .name
299             .as_ref()
300             .unwrap()
301             .to_upper_camel_case();
302         if self.uses_two_names(&info) {
303             format!("{name}Param")
304         } else {
305             name
306         }
307     }
308 
309     fn result_name(&self, ty: TypeId) -> String {
310         let info = self.info(ty);
311         let name = self.resolve().types[ty]
312             .name
313             .as_ref()
314             .unwrap()
315             .to_upper_camel_case();
316         if self.uses_two_names(&info) {
317             format!("{name}Result")
318         } else {
319             name
320         }
321     }
322 
323     fn uses_two_names(&self, info: &TypeInfo) -> bool {
324         info.has_list
325             && info.borrowed
326             && info.owned
327             && matches!(
328                 self.ownership(),
329                 Ownership::Borrowing {
330                     duplicate_if_necessary: true
331                 }
332             )
333     }
334 
335     fn lifetime_for(&self, info: &TypeInfo, mode: TypeMode) -> Option<&'static str> {
336         if matches!(self.ownership(), Ownership::Owning) {
337             return None;
338         }
339         let lt = match mode {
340             TypeMode::AllBorrowed(s) => s,
341             _ => return None,
342         };
343         // No lifetimes needed unless this has a list.
344         if !info.has_list {
345             return None;
346         }
347         // If two names are used then this type will have an owned and a
348         // borrowed copy and the borrowed copy is being used, so it needs a
349         // lifetime. Otherwise if it's only borrowed and not owned then this can
350         // also use a lifetime since it's not needed in two contexts and only
351         // the borrowed version of the structure was generated.
352         if self.uses_two_names(info) || (info.borrowed && !info.owned) {
353             Some(lt)
354         } else {
355             None
356         }
357     }
358 }
359 
360 /// Translate `name` to a Rust `snake_case` identifier.
361 pub fn to_rust_ident(name: &str) -> String {
362     match name {
363         // Escape Rust keywords.
364         // Source: https://doc.rust-lang.org/reference/keywords.html
365         "as" => "as_".into(),
366         "break" => "break_".into(),
367         "const" => "const_".into(),
368         "continue" => "continue_".into(),
369         "crate" => "crate_".into(),
370         "else" => "else_".into(),
371         "enum" => "enum_".into(),
372         "extern" => "extern_".into(),
373         "false" => "false_".into(),
374         "fn" => "fn_".into(),
375         "for" => "for_".into(),
376         "if" => "if_".into(),
377         "impl" => "impl_".into(),
378         "in" => "in_".into(),
379         "let" => "let_".into(),
380         "loop" => "loop_".into(),
381         "match" => "match_".into(),
382         "mod" => "mod_".into(),
383         "move" => "move_".into(),
384         "mut" => "mut_".into(),
385         "pub" => "pub_".into(),
386         "ref" => "ref_".into(),
387         "return" => "return_".into(),
388         "self" => "self_".into(),
389         "static" => "static_".into(),
390         "struct" => "struct_".into(),
391         "super" => "super_".into(),
392         "trait" => "trait_".into(),
393         "true" => "true_".into(),
394         "type" => "type_".into(),
395         "unsafe" => "unsafe_".into(),
396         "use" => "use_".into(),
397         "where" => "where_".into(),
398         "while" => "while_".into(),
399         "async" => "async_".into(),
400         "await" => "await_".into(),
401         "dyn" => "dyn_".into(),
402         "abstract" => "abstract_".into(),
403         "become" => "become_".into(),
404         "box" => "box_".into(),
405         "do" => "do_".into(),
406         "final" => "final_".into(),
407         "macro" => "macro_".into(),
408         "override" => "override_".into(),
409         "priv" => "priv_".into(),
410         "typeof" => "typeof_".into(),
411         "unsized" => "unsized_".into(),
412         "virtual" => "virtual_".into(),
413         "yield" => "yield_".into(),
414         "try" => "try_".into(),
415         s => s.to_snake_case(),
416     }
417 }
418 
419 /// Translate `name` to a Rust `UpperCamelCase` identifier.
420 pub fn to_rust_upper_camel_case(name: &str) -> String {
421     match name {
422         // We use `Host` as the name of the trait for host implementations
423         // to fill in, so rename it if "Host" is used as a regular identifier.
424         "host" => "Host_".into(),
425         s => s.to_upper_camel_case(),
426     }
427 }
428