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(_) | TypeDefKind::ErrorContext => 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("wasmtime::component::FutureReader<"); 170 self.print_optional_ty(ty.as_ref(), TypeMode::Owned); 171 self.push_str(">"); 172 } 173 TypeDefKind::Stream(ty) => { 174 self.push_str("wasmtime::component::StreamReader<"); 175 self.print_optional_ty(ty.as_ref(), TypeMode::Owned); 176 self.push_str(">"); 177 } 178 TypeDefKind::ErrorContext => { 179 self.push_str("wasmtime::component::ErrorContext"); 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_stream(&mut self, ty: Option<&Type>) { 228 let wt = self.wasmtime_path(); 229 self.push_str(&format!("{wt}::component::StreamReader<")); 230 self.print_optional_ty(ty, TypeMode::Owned); 231 self.push_str(">"); 232 } 233 234 fn print_future(&mut self, ty: Option<&Type>) { 235 let wt = self.wasmtime_path(); 236 self.push_str(&format!("{wt}::component::FutureReader<")); 237 self.print_optional_ty(ty, TypeMode::Owned); 238 self.push_str(">"); 239 } 240 241 fn print_error_context(&mut self) { 242 let wt = self.wasmtime_path(); 243 self.push_str(&format!("{wt}::component::ErrorContext")); 244 } 245 246 fn print_handle(&mut self, handle: &Handle) { 247 // Handles are either printed as `ResourceAny` for any guest-defined 248 // resource or `Resource<T>` for all host-defined resources. This means 249 // that this function needs to determine if `handle` points to a host 250 // or a guest resource which is determined by: 251 // 252 // * For world-owned resources, they're always imported. 253 // * For interface-owned resources, it depends on the how bindings were 254 // last generated for this interface. 255 // 256 // Additionally type aliases via `use` are "peeled" here to find the 257 // original definition of the resource since that's the one that we 258 // care about for determining whether it's imported or not. 259 let resource = match handle { 260 Handle::Own(t) | Handle::Borrow(t) => *t, 261 }; 262 let ty = &self.resolve().types[resource]; 263 let def_id = super::resolve_type_definition_id(self.resolve(), resource); 264 let ty_def = &self.resolve().types[def_id]; 265 let is_host_defined = match ty_def.owner { 266 TypeOwner::Interface(i) => self.is_imported_interface(i), 267 _ => true, 268 }; 269 let wt = self.wasmtime_path(); 270 if is_host_defined { 271 self.push_str(&format!("{wt}::component::Resource<")); 272 self.print_type_name_in_interface( 273 ty.owner, 274 &ty.name.as_ref().unwrap().to_upper_camel_case(), 275 ); 276 self.push_str(">"); 277 } else { 278 self.push_str(&format!("{wt}::component::ResourceAny")); 279 } 280 } 281 282 fn print_generics(&mut self, lifetime: Option<&str>) { 283 if lifetime.is_none() { 284 return; 285 } 286 self.push_str("<"); 287 if let Some(lt) = lifetime { 288 self.push_str(lt); 289 self.push_str(","); 290 } 291 self.push_str(">"); 292 } 293 294 fn modes_of(&self, ty: TypeId) -> Vec<(String, TypeMode)> { 295 let info = self.info(ty); 296 if !info.owned && !info.borrowed { 297 return Vec::new(); 298 } 299 let mut result = Vec::new(); 300 let first_mode = 301 if info.owned || !info.borrowed || matches!(self.ownership(), Ownership::Owning) { 302 TypeMode::Owned 303 } else { 304 assert!(!self.uses_two_names(&info)); 305 TypeMode::AllBorrowed("'a") 306 }; 307 result.push((self.result_name(ty), first_mode)); 308 if self.uses_two_names(&info) { 309 result.push((self.param_name(ty), TypeMode::AllBorrowed("'a"))); 310 } 311 result 312 } 313 314 fn param_name(&self, ty: TypeId) -> String { 315 let info = self.info(ty); 316 let name = self.resolve().types[ty] 317 .name 318 .as_ref() 319 .unwrap() 320 .to_upper_camel_case(); 321 if self.uses_two_names(&info) { 322 format!("{name}Param") 323 } else { 324 name 325 } 326 } 327 328 fn result_name(&self, ty: TypeId) -> String { 329 let info = self.info(ty); 330 let name = self.resolve().types[ty] 331 .name 332 .as_ref() 333 .unwrap() 334 .to_upper_camel_case(); 335 if self.uses_two_names(&info) { 336 format!("{name}Result") 337 } else { 338 name 339 } 340 } 341 342 fn uses_two_names(&self, info: &TypeInfo) -> bool { 343 info.has_list 344 && info.borrowed 345 && info.owned 346 && matches!( 347 self.ownership(), 348 Ownership::Borrowing { 349 duplicate_if_necessary: true 350 } 351 ) 352 } 353 354 fn lifetime_for(&self, info: &TypeInfo, mode: TypeMode) -> Option<&'static str> { 355 if matches!(self.ownership(), Ownership::Owning) { 356 return None; 357 } 358 let lt = match mode { 359 TypeMode::AllBorrowed(s) => s, 360 _ => return None, 361 }; 362 // No lifetimes needed unless this has a list. 363 if !info.has_list { 364 return None; 365 } 366 // If two names are used then this type will have an owned and a 367 // borrowed copy and the borrowed copy is being used, so it needs a 368 // lifetime. Otherwise if it's only borrowed and not owned then this can 369 // also use a lifetime since it's not needed in two contexts and only 370 // the borrowed version of the structure was generated. 371 if self.uses_two_names(info) || (info.borrowed && !info.owned) { 372 Some(lt) 373 } else { 374 None 375 } 376 } 377 } 378 379 /// Translate `name` to a Rust `snake_case` identifier. 380 pub fn to_rust_ident(name: &str) -> String { 381 match name { 382 // Escape Rust keywords. 383 // Source: https://doc.rust-lang.org/reference/keywords.html 384 "as" => "as_".into(), 385 "break" => "break_".into(), 386 "const" => "const_".into(), 387 "continue" => "continue_".into(), 388 "crate" => "crate_".into(), 389 "else" => "else_".into(), 390 "enum" => "enum_".into(), 391 "extern" => "extern_".into(), 392 "false" => "false_".into(), 393 "fn" => "fn_".into(), 394 "for" => "for_".into(), 395 "if" => "if_".into(), 396 "impl" => "impl_".into(), 397 "in" => "in_".into(), 398 "let" => "let_".into(), 399 "loop" => "loop_".into(), 400 "match" => "match_".into(), 401 "mod" => "mod_".into(), 402 "move" => "move_".into(), 403 "mut" => "mut_".into(), 404 "pub" => "pub_".into(), 405 "ref" => "ref_".into(), 406 "return" => "return_".into(), 407 "self" => "self_".into(), 408 "static" => "static_".into(), 409 "struct" => "struct_".into(), 410 "super" => "super_".into(), 411 "trait" => "trait_".into(), 412 "true" => "true_".into(), 413 "type" => "type_".into(), 414 "unsafe" => "unsafe_".into(), 415 "use" => "use_".into(), 416 "where" => "where_".into(), 417 "while" => "while_".into(), 418 "async" => "async_".into(), 419 "await" => "await_".into(), 420 "dyn" => "dyn_".into(), 421 "abstract" => "abstract_".into(), 422 "become" => "become_".into(), 423 "box" => "box_".into(), 424 "do" => "do_".into(), 425 "final" => "final_".into(), 426 "macro" => "macro_".into(), 427 "override" => "override_".into(), 428 "priv" => "priv_".into(), 429 "typeof" => "typeof_".into(), 430 "unsized" => "unsized_".into(), 431 "virtual" => "virtual_".into(), 432 "yield" => "yield_".into(), 433 "try" => "try_".into(), 434 s => s.to_snake_case(), 435 } 436 } 437 438 /// Translate `name` to a Rust `UpperCamelCase` identifier. 439 pub fn to_rust_upper_camel_case(name: &str) -> String { 440 match name { 441 // We use `Host` as the name of the trait for host implementations 442 // to fill in, so rename it if "Host" is used as a regular identifier. 443 "host" => "Host_".into(), 444 s => s.to_upper_camel_case(), 445 } 446 } 447