Debian Codegraph @

third_party/rust/uniffi_bindgen/src/bindings/swift/gen_swift/mod.rs

raw
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 once_cell::sync::Lazy;
6 use std::borrow::Borrow;
7 use std::cell::RefCell;
8 use std::collections::{BTreeSet, HashMap, HashSet};
9 use std::fmt::Debug;
10
11 use anyhow::{Context, Result};
12 use askama::Template;
13
14 use heck::{ToLowerCamelCase, ToShoutySnakeCase, ToUpperCamelCase};
15 use serde::{Deserialize, Serialize};
16
17 use super::Bindings;
18
19 use crate::interface::*;
20
21 mod callback_interface;
22 mod compounds;
23 mod custom;
24 mod enum_;
25 mod miscellany;
26 mod object;
27 mod primitives;
28 mod record;
29
30 /// A trait tor the implementation.
31 trait CodeType: Debug {
32 /// The language specific label used to reference this type. This will be used in
33 /// method signatures and property declarations.
34 fn type_label(&self) -> String;
35
36 /// A representation of this type label that can be used as part of another
37 /// identifier. e.g. `read_foo()`, or `FooInternals`.
38 ///
39 /// This is especially useful when creating specialized objects or methods to deal
40 /// with this type only.
41 fn canonical_name(&self) -> String {
42 self.type_label()
43 }
44
45 fn literal(&self, _literal: &Literal) -> Result<String> {
46 unimplemented!("Unimplemented for {}", self.type_label())
47 }
48
49 /// Name of the FfiConverter
50 ///
51 /// This is the object that contains the lower, write, lift, and read methods for this type.
52 fn ffi_converter_name(&self) -> String {
53 format!("FfiConverter{}", self.canonical_name())
54 }
55
56 /// Function to run at startup
57 fn initialization_fn(&self) -> Option<String> {
58 None
59 }
60 }
61
62 /// From <https://docs.swift.org/swift-book/documentation/the-swift-programming-language/lexicalstructure/#Keywords-and-Punctuation>
63 static KEYWORDS: Lazy<HashSet<String>> = Lazy::new(|| {
64 [
65 // Keywords used in declarations:
66 "associatedtype",
67 "class",
68 "deinit",
69 "enum",
70 "extension",
71 "fileprivate",
72 "func",
73 "import",
74 "init",
75 "inout",
76 "internal",
77 "let",
78 "open",
79 "operator",
80 "private",
81 "precedencegroup",
82 "protocol",
83 "public",
84 "rethrows",
85 "static",
86 "struct",
87 "subscript",
88 "typealias",
89 "var",
90 // Keywords used in statements:
91 "break",
92 "case",
93 "catch",
94 "continue",
95 "default",
96 "defer",
97 "do",
98 "else",
99 "fallthrough",
100 "for",
101 "guard",
102 "if",
103 "in",
104 "repeat",
105 "return",
106 "throw",
107 "switch",
108 "where",
109 "while",
110 // Keywords used in expressions and types:
111 "Any",
112 "as",
113 "await",
114 "catch",
115 "false",
116 "is",
117 "nil",
118 "rethrows",
119 "self",
120 "Self",
121 "super",
122 "throw",
123 "throws",
124 "true",
125 "try",
126 ]
127 .iter()
128 .map(ToString::to_string)
129 .collect::<HashSet<_>>()
130 });
131
132 /// Quote a name for use in a context where keywords must be quoted
133 pub fn quote_general_keyword(nm: String) -> String {
134 if KEYWORDS.contains(&nm) {
135 format!("`{nm}`")
136 } else {
137 nm
138 }
139 }
140
141 /// Per <https://docs.swift.org/swift-book/documentation/the-swift-programming-language/lexicalstructure/#Keywords-and-Punctuation> subset of keywords which need quoting in arg context.
142 static ARG_KEYWORDS: Lazy<HashSet<String>> = Lazy::new(|| {
143 ["inout", "var", "let"]
144 .iter()
145 .map(ToString::to_string)
146 .collect::<HashSet<_>>()
147 });
148
149 /// Quote a name for use in arg context where fewer keywords must be quoted
150 pub fn quote_arg_keyword(nm: String) -> String {
151 if ARG_KEYWORDS.contains(&nm) {
152 format!("`{nm}`")
153 } else {
154 nm
155 }
156 }
157
158 /// Config options for the caller to customize the generated Swift.
159 ///
160 /// Note that this can only be used to control details of the Swift *that do not affect the underlying component*,
161 /// since the details of the underlying component are entirely determined by the `ComponentInterface`.
162 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
163 pub struct Config {
164 pub(super) module_name: Option<String>,
165 ffi_module_name: Option<String>,
166 ffi_module_filename: Option<String>,
167 generate_module_map: Option<bool>,
168 #[serde(default)]
169 omit_checksums: bool,
170 omit_argument_labels: Option<bool>,
171 generate_immutable_records: Option<bool>,
172 omit_localized_error_conformance: Option<bool>,
173 generate_case_iterable_conformance: Option<bool>,
174 generate_codable_conformance: Option<bool>,
175 #[serde(default)]
176 custom_types: HashMap<String, CustomTypeConfig>,
177 #[serde(default)]
178 link_frameworks: Vec<String>,
179 }
180
181 #[derive(Debug, Default, Clone, Serialize, Deserialize)]
182 #[serde(default)]
183 pub struct CustomTypeConfig {
184 imports: Option<Vec<String>>,
185 type_name: Option<String>,
186 into_custom: String, // b/w compat alias for lift
187 lift: String,
188 from_custom: String, // b/w compat alias for lower
189 lower: String,
190 }
191
192 // functions replace literal "{}" in strings with a specified value.
193 impl CustomTypeConfig {
194 fn lift(&self, name: &str) -> String {
195 let converter = if self.lift.is_empty() {
196 &self.into_custom
197 } else {
198 &self.lift
199 };
200 converter.replace("{}", name)
201 }
202 fn lower(&self, name: &str) -> String {
203 let converter = if self.lower.is_empty() {
204 &self.from_custom
205 } else {
206 &self.lower
207 };
208 converter.replace("{}", name)
209 }
210 }
211
212 impl Config {
213 /// The name of the Swift module containing the high-level foreign-language bindings.
214 /// Panics if the module name hasn't been configured.
215 pub fn module_name(&self) -> String {
216 self.module_name
217 .as_ref()
218 .expect("module name should have been set in update_component_configs")
219 .clone()
220 }
221
222 /// The name of the lower-level C module containing the FFI declarations.
223 pub fn ffi_module_name(&self) -> String {
224 match self.ffi_module_name.as_ref() {
225 Some(name) => name.clone(),
226 None => format!("{}FFI", self.module_name()),
227 }
228 }
229
230 /// The filename stem for the lower-level C module containing the FFI declarations.
231 pub fn ffi_module_filename(&self) -> String {
232 match self.ffi_module_filename.as_ref() {
233 Some(name) => name.clone(),
234 None => self.ffi_module_name(),
235 }
236 }
237
238 /// The name of the `.modulemap` file for the lower-level C module with FFI declarations.
239 pub fn modulemap_filename(&self) -> String {
240 format!("{}.modulemap", self.ffi_module_filename())
241 }
242
243 /// The name of the `.h` file for the lower-level C module with FFI declarations.
244 pub fn header_filename(&self) -> String {
245 format!("{}.h", self.ffi_module_filename())
246 }
247
248 /// Whether to generate a `.modulemap` file for the lower-level C module with FFI declarations.
249 pub fn generate_module_map(&self) -> bool {
250 self.generate_module_map.unwrap_or(true)
251 }
252
253 /// Whether to omit argument labels in Swift function definitions.
254 pub fn omit_argument_labels(&self) -> bool {
255 self.omit_argument_labels.unwrap_or(false)
256 }
257
258 /// Whether to generate immutable records (`let` instead of `var`)
259 pub fn generate_immutable_records(&self) -> bool {
260 self.generate_immutable_records.unwrap_or(false)
261 }
262
263 /// Whether to make generated error types conform to `LocalizedError`. Default: false.
264 pub fn omit_localized_error_conformance(&self) -> bool {
265 self.omit_localized_error_conformance.unwrap_or(false)
266 }
267
268 /// Whether to make simple generated enum and error types conform to `CaseIterable`. Default: false.
269 pub fn generate_case_iterable_conformance(&self) -> bool {
270 self.generate_case_iterable_conformance.unwrap_or(false)
271 }
272
273 /// Whether to make generated records, enums and errors conform to `Codable`. Default: false.
274 pub fn generate_codable_conformance(&self) -> bool {
275 self.generate_codable_conformance.unwrap_or(false)
276 }
277
278 /// Extra frameworks to link this Swift module against. This is populated in the modulemap file,
279 /// usually as part of an `xcframework`.
280 pub fn link_frameworks(&self) -> Vec<String> {
281 self.link_frameworks.clone()
282 }
283 }
284
285 // Given a trait, work out what the protocol name we generate for it.
286 // This differs based on whether the trait supports foreign impls (ie,
287 // whether is has a "callback interface".
288 fn trait_protocol_name(ci: &ComponentInterface, name: &str) -> Result<String> {
289 let (obj_name, has_callback_interface) = match ci.get_object_definition(name) {
290 Some(obj) => (obj.name(), obj.has_callback_interface()),
291 None => (
292 ci.get_callback_interface_definition(name)
293 .ok_or_else(|| anyhow::anyhow!("no interface {}", name))?
294 .name(),
295 true,
296 ),
297 };
298 let class_name = SwiftCodeOracle.class_name(obj_name);
299 if has_callback_interface {
300 Ok(class_name)
301 } else {
302 Ok(format!("{class_name}Protocol"))
303 }
304 }
305
306 /// Generate UniFFI component bindings for Swift, as strings in memory.
307 pub fn generate_bindings(config: &Config, ci: &ComponentInterface) -> Result<Bindings> {
308 let header = BridgingHeader::new(config, ci)
309 .render()
310 .context("failed to render Swift bridging header")?;
311 let library = SwiftWrapper::new(config.clone(), ci)
312 .render()
313 .context("failed to render Swift library")?;
314 let modulemap = if config.generate_module_map() {
315 Some(
316 ModuleMap::new_for_single_component(config, ci)
317 .render()
318 .context("failed to render Swift modulemap")?,
319 )
320 } else {
321 None
322 };
323 Ok(Bindings {
324 library,
325 header,
326 modulemap,
327 })
328 }
329
330 /// Generate the bridging header for a component
331 pub fn generate_header(config: &Config, ci: &ComponentInterface) -> Result<String> {
332 BridgingHeader::new(config, ci)
333 .render()
334 .context("failed to render Swift bridging header")
335 }
336
337 /// Generate the swift source for a component
338 pub fn generate_swift(config: &Config, ci: &ComponentInterface) -> Result<String> {
339 SwiftWrapper::new(config.clone(), ci)
340 .render()
341 .context("failed to render Swift library")
342 }
343
344 /// Generate the modulemap for a set of components
345 pub fn generate_modulemap(
346 module_name: String,
347 header_filenames: Vec<String>,
348 xcframework: bool,
349 link_frameworks: Vec<String>,
350 ) -> Result<String> {
351 ModuleMap {
352 module_name,
353 header_filenames,
354 xcframework,
355 link_frameworks,
356 }
357 .render()
358 .context("failed to render Swift library")
359 }
360
361 /// Renders Swift helper code for all types
362 ///
363 /// This template is a bit different than others in that it stores internal state from the render
364 /// process. Make sure to only call `render()` once.
365 #[derive(Template)]
366 #[template(syntax = "swift", escape = "none", path = "Types.swift")]
367 pub struct TypeRenderer<'a> {
368 config: &'a Config,
369 ci: &'a ComponentInterface,
370 // Track imports added with the `add_import()` macro
371 imports: RefCell<BTreeSet<String>>,
372 }
373
374 impl<'a> TypeRenderer<'a> {
375 fn new(config: &'a Config, ci: &'a ComponentInterface) -> Self {
376 Self {
377 config,
378 ci,
379 imports: RefCell::new(BTreeSet::new()),
380 }
381 }
382
383 // The following methods are used by the `Types.swift` macros.
384
385 // Helper to add an import statement
386 //
387 // Call this inside your template to cause an import statement to be added at the top of the
388 // file. Imports will be sorted and de-deuped.
389 //
390 // Returns an empty string so that it can be used inside an askama `{{ }}` block.
391 fn add_import(&self, name: &str) -> &str {
392 self.imports.borrow_mut().insert(name.to_owned());
393 ""
394 }
395 }
396
397 /// Template for generating the `.h` file that defines the low-level C FFI.
398 ///
399 /// This file defines only the low-level structs and functions that are exposed
400 /// by the compiled Rust code. It gets wrapped into a higher-level API by the
401 /// code from [`SwiftWrapper`].
402 #[derive(Template)]
403 #[template(syntax = "c", escape = "none", path = "BridgingHeaderTemplate.h")]
404 pub struct BridgingHeader<'config, 'ci> {
405 _config: &'config Config,
406 ci: &'ci ComponentInterface,
407 }
408
409 impl<'config, 'ci> BridgingHeader<'config, 'ci> {
410 pub fn new(config: &'config Config, ci: &'ci ComponentInterface) -> Self {
411 Self {
412 _config: config,
413 ci,
414 }
415 }
416 }
417
418 /// Template for generating the `.modulemap` file that exposes the low-level C FFI.
419 ///
420 /// This file defines how the low-level C FFI from [`BridgingHeader`] gets exposed
421 /// as a Swift module that can be called by other Swift code. In our case, its only
422 /// job is to define the *name* of the Swift module that will contain the FFI functions
423 /// so that it can be imported by the higher-level code in from [`SwiftWrapper`].
424 #[derive(Template)]
425 #[template(syntax = "c", escape = "none", path = "ModuleMapTemplate.modulemap")]
426 pub struct ModuleMap {
427 module_name: String,
428 header_filenames: Vec<String>,
429 xcframework: bool,
430 link_frameworks: Vec<String>,
431 }
432
433 impl ModuleMap {
434 pub fn new_for_single_component(config: &Config, _ci: &ComponentInterface) -> Self {
435 Self {
436 module_name: config.ffi_module_name(),
437 header_filenames: vec![config.header_filename()],
438 xcframework: false,
439 link_frameworks: config.link_frameworks(),
440 }
441 }
442 }
443
444 #[derive(Template)]
445 #[template(syntax = "swift", escape = "none", path = "wrapper.swift")]
446 pub struct SwiftWrapper<'a> {
447 config: Config,
448 ci: &'a ComponentInterface,
449 type_helper_code: String,
450 type_imports: BTreeSet<String>,
451 ensure_init_fn_name: String,
452 }
453 impl<'a> SwiftWrapper<'a> {
454 pub fn new(config: Config, ci: &'a ComponentInterface) -> Self {
455 let type_renderer = TypeRenderer::new(&config, ci);
456 let type_helper_code = type_renderer.render().unwrap();
457 let type_imports = type_renderer.imports.into_inner();
458 Self {
459 config,
460 ci,
461 type_helper_code,
462 type_imports,
463 ensure_init_fn_name: format!(
464 "uniffiEnsure{}Initialized",
465 ci.crate_name().to_upper_camel_case()
466 ),
467 }
468 }
469
470 pub fn imports(&self) -> Vec<String> {
471 self.type_imports.iter().cloned().collect()
472 }
473
474 pub fn initialization_fns(&self) -> Vec<String> {
475 let init_fns = self
476 .ci
477 .iter_local_types()
478 .map(|t| SwiftCodeOracle.find(t))
479 .filter_map(|ct| ct.initialization_fn());
480
481 // Also call global initialization function for any external type we use.
482 // For example, we need to make sure that all callback interface vtables are registered
483 // (#2343).
484 let extern_module_init_fns = self
485 .ci
486 .iter_external_types()
487 .filter_map(|t| t.module_path())
488 .map(|module_path| {
489 format!(
490 "uniffiEnsure{}Initialized",
491 module_path.to_upper_camel_case()
492 )
493 })
494 // Collect into a hash set to de-dup
495 .collect::<HashSet<_>>();
496
497 init_fns.chain(extern_module_init_fns).collect()
498 }
499 }
500
501 #[derive(Clone)]
502 pub struct SwiftCodeOracle;
503
504 impl SwiftCodeOracle {
505 // Map `Type` instances to a `Box<dyn CodeType>` for that type.
506 //
507 // There is a companion match in `templates/Types.swift` which performs a similar function for the
508 // template code.
509 //
510 // - When adding additional types here, make sure to also add a match arm to the `Types.swift` template.
511 // - To keep things manageable, let's try to limit ourselves to these 2 mega-matches
512 fn create_code_type(&self, type_: Type) -> Box<dyn CodeType> {
513 match type_ {
514 Type::UInt8 => Box::new(primitives::UInt8CodeType),
515 Type::Int8 => Box::new(primitives::Int8CodeType),
516 Type::UInt16 => Box::new(primitives::UInt16CodeType),
517 Type::Int16 => Box::new(primitives::Int16CodeType),
518 Type::UInt32 => Box::new(primitives::UInt32CodeType),
519 Type::Int32 => Box::new(primitives::Int32CodeType),
520 Type::UInt64 => Box::new(primitives::UInt64CodeType),
521 Type::Int64 => Box::new(primitives::Int64CodeType),
522 Type::Float32 => Box::new(primitives::Float32CodeType),
523 Type::Float64 => Box::new(primitives::Float64CodeType),
524 Type::Boolean => Box::new(primitives::BooleanCodeType),
525 Type::String => Box::new(primitives::StringCodeType),
526 Type::Bytes => Box::new(primitives::BytesCodeType),
527
528 Type::Timestamp => Box::new(miscellany::TimestampCodeType),
529 Type::Duration => Box::new(miscellany::DurationCodeType),
530
531 Type::Enum { name, .. } => Box::new(enum_::EnumCodeType::new(name)),
532 Type::Object { name, imp, .. } => Box::new(object::ObjectCodeType::new(name, imp)),
533 Type::Record { name, .. } => Box::new(record::RecordCodeType::new(name)),
534 Type::CallbackInterface { name, .. } => {
535 Box::new(callback_interface::CallbackInterfaceCodeType::new(name))
536 }
537 Type::Optional { inner_type } => {
538 Box::new(compounds::OptionalCodeType::new(*inner_type))
539 }
540 Type::Sequence { inner_type } => {
541 Box::new(compounds::SequenceCodeType::new(*inner_type))
542 }
543 Type::Map {
544 key_type,
545 value_type,
546 } => Box::new(compounds::MapCodeType::new(*key_type, *value_type)),
547 Type::Custom { name, .. } => Box::new(custom::CustomCodeType::new(name)),
548 }
549 }
550
551 fn find(&self, type_: &Type) -> Box<dyn CodeType> {
552 self.create_code_type(type_.clone())
553 }
554
555 /// Get the idiomatic Swift rendering of a class name (for enums, records, errors, etc).
556 fn class_name<S: AsRef<str>>(&self, nm: S) -> String {
557 nm.as_ref().to_string().to_upper_camel_case()
558 }
559
560 /// Get the idiomatic Swift rendering of a function name.
561 fn fn_name<S: AsRef<str>>(&self, nm: S) -> String {
562 nm.as_ref().to_string().to_lower_camel_case()
563 }
564
565 /// Get the idiomatic Swift rendering of a variable name.
566 fn var_name<S: AsRef<str>>(&self, nm: S) -> String {
567 nm.as_ref().to_string().to_lower_camel_case()
568 }
569
570 /// Get the idiomatic Swift rendering of an individual enum variant.
571 fn enum_variant_name<S: AsRef<str>>(&self, nm: S) -> String {
572 nm.as_ref().to_string().to_lower_camel_case()
573 }
574
575 /// Get the idiomatic Swift rendering of an FFI callback function name
576 fn ffi_callback_name<S: AsRef<str>>(&self, nm: S) -> String {
577 format!("Uniffi{}", nm.as_ref().to_upper_camel_case())
578 }
579
580 /// Get the idiomatic Swift rendering of an FFI struct name
581 fn ffi_struct_name<S: AsRef<str>>(&self, nm: S) -> String {
582 format!("Uniffi{}", nm.as_ref().to_upper_camel_case())
583 }
584
585 /// Get the idiomatic Swift rendering of an if guard name
586 fn if_guard_name<S: AsRef<str>>(&self, nm: S) -> String {
587 format!("UNIFFI_FFIDEF_{}", nm.as_ref().to_shouty_snake_case())
588 }
589
590 fn ffi_type_label(&self, ffi_type: &FfiType) -> String {
591 match ffi_type {
592 FfiType::Int8 => "Int8".into(),
593 FfiType::UInt8 => "UInt8".into(),
594 FfiType::Int16 => "Int16".into(),
595 FfiType::UInt16 => "UInt16".into(),
596 FfiType::Int32 => "Int32".into(),
597 FfiType::UInt32 => "UInt32".into(),
598 FfiType::Int64 => "Int64".into(),
599 FfiType::UInt64 => "UInt64".into(),
600 FfiType::Float32 => "Float".into(),
601 FfiType::Float64 => "Double".into(),
602 FfiType::Handle => "UInt64".into(),
603 FfiType::RustArcPtr(_) => "UnsafeMutableRawPointer".into(),
604 FfiType::RustBuffer(_) => "RustBuffer".into(),
605 FfiType::RustCallStatus => "RustCallStatus".into(),
606 FfiType::ForeignBytes => "ForeignBytes".into(),
607 // Note: @escaping is required for Swift versions before 5.7 for callbacks passed into
608 // async functions. Swift 5.7 and later does not require it. We should probably remove
609 // it once we upgrade our minimum requirement to 5.7 or later.
610 FfiType::Callback(name) => format!("@escaping {}", self.ffi_callback_name(name)),
611 FfiType::Struct(name) => self.ffi_struct_name(name),
612 FfiType::Reference(inner) => {
613 format!("UnsafePointer<{}>", self.ffi_type_label(inner))
614 }
615 FfiType::MutReference(inner) => {
616 format!("UnsafeMutablePointer<{}>", self.ffi_type_label(inner))
617 }
618 FfiType::VoidPointer => "UnsafeMutableRawPointer".into(),
619 }
620 }
621
622 /// Default values for FFI types
623 ///
624 /// Used to set a default return value when returning an error
625 fn ffi_default_value(&self, return_type: Option<&FfiType>) -> String {
626 match return_type {
627 Some(t) => match t {
628 FfiType::UInt8
629 | FfiType::Int8
630 | FfiType::UInt16
631 | FfiType::Int16
632 | FfiType::UInt32
633 | FfiType::Int32
634 | FfiType::UInt64
635 | FfiType::Int64 => "0".to_owned(),
636 FfiType::Float32 | FfiType::Float64 => "0.0".to_owned(),
637 FfiType::RustArcPtr(_) => "nil".to_owned(),
638 FfiType::RustBuffer(_) => "RustBuffer.empty()".to_owned(),
639 _ => unimplemented!("FFI return type: {t:?}"),
640 },
641 // When we need to use a value for void returns, we use a `u8` placeholder
642 None => "0".to_owned(),
643 }
644 }
645
646 /// Get the name of the protocol and class name for an object.
647 ///
648 /// If we support callback interfaces, the protocol name is the object name, and the class name is derived from that.
649 /// Otherwise, the class name is the object name and the protocol name is derived from that.
650 ///
651 /// This split determines what types `FfiConverter.lower()` inputs. If we support callback
652 /// interfaces, `lower` must lower anything that implements the protocol. If not, then lower
653 /// only lowers the concrete class.
654 fn object_names(&self, obj: &Object) -> (String, String) {
655 let class_name = self.class_name(obj.name());
656 if obj.has_callback_interface() {
657 let impl_name = format!("{class_name}Impl");
658 (class_name, impl_name)
659 } else {
660 (format!("{class_name}Protocol"), class_name)
661 }
662 }
663 }
664
665 pub mod filters {
666 use super::*;
667 pub use crate::backend::filters::*;
668 use uniffi_meta::LiteralMetadata;
669
670 fn oracle() -> &'static SwiftCodeOracle {
671 &SwiftCodeOracle
672 }
673
674 pub fn type_name(as_type: &impl AsType) -> Result<String, askama::Error> {
675 Ok(oracle().find(&as_type.as_type()).type_label())
676 }
677
678 pub fn return_type_name(as_type: Option<&impl AsType>) -> Result<String, askama::Error> {
679 Ok(match as_type {
680 Some(as_type) => oracle().find(&as_type.as_type()).type_label(),
681 None => "()".to_owned(),
682 })
683 }
684
685 pub fn canonical_name(as_type: &impl AsType) -> Result<String, askama::Error> {
686 Ok(oracle().find(&as_type.as_type()).canonical_name())
687 }
688
689 pub fn ffi_converter_name(as_type: &impl AsType) -> Result<String, askama::Error> {
690 Ok(oracle().find(&as_type.as_type()).ffi_converter_name())
691 }
692
693 pub fn ffi_error_converter_name(as_type: &impl AsType) -> Result<String, askama::Error> {
694 // special handling for types used as errors.
695 let mut name = oracle().find(&as_type.as_type()).ffi_converter_name();
696 if matches!(&as_type.as_type(), Type::Object { .. }) {
697 name.push_str("__as_error")
698 }
699 Ok(name)
700 }
701
702 // To better support external types, we always call the "public" lift and lower functions for
703 // "named" types, regardless of whether they are being called from a type in the same crate
704 // (ie, a "local" type) or from a different crate (ie, an "external" type)
705 pub fn lower_fn(as_type: &impl AsType) -> Result<String, askama::Error> {
706 let ty = &as_type.as_type();
707 let ffi_converter_name = oracle().find(ty).ffi_converter_name();
708 Ok(match ty.name() {
709 Some(_) => format!("{}_lower", ffi_converter_name),
710 None => format!("{}.lower", ffi_converter_name),
711 })
712 }
713
714 pub fn write_fn(as_type: &impl AsType) -> Result<String, askama::Error> {
715 let ty = &as_type.as_type();
716 let ffi_converter_name = oracle().find(ty).ffi_converter_name();
717 Ok(format!("{}.write", ffi_converter_name))
718 }
719
720 // See above re lower_fn - we always use the public version for named types.
721 pub fn lift_fn(as_type: &impl AsType) -> Result<String, askama::Error> {
722 let ty = &as_type.as_type();
723 let ffi_converter_name = oracle().find(ty).ffi_converter_name();
724 Ok(match ty.name() {
725 Some(_) => format!("{}_lift", ffi_converter_name),
726 None => format!("{}.lift", ffi_converter_name),
727 })
728 }
729
730 pub fn read_fn(as_type: &impl AsType) -> Result<String, askama::Error> {
731 let ty = &as_type.as_type();
732 let ffi_converter_name = oracle().find(ty).ffi_converter_name();
733 Ok(format!("{}.read", ffi_converter_name))
734 }
735
736 pub fn literal_swift(
737 literal: &Literal,
738 as_type: &impl AsType,
739 ) -> Result<String, askama::Error> {
740 oracle()
741 .find(&as_type.as_type())
742 .literal(literal)
743 .map_err(|e| to_askama_error(&e))
744 }
745
746 // Get the idiomatic Swift rendering of an individual enum variant's discriminant
747 pub fn variant_discr_literal(e: &Enum, index: &usize) -> Result<String, askama::Error> {
748 let literal = e.variant_discr(*index).expect("invalid index");
749 match literal {
750 LiteralMetadata::UInt(v, _, _) => Ok(v.to_string()),
751 LiteralMetadata::Int(v, _, _) => Ok(v.to_string()),
752 _ => unreachable!("expected an UInt!"),
753 }
754 }
755
756 /// Get the Swift type for an FFIType
757 pub fn ffi_type_name(ffi_type: &FfiType) -> Result<String, askama::Error> {
758 Ok(oracle().ffi_type_label(ffi_type))
759 }
760
761 pub fn ffi_default_value(return_type: Option<FfiType>) -> Result<String, askama::Error> {
762 Ok(oracle().ffi_default_value(return_type.as_ref()))
763 }
764
765 /// Like `ffi_type_name`, but used in `BridgingHeaderTemplate.h` which uses a slightly different
766 /// names.
767 pub fn header_ffi_type_name(ffi_type: &FfiType) -> Result<String, askama::Error> {
768 Ok(match ffi_type {
769 FfiType::Int8 => "int8_t".into(),
770 FfiType::UInt8 => "uint8_t".into(),
771 FfiType::Int16 => "int16_t".into(),
772 FfiType::UInt16 => "uint16_t".into(),
773 FfiType::Int32 => "int32_t".into(),
774 FfiType::UInt32 => "uint32_t".into(),
775 FfiType::Int64 => "int64_t".into(),
776 FfiType::UInt64 => "uint64_t".into(),
777 FfiType::Float32 => "float".into(),
778 FfiType::Float64 => "double".into(),
779 FfiType::Handle => "uint64_t".into(),
780 FfiType::RustArcPtr(_) => "void*_Nonnull".into(),
781 FfiType::RustBuffer(_) => "RustBuffer".into(),
782 FfiType::RustCallStatus => "RustCallStatus".into(),
783 FfiType::ForeignBytes => "ForeignBytes".into(),
784 FfiType::Callback(name) => {
785 format!("{} _Nonnull", SwiftCodeOracle.ffi_callback_name(name))
786 }
787 FfiType::Struct(name) => SwiftCodeOracle.ffi_struct_name(name),
788 FfiType::Reference(inner) => {
789 format!("const {}* _Nonnull", header_ffi_type_name(inner)?)
790 }
791 FfiType::MutReference(inner) => format!("{}* _Nonnull", header_ffi_type_name(inner)?),
792 FfiType::VoidPointer => "void* _Nonnull".into(),
793 })
794 }
795
796 /// Get the idiomatic Swift rendering of a class name (for enums, records, errors, etc).
797 pub fn class_name(nm: &str) -> Result<String, askama::Error> {
798 Ok(oracle().class_name(nm))
799 }
800
801 /// Get the idiomatic Swift rendering of a function name.
802 pub fn fn_name(nm: &str) -> Result<String, askama::Error> {
803 Ok(quote_general_keyword(oracle().fn_name(nm)))
804 }
805
806 /// Get the idiomatic Swift rendering of a variable name.
807 pub fn var_name(nm: &str) -> Result<String, askama::Error> {
808 Ok(quote_general_keyword(oracle().var_name(nm)))
809 }
810
811 /// Get the idiomatic Swift rendering of an arguments name.
812 /// This is the same as the var name but quoting is not required.
813 pub fn arg_name(nm: &str) -> Result<String, askama::Error> {
814 Ok(quote_arg_keyword(oracle().var_name(nm)))
815 }
816
817 /// Get the idiomatic Swift rendering of an individual enum variant, quoted if it is a keyword (for use in e.g. declarations)
818 pub fn enum_variant_swift_quoted(nm: &str) -> Result<String, askama::Error> {
819 Ok(quote_general_keyword(oracle().enum_variant_name(nm)))
820 }
821
822 /// Like enum_variant_swift_quoted, but a class name.
823 pub fn error_variant_swift_quoted(nm: &str) -> Result<String, askama::Error> {
824 Ok(quote_general_keyword(oracle().class_name(nm)))
825 }
826
827 /// Get the idiomatic Swift rendering of an FFI callback function name
828 pub fn ffi_callback_name(nm: &str) -> Result<String, askama::Error> {
829 Ok(oracle().ffi_callback_name(nm))
830 }
831
832 /// Get the idiomatic Swift rendering of an FFI struct name
833 pub fn ffi_struct_name(nm: &str) -> Result<String, askama::Error> {
834 Ok(oracle().ffi_struct_name(nm))
835 }
836
837 /// Get the idiomatic Swift rendering of an if guard name
838 pub fn if_guard_name(nm: &str) -> Result<String, askama::Error> {
839 Ok(oracle().if_guard_name(nm))
840 }
841
842 /// Get the idiomatic Swift rendering of docstring
843 pub fn docstring(docstring: &str, spaces: &i32) -> Result<String, askama::Error> {
844 let middle = textwrap::indent(&textwrap::dedent(docstring), " * ");
845 let wrapped = format!("/**\n{middle}\n */");
846
847 let spaces = usize::try_from(*spaces).unwrap_or_default();
848 Ok(textwrap::indent(&wrapped, &" ".repeat(spaces)))
849 }
850
851 pub fn object_names(obj: &Object) -> Result<(String, String), askama::Error> {
852 Ok(SwiftCodeOracle.object_names(obj))
853 }
854 }