Debian Codegraph @

third_party/rust/uniffi_bindgen/src/bindings/swift/gen_swift/primitives.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 super::CodeType;
6 use crate::backend::Literal;
7 use crate::{
8 bail,
9 interface::{Radix, Type},
10 Result,
11 };
12
13 fn render_literal(literal: &Literal) -> Result<String> {
14 fn typed_number(type_: &Type, num_str: String) -> Result<String> {
15 let unwrapped_type = match type_ {
16 Type::Optional { inner_type } => inner_type,
17 t => t,
18 };
19 Ok(match unwrapped_type {
20 // special case Int32.
21 Type::Int32 => num_str,
22 // otherwise use constructor e.g. UInt8(x)
23 Type::Int8
24 | Type::UInt8
25 | Type::Int16
26 | Type::UInt16
27 | Type::UInt32
28 | Type::Int64
29 | Type::UInt64
30 | Type::Float32
31 | Type::Float64 =>
32 // XXX we should pass in the codetype itself.
33 {
34 format!(
35 "{}({num_str})",
36 super::SwiftCodeOracle.find(type_).type_label()
37 )
38 }
39 _ => bail!("Unexpected literal: {num_str} for type: {type_:?}"),
40 })
41 }
42
43 Ok(match literal {
44 Literal::Boolean(v) => format!("{v}"),
45 Literal::String(s) => format!("\"{s}\""),
46 Literal::Int(i, radix, type_) => typed_number(
47 type_,
48 match radix {
49 Radix::Octal => format!("0o{i:o}"),
50 Radix::Decimal => format!("{i}"),
51 Radix::Hexadecimal => format!("{i:#x}"),
52 },
53 )?,
54 Literal::UInt(i, radix, type_) => typed_number(
55 type_,
56 match radix {
57 Radix::Octal => format!("0o{i:o}"),
58 Radix::Decimal => format!("{i}"),
59 Radix::Hexadecimal => format!("{i:#x}"),
60 },
61 )?,
62 Literal::Float(string, type_) => typed_number(type_, string.clone())?,
63 _ => bail!("Invalid literal: {literal:?}"),
64 })
65 }
66
67 macro_rules! impl_code_type_for_primitive {
68 ($T:ident, $class_name:literal) => {
69 #[derive(Debug)]
70 pub struct $T;
71
72 impl CodeType for $T {
73 fn type_label(&self) -> String {
74 $class_name.into()
75 }
76
77 fn literal(&self, literal: &Literal) -> Result<String> {
78 render_literal(&literal)
79 }
80 }
81 };
82 }
83
84 impl_code_type_for_primitive!(BooleanCodeType, "Bool");
85 impl_code_type_for_primitive!(StringCodeType, "String");
86 impl_code_type_for_primitive!(BytesCodeType, "Data");
87 impl_code_type_for_primitive!(Int8CodeType, "Int8");
88 impl_code_type_for_primitive!(Int16CodeType, "Int16");
89 impl_code_type_for_primitive!(Int32CodeType, "Int32");
90 impl_code_type_for_primitive!(Int64CodeType, "Int64");
91 impl_code_type_for_primitive!(UInt8CodeType, "UInt8");
92 impl_code_type_for_primitive!(UInt16CodeType, "UInt16");
93 impl_code_type_for_primitive!(UInt32CodeType, "UInt32");
94 impl_code_type_for_primitive!(UInt64CodeType, "UInt64");
95 impl_code_type_for_primitive!(Float32CodeType, "Float");
96 impl_code_type_for_primitive!(Float64CodeType, "Double");