| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
use anyhow::{bail, Context, Result}; |
| 6 |
use askama::Template; |
| 7 |
|
| 8 |
use heck::{ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase}; |
| 9 |
use once_cell::sync::Lazy; |
| 10 |
use serde::{Deserialize, Serialize}; |
| 11 |
use std::borrow::Borrow; |
| 12 |
use std::cell::RefCell; |
| 13 |
use std::collections::{BTreeSet, HashMap, HashSet}; |
| 14 |
use std::fmt::Debug; |
| 15 |
|
| 16 |
use crate::interface::*; |
| 17 |
use crate::VisitMut; |
| 18 |
|
| 19 |
mod callback_interface; |
| 20 |
mod compounds; |
| 21 |
mod custom; |
| 22 |
mod enum_; |
| 23 |
mod miscellany; |
| 24 |
mod object; |
| 25 |
mod primitives; |
| 26 |
mod record; |
| 27 |
|
| 28 |
/// A trait tor the implementation. |
| 29 |
trait CodeType: Debug { |
| 30 |
/// The language specific label used to reference this type. This will be used in |
| 31 |
/// method signatures and property declarations. |
| 32 |
fn type_label(&self) -> String; |
| 33 |
|
| 34 |
/// A representation of this type label that can be used as part of another |
| 35 |
/// identifier. e.g. `read_foo()`, or `FooInternals`. |
| 36 |
/// |
| 37 |
/// This is especially useful when creating specialized objects or methods to deal |
| 38 |
/// with this type only. |
| 39 |
fn canonical_name(&self) -> String { |
| 40 |
self.type_label() |
| 41 |
} |
| 42 |
|
| 43 |
fn literal(&self, _literal: &Literal) -> Result<String> { |
| 44 |
bail!("Unimplemented for {}", self.type_label()) |
| 45 |
} |
| 46 |
|
| 47 |
/// Name of the FfiConverter |
| 48 |
/// |
| 49 |
/// This is the object that contains the lower, write, lift, and read methods for this type. |
| 50 |
fn ffi_converter_name(&self) -> String { |
| 51 |
format!("FfiConverter{}", self.canonical_name()) |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
// Taken from Python's `keyword.py` module. |
| 56 |
static KEYWORDS: Lazy<HashSet<String>> = Lazy::new(|| { |
| 57 |
let kwlist = vec![ |
| 58 |
"False", |
| 59 |
"None", |
| 60 |
"True", |
| 61 |
"__peg_parser__", |
| 62 |
"and", |
| 63 |
"as", |
| 64 |
"assert", |
| 65 |
"async", |
| 66 |
"await", |
| 67 |
"break", |
| 68 |
"class", |
| 69 |
"continue", |
| 70 |
"def", |
| 71 |
"del", |
| 72 |
"elif", |
| 73 |
"else", |
| 74 |
"except", |
| 75 |
"finally", |
| 76 |
"for", |
| 77 |
"from", |
| 78 |
"global", |
| 79 |
"if", |
| 80 |
"import", |
| 81 |
"in", |
| 82 |
"is", |
| 83 |
"lambda", |
| 84 |
"nonlocal", |
| 85 |
"not", |
| 86 |
"or", |
| 87 |
"pass", |
| 88 |
"raise", |
| 89 |
"return", |
| 90 |
"try", |
| 91 |
"while", |
| 92 |
"with", |
| 93 |
"yield", |
| 94 |
]; |
| 95 |
HashSet::from_iter(kwlist.into_iter().map(|s| s.to_string())) |
| 96 |
}); |
| 97 |
|
| 98 |
// Config options to customize the generated python. |
| 99 |
#[derive(Debug, Clone, Default, Serialize, Deserialize)] |
| 100 |
pub struct Config { |
| 101 |
pub(super) cdylib_name: Option<String>, |
| 102 |
#[serde(default)] |
| 103 |
custom_types: HashMap<String, CustomTypeConfig>, |
| 104 |
#[serde(default)] |
| 105 |
external_packages: HashMap<String, String>, |
| 106 |
} |
| 107 |
|
| 108 |
#[derive(Debug, Clone, Default, Serialize, Deserialize)] |
| 109 |
#[serde(default)] |
| 110 |
pub struct CustomTypeConfig { |
| 111 |
// This `CustomTypeConfig` doesn't have a `type_name` like the others -- which is why we have |
| 112 |
// separate structs rather than a shared one. |
| 113 |
imports: Option<Vec<String>>, |
| 114 |
into_custom: String, // b/w compat alias for lift |
| 115 |
lift: String, |
| 116 |
from_custom: String, // b/w compat alias for lower |
| 117 |
lower: String, |
| 118 |
} |
| 119 |
|
| 120 |
// functions replace literal "{}" in strings with a specified value. |
| 121 |
impl CustomTypeConfig { |
| 122 |
fn lift(&self, name: &str) -> String { |
| 123 |
let converter = if self.lift.is_empty() { |
| 124 |
&self.into_custom |
| 125 |
} else { |
| 126 |
&self.lift |
| 127 |
}; |
| 128 |
converter.replace("{}", name) |
| 129 |
} |
| 130 |
fn lower(&self, name: &str) -> String { |
| 131 |
let converter = if self.lower.is_empty() { |
| 132 |
&self.from_custom |
| 133 |
} else { |
| 134 |
&self.lower |
| 135 |
}; |
| 136 |
converter.replace("{}", name) |
| 137 |
} |
| 138 |
} |
| 139 |
|
| 140 |
impl Config { |
| 141 |
pub fn cdylib_name(&self) -> String { |
| 142 |
if let Some(cdylib_name) = &self.cdylib_name { |
| 143 |
cdylib_name.clone() |
| 144 |
} else { |
| 145 |
"uniffi".into() |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
/// Get the package name for a given external namespace. |
| 150 |
pub fn module_for_namespace(&self, ns: &str) -> String { |
| 151 |
let ns = ns.to_string().to_snake_case(); |
| 152 |
match self.external_packages.get(&ns) { |
| 153 |
None => format!(".{ns}"), |
| 154 |
Some(value) if value.is_empty() => ns, |
| 155 |
Some(value) => format!("{value}.{ns}"), |
| 156 |
} |
| 157 |
} |
| 158 |
} |
| 159 |
|
| 160 |
// Generate python bindings for the given ComponentInterface, as a string. |
| 161 |
pub fn generate_python_bindings(config: &Config, ci: &mut ComponentInterface) -> Result<String> { |
| 162 |
PythonWrapper::new(config.clone(), ci) |
| 163 |
.render() |
| 164 |
.context("failed to render python bindings") |
| 165 |
} |
| 166 |
|
| 167 |
/// A struct to record a Python import statement. |
| 168 |
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] |
| 169 |
pub enum ImportRequirement { |
| 170 |
/// A simple module import. |
| 171 |
Module { mod_name: String }, |
| 172 |
/// A single symbol from a module. |
| 173 |
Symbol { |
| 174 |
mod_name: String, |
| 175 |
symbol_name: String, |
| 176 |
}, |
| 177 |
/// A single symbol from a module with the specified local name. |
| 178 |
SymbolAs { |
| 179 |
mod_name: String, |
| 180 |
symbol_name: String, |
| 181 |
as_name: String, |
| 182 |
}, |
| 183 |
} |
| 184 |
|
| 185 |
impl ImportRequirement { |
| 186 |
/// Render the Python import statement. |
| 187 |
fn render(&self) -> String { |
| 188 |
match &self { |
| 189 |
ImportRequirement::Module { mod_name } => format!("import {mod_name}"), |
| 190 |
ImportRequirement::Symbol { |
| 191 |
mod_name, |
| 192 |
symbol_name, |
| 193 |
} => format!("from {mod_name} import {symbol_name}"), |
| 194 |
ImportRequirement::SymbolAs { |
| 195 |
mod_name, |
| 196 |
symbol_name, |
| 197 |
as_name, |
| 198 |
} => format!("from {mod_name} import {symbol_name} as {as_name}"), |
| 199 |
} |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
/// Renders Python helper code for all types |
| 204 |
/// |
| 205 |
/// This template is a bit different than others in that it stores internal state from the render |
| 206 |
/// process. Make sure to only call `render()` once. |
| 207 |
#[derive(Template)] |
| 208 |
#[template(syntax = "py", escape = "none", path = "Types.py")] |
| 209 |
pub struct TypeRenderer<'a> { |
| 210 |
python_config: &'a Config, |
| 211 |
ci: &'a ComponentInterface, |
| 212 |
// Track imports added with the `add_import()` macro |
| 213 |
imports: RefCell<BTreeSet<ImportRequirement>>, |
| 214 |
} |
| 215 |
|
| 216 |
impl<'a> TypeRenderer<'a> { |
| 217 |
fn new(python_config: &'a Config, ci: &'a ComponentInterface) -> Self { |
| 218 |
Self { |
| 219 |
python_config, |
| 220 |
ci, |
| 221 |
imports: RefCell::new(BTreeSet::new()), |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
// The following methods are used by the `Types.py` macros. |
| 226 |
|
| 227 |
// Helper to add an import statement |
| 228 |
// |
| 229 |
// Call this inside your template to cause an import statement to be added at the top of the |
| 230 |
// file. Imports will be sorted and de-deuped. |
| 231 |
// |
| 232 |
// Returns an empty string so that it can be used inside an askama `{{ }}` block. |
| 233 |
fn add_import(&self, name: &str) -> &str { |
| 234 |
self.imports.borrow_mut().insert(ImportRequirement::Module { |
| 235 |
mod_name: name.to_owned(), |
| 236 |
}); |
| 237 |
"" |
| 238 |
} |
| 239 |
|
| 240 |
// Like add_import, but arranges for `from module import name`. |
| 241 |
fn add_import_of(&self, mod_name: &str, name: &str) -> &str { |
| 242 |
self.imports.borrow_mut().insert(ImportRequirement::Symbol { |
| 243 |
mod_name: mod_name.to_owned(), |
| 244 |
symbol_name: name.to_owned(), |
| 245 |
}); |
| 246 |
"" |
| 247 |
} |
| 248 |
|
| 249 |
// Like add_import, but arranges for `from module import name as other`. |
| 250 |
fn add_import_of_as(&self, mod_name: &str, symbol_name: &str, as_name: &str) -> &str { |
| 251 |
self.imports |
| 252 |
.borrow_mut() |
| 253 |
.insert(ImportRequirement::SymbolAs { |
| 254 |
mod_name: mod_name.to_owned(), |
| 255 |
symbol_name: symbol_name.to_owned(), |
| 256 |
as_name: as_name.to_owned(), |
| 257 |
}); |
| 258 |
"" |
| 259 |
} |
| 260 |
|
| 261 |
// An inefficient algo to return type aliases needed for custom types |
| 262 |
// in an order such that dependencies are in the correct order. |
| 263 |
// Eg, if there's a custom type `Guid` -> `str` and another `GuidWrapper` -> `Guid`, |
| 264 |
// it's important the type alias for `Guid` appears first. Fails to handle |
| 265 |
// another level of indirection (eg, `A { builtin: C}, B { }, C { builtin: B })`) |
| 266 |
// but that's pathological :) |
| 267 |
fn get_custom_type_aliases(&self) -> Vec<(String, &Type)> { |
| 268 |
let mut ordered = vec![]; |
| 269 |
for type_ in self.ci.iter_local_types() { |
| 270 |
if !self.ci.is_external(type_) { |
| 271 |
if let Type::Custom { name, builtin, .. } = type_ { |
| 272 |
match ordered.iter().position(|x: &(&str, &Type)| { |
| 273 |
x.1.iter_types() |
| 274 |
.any(|nested_type| *name == nested_type.as_codetype().type_label()) |
| 275 |
}) { |
| 276 |
// This 'name' appears as a builtin, so we must insert our type first. |
| 277 |
Some(pos) => ordered.insert(pos, (name, builtin)), |
| 278 |
// Otherwise at the end. |
| 279 |
None => ordered.push((name, builtin)), |
| 280 |
} |
| 281 |
} |
| 282 |
} |
| 283 |
} |
| 284 |
ordered |
| 285 |
.into_iter() |
| 286 |
.map(|(n, t)| (PythonCodeOracle.class_name(n), t)) |
| 287 |
.collect() |
| 288 |
} |
| 289 |
|
| 290 |
// Sort object types to avoid forward references; traits before everything else. |
| 291 |
fn iter_sorted_object_types(&self) -> impl Iterator<Item = &Type> { |
| 292 |
let mut obs: Vec<&Type> = self |
| 293 |
.ci |
| 294 |
.iter_local_types() |
| 295 |
.filter(|t| matches!(t, Type::Object { .. })) |
| 296 |
.collect(); |
| 297 |
obs.sort_by_key(|t| !matches!(t, Type::Object { imp, .. } if imp.is_trait_interface())); |
| 298 |
obs.into_iter() |
| 299 |
} |
| 300 |
} |
| 301 |
|
| 302 |
#[derive(Template)] |
| 303 |
#[template(syntax = "py", escape = "none", path = "wrapper.py")] |
| 304 |
pub struct PythonWrapper<'a> { |
| 305 |
ci: &'a ComponentInterface, |
| 306 |
config: Config, |
| 307 |
type_helper_code: String, |
| 308 |
type_imports: BTreeSet<ImportRequirement>, |
| 309 |
} |
| 310 |
impl<'a> PythonWrapper<'a> { |
| 311 |
pub fn new(config: Config, ci: &'a mut ComponentInterface) -> Self { |
| 312 |
ci.visit_mut(&PythonCodeOracle); |
| 313 |
|
| 314 |
let type_renderer = TypeRenderer::new(&config, ci); |
| 315 |
let type_helper_code = type_renderer.render().unwrap(); |
| 316 |
let type_imports = type_renderer.imports.into_inner(); |
| 317 |
|
| 318 |
Self { |
| 319 |
config, |
| 320 |
ci, |
| 321 |
type_helper_code, |
| 322 |
type_imports, |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
pub fn imports(&self) -> Vec<ImportRequirement> { |
| 327 |
self.type_imports.iter().cloned().collect() |
| 328 |
} |
| 329 |
} |
| 330 |
|
| 331 |
fn fixup_keyword(name: String) -> String { |
| 332 |
if KEYWORDS.contains(&name) { |
| 333 |
format!("_{name}") |
| 334 |
} else { |
| 335 |
name |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
#[derive(Clone, Default)] |
| 340 |
pub struct PythonCodeOracle; |
| 341 |
|
| 342 |
impl PythonCodeOracle { |
| 343 |
fn find(&self, type_: &Type) -> Box<dyn CodeType> { |
| 344 |
type_.clone().as_type().as_codetype() |
| 345 |
} |
| 346 |
|
| 347 |
/// Get the idiomatic Python rendering of a class name (for enums, records, errors, etc). |
| 348 |
fn class_name(&self, nm: &str) -> String { |
| 349 |
fixup_keyword(nm.to_string().to_upper_camel_case()) |
| 350 |
} |
| 351 |
|
| 352 |
/// Get the idiomatic Python rendering of a function name. |
| 353 |
fn fn_name(&self, nm: &str) -> String { |
| 354 |
fixup_keyword(nm.to_string().to_snake_case()) |
| 355 |
} |
| 356 |
|
| 357 |
/// Get the idiomatic Python rendering of a variable name. |
| 358 |
fn var_name(&self, nm: &str) -> String { |
| 359 |
fixup_keyword(nm.to_string().to_snake_case()) |
| 360 |
} |
| 361 |
|
| 362 |
/// Get the idiomatic Python rendering of an individual enum variant. |
| 363 |
fn enum_variant_name(&self, nm: &str) -> String { |
| 364 |
fixup_keyword(nm.to_string().to_shouty_snake_case()) |
| 365 |
} |
| 366 |
|
| 367 |
/// Get the idiomatic Python rendering of an FFI callback function name |
| 368 |
fn ffi_callback_name(&self, nm: &str) -> String { |
| 369 |
format!("_UNIFFI_{}", nm.to_shouty_snake_case()) |
| 370 |
} |
| 371 |
|
| 372 |
/// Get the idiomatic Python rendering of an FFI struct name |
| 373 |
fn ffi_struct_name(&self, nm: &str) -> String { |
| 374 |
// The ctypes docs use both SHOUTY_SNAKE_CASE AND UpperCamelCase for structs. Let's use |
| 375 |
// UpperCamelCase and reserve shouting for global variables |
| 376 |
format!("_Uniffi{}", nm.to_upper_camel_case()) |
| 377 |
} |
| 378 |
|
| 379 |
fn ffi_type_label(&self, ffi_type: &FfiType, ci: &ComponentInterface) -> String { |
| 380 |
match ffi_type { |
| 381 |
FfiType::Int8 => "ctypes.c_int8".to_string(), |
| 382 |
FfiType::UInt8 => "ctypes.c_uint8".to_string(), |
| 383 |
FfiType::Int16 => "ctypes.c_int16".to_string(), |
| 384 |
FfiType::UInt16 => "ctypes.c_uint16".to_string(), |
| 385 |
FfiType::Int32 => "ctypes.c_int32".to_string(), |
| 386 |
FfiType::UInt32 => "ctypes.c_uint32".to_string(), |
| 387 |
FfiType::Int64 => "ctypes.c_int64".to_string(), |
| 388 |
FfiType::UInt64 => "ctypes.c_uint64".to_string(), |
| 389 |
FfiType::Float32 => "ctypes.c_float".to_string(), |
| 390 |
FfiType::Float64 => "ctypes.c_double".to_string(), |
| 391 |
FfiType::Handle => "ctypes.c_uint64".to_string(), |
| 392 |
FfiType::RustArcPtr(_) => "ctypes.c_void_p".to_string(), |
| 393 |
FfiType::RustBuffer(maybe_external) => match maybe_external { |
| 394 |
Some(external_meta) if external_meta.module_path != ci.crate_name() => { |
| 395 |
format!("_UniffiRustBuffer{}", self.class_name(&external_meta.name)) |
| 396 |
} |
| 397 |
_ => "_UniffiRustBuffer".to_string(), |
| 398 |
}, |
| 399 |
FfiType::RustCallStatus => "_UniffiRustCallStatus".to_string(), |
| 400 |
FfiType::ForeignBytes => "_UniffiForeignBytes".to_string(), |
| 401 |
FfiType::Callback(name) => self.ffi_callback_name(name), |
| 402 |
FfiType::Struct(name) => self.ffi_struct_name(name), |
| 403 |
// Pointer to an `asyncio.EventLoop` instance |
| 404 |
FfiType::Reference(inner) | FfiType::MutReference(inner) => { |
| 405 |
format!("ctypes.POINTER({})", self.ffi_type_label(inner, ci)) |
| 406 |
} |
| 407 |
FfiType::VoidPointer => "ctypes.c_void_p".to_string(), |
| 408 |
} |
| 409 |
} |
| 410 |
|
| 411 |
/// Default values for FFI types |
| 412 |
/// |
| 413 |
/// Used to set a default return value when returning an error |
| 414 |
fn ffi_default_value(&self, return_type: Option<&FfiType>, ci: &ComponentInterface) -> String { |
| 415 |
match return_type { |
| 416 |
Some(t) => match t { |
| 417 |
FfiType::UInt8 |
| 418 |
| FfiType::Int8 |
| 419 |
| FfiType::UInt16 |
| 420 |
| FfiType::Int16 |
| 421 |
| FfiType::UInt32 |
| 422 |
| FfiType::Int32 |
| 423 |
| FfiType::UInt64 |
| 424 |
| FfiType::Int64 => "0".to_owned(), |
| 425 |
FfiType::Float32 | FfiType::Float64 => "0.0".to_owned(), |
| 426 |
FfiType::RustArcPtr(_) => "ctypes.c_void_p()".to_owned(), |
| 427 |
FfiType::RustBuffer(maybe_external) => match maybe_external { |
| 428 |
Some(external_meta) if external_meta.module_path != ci.crate_name() => { |
| 429 |
format!("_UniffiRustBuffer{}.default()", external_meta.name) |
| 430 |
} |
| 431 |
_ => "_UniffiRustBuffer.default()".to_owned(), |
| 432 |
}, |
| 433 |
_ => unimplemented!("FFI return type: {t:?}"), |
| 434 |
}, |
| 435 |
// When we need to use a value for void returns, we use a `u8` placeholder |
| 436 |
None => "0".to_owned(), |
| 437 |
} |
| 438 |
} |
| 439 |
} |
| 440 |
|
| 441 |
impl VisitMut for PythonCodeOracle { |
| 442 |
fn visit_record(&self, record: &mut Record) { |
| 443 |
record.rename(self.class_name(record.name())); |
| 444 |
} |
| 445 |
|
| 446 |
fn visit_object(&self, object: &mut Object) { |
| 447 |
object.rename(self.class_name(object.name())); |
| 448 |
for i in object.trait_impls_mut() { |
| 449 |
i.trait_name = self.class_name(&i.trait_name); |
| 450 |
// should i.tr_module_path be fixed? |
| 451 |
} |
| 452 |
} |
| 453 |
|
| 454 |
fn visit_field(&self, field: &mut Field) { |
| 455 |
field.rename(self.var_name(field.name())); |
| 456 |
} |
| 457 |
|
| 458 |
fn visit_ffi_field(&self, ffi_field: &mut FfiField) { |
| 459 |
ffi_field.rename(self.var_name(ffi_field.name())); |
| 460 |
} |
| 461 |
|
| 462 |
fn visit_ffi_argument(&self, ffi_argument: &mut FfiArgument) { |
| 463 |
ffi_argument.rename(self.class_name(ffi_argument.name())); |
| 464 |
} |
| 465 |
|
| 466 |
fn visit_enum(&self, _is_error: bool, enum_: &mut Enum) { |
| 467 |
enum_.rename(self.class_name(enum_.name())); |
| 468 |
} |
| 469 |
|
| 470 |
fn visit_enum_key(&self, key: &mut String) -> String { |
| 471 |
self.class_name(key) |
| 472 |
} |
| 473 |
|
| 474 |
fn visit_variant(&self, is_error: bool, variant: &mut Variant) { |
| 475 |
if is_error { |
| 476 |
variant.rename(self.class_name(variant.name())); |
| 477 |
} else { |
| 478 |
variant.rename(self.enum_variant_name(variant.name())); |
| 479 |
} |
| 480 |
} |
| 481 |
|
| 482 |
fn visit_type(&self, type_: &mut Type) { |
| 483 |
// Renaming Types is a special case. We have simple types with names like |
| 484 |
// an Object, but we also have types which have inner_types and builtin types. |
| 485 |
// Which in turn have a different name. Therefore we pass the patterns as a |
| 486 |
// function down to the renaming operation of the type itself, which can apply it |
| 487 |
// to all its nested names if needed. |
| 488 |
let name_transformer = |name: &str| self.class_name(name); |
| 489 |
type_.rename_recursive(&name_transformer); |
| 490 |
} |
| 491 |
|
| 492 |
fn visit_method(&self, method: &mut Method) { |
| 493 |
method.rename(self.fn_name(method.name())); |
| 494 |
} |
| 495 |
|
| 496 |
fn visit_argument(&self, argument: &mut Argument) { |
| 497 |
argument.rename(self.var_name(argument.name())); |
| 498 |
} |
| 499 |
|
| 500 |
fn visit_constructor(&self, constructor: &mut Constructor) { |
| 501 |
if !constructor.is_primary_constructor() { |
| 502 |
constructor.rename(self.fn_name(constructor.name())); |
| 503 |
} |
| 504 |
} |
| 505 |
|
| 506 |
fn visit_function(&self, function: &mut Function) { |
| 507 |
// Conversions for wrapper.py |
| 508 |
//TODO: Renaming the function name in wrapper.py is not currently tested |
| 509 |
function.rename(self.fn_name(function.name())); |
| 510 |
} |
| 511 |
|
| 512 |
fn visit_error_name(&self, name: &mut String) { |
| 513 |
*name = self.class_name(name); |
| 514 |
} |
| 515 |
} |
| 516 |
|
| 517 |
trait AsCodeType { |
| 518 |
fn as_codetype(&self) -> Box<dyn CodeType>; |
| 519 |
} |
| 520 |
|
| 521 |
impl<T: AsType> AsCodeType for T { |
| 522 |
fn as_codetype(&self) -> Box<dyn CodeType> { |
| 523 |
// Map `Type` instances to a `Box<dyn CodeType>` for that type. |
| 524 |
// |
| 525 |
// There is a companion match in `templates/Types.py` which performs a similar function for the |
| 526 |
// template code. |
| 527 |
// |
| 528 |
// - When adding additional types here, make sure to also add a match arm to the `Types.py` template. |
| 529 |
// - To keep things manageable, let's try to limit ourselves to these 2 mega-matches |
| 530 |
match self.as_type() { |
| 531 |
Type::UInt8 => Box::new(primitives::UInt8CodeType), |
| 532 |
Type::Int8 => Box::new(primitives::Int8CodeType), |
| 533 |
Type::UInt16 => Box::new(primitives::UInt16CodeType), |
| 534 |
Type::Int16 => Box::new(primitives::Int16CodeType), |
| 535 |
Type::UInt32 => Box::new(primitives::UInt32CodeType), |
| 536 |
Type::Int32 => Box::new(primitives::Int32CodeType), |
| 537 |
Type::UInt64 => Box::new(primitives::UInt64CodeType), |
| 538 |
Type::Int64 => Box::new(primitives::Int64CodeType), |
| 539 |
Type::Float32 => Box::new(primitives::Float32CodeType), |
| 540 |
Type::Float64 => Box::new(primitives::Float64CodeType), |
| 541 |
Type::Boolean => Box::new(primitives::BooleanCodeType), |
| 542 |
Type::String => Box::new(primitives::StringCodeType), |
| 543 |
Type::Bytes => Box::new(primitives::BytesCodeType), |
| 544 |
|
| 545 |
Type::Timestamp => Box::new(miscellany::TimestampCodeType), |
| 546 |
Type::Duration => Box::new(miscellany::DurationCodeType), |
| 547 |
|
| 548 |
Type::Enum { name, .. } => Box::new(enum_::EnumCodeType::new(name)), |
| 549 |
Type::Object { name, .. } => Box::new(object::ObjectCodeType::new(name)), |
| 550 |
Type::Record { name, .. } => Box::new(record::RecordCodeType::new(name)), |
| 551 |
Type::CallbackInterface { name, .. } => { |
| 552 |
Box::new(callback_interface::CallbackInterfaceCodeType::new(name)) |
| 553 |
} |
| 554 |
Type::Optional { inner_type } => { |
| 555 |
Box::new(compounds::OptionalCodeType::new(*inner_type)) |
| 556 |
} |
| 557 |
Type::Sequence { inner_type } => { |
| 558 |
Box::new(compounds::SequenceCodeType::new(*inner_type)) |
| 559 |
} |
| 560 |
Type::Map { |
| 561 |
key_type, |
| 562 |
value_type, |
| 563 |
} => Box::new(compounds::MapCodeType::new(*key_type, *value_type)), |
| 564 |
Type::Custom { name, .. } => Box::new(custom::CustomCodeType::new(name)), |
| 565 |
} |
| 566 |
} |
| 567 |
} |
| 568 |
|
| 569 |
pub mod filters { |
| 570 |
use crate::backend::filters::to_askama_error; |
| 571 |
|
| 572 |
use super::*; |
| 573 |
|
| 574 |
pub(super) fn type_name(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 575 |
Ok(as_ct.as_codetype().type_label()) |
| 576 |
} |
| 577 |
|
| 578 |
pub(super) fn ffi_converter_name(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 579 |
Ok(String::from("_Uniffi") + &as_ct.as_codetype().ffi_converter_name()[3..]) |
| 580 |
} |
| 581 |
|
| 582 |
pub(super) fn canonical_name(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 583 |
Ok(as_ct.as_codetype().canonical_name()) |
| 584 |
} |
| 585 |
|
| 586 |
pub(super) fn lift_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 587 |
Ok(format!("{}.lift", ffi_converter_name(as_ct)?)) |
| 588 |
} |
| 589 |
|
| 590 |
pub(super) fn check_lower_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 591 |
Ok(format!("{}.check_lower", ffi_converter_name(as_ct)?)) |
| 592 |
} |
| 593 |
|
| 594 |
pub(super) fn lower_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 595 |
Ok(format!("{}.lower", ffi_converter_name(as_ct)?)) |
| 596 |
} |
| 597 |
|
| 598 |
pub(super) fn read_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 599 |
Ok(format!("{}.read", ffi_converter_name(as_ct)?)) |
| 600 |
} |
| 601 |
|
| 602 |
pub(super) fn write_fn(as_ct: &impl AsCodeType) -> Result<String, askama::Error> { |
| 603 |
Ok(format!("{}.write", ffi_converter_name(as_ct)?)) |
| 604 |
} |
| 605 |
|
| 606 |
pub(super) fn literal_py( |
| 607 |
literal: &Literal, |
| 608 |
as_ct: &impl AsCodeType, |
| 609 |
) -> Result<String, askama::Error> { |
| 610 |
as_ct |
| 611 |
.as_codetype() |
| 612 |
.literal(literal) |
| 613 |
.map_err(|e| to_askama_error(&e)) |
| 614 |
} |
| 615 |
|
| 616 |
// Get the idiomatic Python rendering of an individual enum variant's discriminant |
| 617 |
pub fn variant_discr_literal(e: &Enum, index: &usize) -> Result<String, askama::Error> { |
| 618 |
let literal = e |
| 619 |
.variant_discr(*index) |
| 620 |
.context("invalid index") |
| 621 |
.map_err(|e| to_askama_error(&e))?; |
| 622 |
Type::UInt64 |
| 623 |
.as_codetype() |
| 624 |
.literal(&literal) |
| 625 |
.map_err(|e| to_askama_error(&e)) |
| 626 |
} |
| 627 |
|
| 628 |
pub fn ffi_type_name( |
| 629 |
type_: &FfiType, |
| 630 |
ci: &ComponentInterface, |
| 631 |
) -> Result<String, askama::Error> { |
| 632 |
Ok(PythonCodeOracle.ffi_type_label(type_, ci)) |
| 633 |
} |
| 634 |
|
| 635 |
pub fn ffi_default_value( |
| 636 |
return_type: Option<FfiType>, |
| 637 |
ci: &ComponentInterface, |
| 638 |
) -> Result<String, askama::Error> { |
| 639 |
Ok(PythonCodeOracle.ffi_default_value(return_type.as_ref(), ci)) |
| 640 |
} |
| 641 |
|
| 642 |
/// Get the idiomatic Python rendering of an FFI callback function name |
| 643 |
pub fn ffi_callback_name(nm: &str) -> Result<String, askama::Error> { |
| 644 |
Ok(PythonCodeOracle.ffi_callback_name(nm)) |
| 645 |
} |
| 646 |
|
| 647 |
/// Get the idiomatic Python rendering of an FFI struct name |
| 648 |
pub fn ffi_struct_name(nm: &str) -> Result<String, askama::Error> { |
| 649 |
Ok(PythonCodeOracle.ffi_struct_name(nm)) |
| 650 |
} |
| 651 |
|
| 652 |
/// Get the idiomatic Python rendering of docstring |
| 653 |
pub fn docstring(docstring: &str, spaces: &i32) -> Result<String, askama::Error> { |
| 654 |
let docstring = textwrap::dedent(docstring); |
| 655 |
// Escape triple quotes to avoid syntax error |
| 656 |
let escaped = docstring.replace(r#"""""#, r#"\"\"\""#); |
| 657 |
|
| 658 |
let wrapped = format!("\"\"\"\n{escaped}\n\"\"\""); |
| 659 |
|
| 660 |
let spaces = usize::try_from(*spaces).unwrap_or_default(); |
| 661 |
Ok(textwrap::indent(&wrapped, &" ".repeat(spaces))) |
| 662 |
} |
| 663 |
} |
| 664 |
|
| 665 |
#[cfg(test)] |
| 666 |
mod tests { |
| 667 |
#[test] |
| 668 |
fn test_docstring_escape() { |
| 669 |
let docstring = r#""""This is a docstring beginning with triple quotes. |
| 670 |
Contains "quotes" in it. |
| 671 |
It also has a triple quote: """ |
| 672 |
And a even longer quote: """"""#; |
| 673 |
|
| 674 |
let expected = r#"""" |
| 675 |
\"\"\"This is a docstring beginning with triple quotes. |
| 676 |
Contains "quotes" in it. |
| 677 |
It also has a triple quote: \"\"\" |
| 678 |
And a even longer quote: \"\"\""" |
| 679 |
""""#; |
| 680 |
|
| 681 |
assert_eq!(super::filters::docstring(docstring, &0).unwrap(), expected); |
| 682 |
} |
| 683 |
} |