-
Notifications
You must be signed in to change notification settings - Fork 233
/
gen_kotlin.rs
282 lines (259 loc) · 10.9 KB
/
gen_kotlin.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use anyhow::Result;
use askama::Template;
use heck::{CamelCase, MixedCase, ShoutySnakeCase};
use serde::{Deserialize, Serialize};
use crate::interface::*;
use crate::MergeWith;
// Some config options for it the caller wants to customize the generated Kotlin.
// Note that this can only be used to control details of the Kotlin *that do not affect the underlying component*,
// sine the details of the underlying component are entirely determined by the `ComponentInterface`.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Config {
package_name: Option<String>,
cdylib_name: Option<String>,
}
impl Config {
pub fn package_name(&self) -> String {
if let Some(package_name) = &self.package_name {
package_name.clone()
} else {
"uniffi".into()
}
}
pub fn cdylib_name(&self) -> String {
if let Some(cdylib_name) = &self.cdylib_name {
cdylib_name.clone()
} else {
"uniffi".into()
}
}
}
impl From<&ComponentInterface> for Config {
fn from(ci: &ComponentInterface) -> Self {
Config {
package_name: Some(format!("uniffi.{}", ci.namespace())),
cdylib_name: Some(format!("uniffi_{}", ci.namespace())),
}
}
}
impl MergeWith for Config {
fn merge_with(&self, other: &Self) -> Self {
Config {
package_name: self.package_name.merge_with(&other.package_name),
cdylib_name: self.cdylib_name.merge_with(&other.cdylib_name),
}
}
}
#[derive(Template)]
#[template(syntax = "kt", escape = "none", path = "wrapper.kt")]
pub struct KotlinWrapper<'a> {
config: Config,
ci: &'a ComponentInterface,
}
impl<'a> KotlinWrapper<'a> {
pub fn new(config: Config, ci: &'a ComponentInterface) -> Self {
Self { config, ci }
}
}
mod filters {
use super::*;
use std::fmt;
/// Get the Kotlin syntax for representing a given api-level `Type`.
pub fn type_kt(type_: &Type) -> Result<String, askama::Error> {
Ok(match type_ {
// These native Kotlin types map nicely to the FFI without conversion.
Type::UInt8 => "UByte".to_string(),
Type::UInt16 => "UShort".to_string(),
Type::UInt32 => "UInt".to_string(),
Type::UInt64 => "ULong".to_string(),
Type::Int8 => "Byte".to_string(),
Type::Int16 => "Short".to_string(),
Type::Int32 => "Int".to_string(),
Type::Int64 => "Long".to_string(),
Type::Float32 => "Float".to_string(),
Type::Float64 => "Double".to_string(),
// These types need conversion, and special handling for lifting/lowering.
Type::Boolean => "Boolean".to_string(),
Type::String => "String".to_string(),
Type::Timestamp => "java.time.Instant".to_string(),
Type::Duration => "java.time.Duration".to_string(),
Type::Enum(name)
| Type::Record(name)
| Type::Object(name)
| Type::Error(name)
| Type::CallbackInterface(name) => class_name_kt(name)?,
Type::Optional(t) => format!("{}?", type_kt(t)?),
Type::Sequence(t) => format!("List<{}>", type_kt(t)?),
Type::Map(t) => format!("Map<String, {}>", type_kt(t)?),
})
}
/// Get the Kotlin syntax for representing a given low-level `FFIType`.
pub fn type_ffi(type_: &FFIType) -> Result<String, askama::Error> {
Ok(match type_ {
// Note that unsigned integers in Kotlin are currently experimental, but java.nio.ByteBuffer does not
// support them yet. Thus, we use the signed variants to represent both signed and unsigned
// types from the component API.
FFIType::Int8 | FFIType::UInt8 => "Byte".to_string(),
FFIType::Int16 | FFIType::UInt16 => "Short".to_string(),
FFIType::Int32 | FFIType::UInt32 => "Int".to_string(),
FFIType::Int64 | FFIType::UInt64 => "Long".to_string(),
FFIType::Float32 => "Float".to_string(),
FFIType::Float64 => "Double".to_string(),
FFIType::RustCString => "Pointer".to_string(),
FFIType::RustBuffer => "RustBuffer.ByValue".to_string(),
FFIType::RustError => "RustError".to_string(),
FFIType::ForeignBytes => "ForeignBytes.ByValue".to_string(),
FFIType::ForeignCallback => "ForeignCallback".to_string(),
})
}
pub fn literal_kt(literal: &Literal) -> Result<String, askama::Error> {
fn typed_number(type_: &Type, num_str: String) -> Result<String, askama::Error> {
Ok(match type_ {
// Bytes, Shorts and Ints can all be inferred from the type.
Type::Int8 | Type::Int16 | Type::Int32 => num_str,
Type::Int64 => format!("{}L", num_str),
Type::UInt8 | Type::UInt16 | Type::UInt32 => format!("{}u", num_str),
Type::UInt64 => format!("{}uL", num_str),
Type::Float32 => format!("{}f", num_str),
Type::Float64 => num_str,
_ => panic!("Unexpected literal: {} is not a number", num_str),
})
}
Ok(match literal {
Literal::Boolean(v) => format!("{}", v),
Literal::String(s) => format!("\"{}\"", s),
Literal::Null => "null".into(),
Literal::EmptySequence => "listOf()".into(),
Literal::EmptyMap => "mapOf".into(),
Literal::Enum(v, type_) => format!("{}.{}", type_kt(type_)?, enum_variant_kt(v)?),
Literal::Int(i, radix, type_) => typed_number(
type_,
match radix {
Radix::Octal => format!("{:#x}", i),
Radix::Decimal => format!("{}", i),
Radix::Hexadecimal => format!("{:#x}", i),
},
)?,
Literal::UInt(i, radix, type_) => typed_number(
type_,
match radix {
Radix::Octal => format!("{:#x}", i),
Radix::Decimal => format!("{}", i),
Radix::Hexadecimal => format!("{:#x}", i),
},
)?,
Literal::Float(string, type_) => typed_number(type_, string.clone())?,
})
}
/// Get the idiomatic Kotlin rendering of a class name (for enums, records, errors, etc).
pub fn class_name_kt(nm: &dyn fmt::Display) -> Result<String, askama::Error> {
Ok(nm.to_string().to_camel_case())
}
/// Get the idiomatic Kotlin rendering of a function name.
pub fn fn_name_kt(nm: &dyn fmt::Display) -> Result<String, askama::Error> {
Ok(nm.to_string().to_mixed_case())
}
/// Get the idiomatic Kotlin rendering of a variable name.
pub fn var_name_kt(nm: &dyn fmt::Display) -> Result<String, askama::Error> {
Ok(nm.to_string().to_mixed_case())
}
/// Get the idiomatic Kotlin rendering of an individual enum variant.
pub fn enum_variant_kt(nm: &dyn fmt::Display) -> Result<String, askama::Error> {
Ok(nm.to_string().to_shouty_snake_case())
}
/// Get a Kotlin expression for lowering a value into something we can pass over the FFI.
///
/// Where possible, this delegates to a `lower()` method on the type itself, but special
/// handling is required for some compound data types.
pub fn lower_kt(nm: &dyn fmt::Display, type_: &Type) -> Result<String, askama::Error> {
let nm = var_name_kt(nm)?;
Ok(match type_ {
Type::CallbackInterface(_) => format!(
"{}Internals.lower({})",
class_name_kt(&type_.canonical_name())?,
nm,
),
Type::Optional(_)
| Type::Sequence(_)
| Type::Map(_)
| Type::Timestamp
| Type::Duration => {
format!("lower{}({})", class_name_kt(&type_.canonical_name())?, nm,)
}
_ => format!("{}.lower()", nm),
})
}
/// Get a Kotlin expression for writing a value into a byte buffer.
///
/// Where possible, this delegates to a `write()` method on the type itself, but special
/// handling is required for some compound data types.
pub fn write_kt(
nm: &dyn fmt::Display,
target: &dyn fmt::Display,
type_: &Type,
) -> Result<String, askama::Error> {
let nm = var_name_kt(nm)?;
Ok(match type_ {
Type::CallbackInterface(_) => format!(
"{}Internals.write({}, {})",
class_name_kt(&type_.canonical_name())?,
nm,
target,
),
Type::Optional(_)
| Type::Sequence(_)
| Type::Map(_)
| Type::Timestamp
| Type::Duration => format!(
"write{}({}, {})",
class_name_kt(&type_.canonical_name())?,
nm,
target,
),
_ => format!("{}.write({})", nm, target),
})
}
/// Get a Kotlin expression for lifting a value from something we received over the FFI.
///
/// Where possible, this delegates to a `lift()` method on the type itself, but special
/// handling is required for some compound data types.
pub fn lift_kt(nm: &dyn fmt::Display, type_: &Type) -> Result<String, askama::Error> {
let nm = nm.to_string();
Ok(match type_ {
Type::CallbackInterface(_) => format!(
"{}Internals.lift({})",
class_name_kt(&type_.canonical_name())?,
nm,
),
Type::Optional(_)
| Type::Sequence(_)
| Type::Map(_)
| Type::Timestamp
| Type::Duration => format!("lift{}({})", class_name_kt(&type_.canonical_name())?, nm),
_ => format!("{}.lift({})", type_kt(type_)?, nm),
})
}
/// Get a Kotlin expression for reading a value from a byte buffer.
///
/// Where possible, this delegates to a `read()` method on the type itself, but special
/// handling is required for some compound data types.
pub fn read_kt(nm: &dyn fmt::Display, type_: &Type) -> Result<String, askama::Error> {
let nm = nm.to_string();
Ok(match type_ {
Type::CallbackInterface(_) => format!(
"{}Internals.read({})",
class_name_kt(&type_.canonical_name())?,
nm,
),
Type::Optional(_)
| Type::Sequence(_)
| Type::Map(_)
| Type::Timestamp
| Type::Duration => format!("read{}({})", class_name_kt(&type_.canonical_name())?, nm),
_ => format!("{}.read({})", type_kt(type_)?, nm),
})
}
}