Debian Codegraph @

third_party/rust/uniffi_bindgen/src/bindings/ruby/gen_ruby/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 anyhow::Result;
6 use askama::Template;
7
8 use heck::{ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase};
9 use serde::{Deserialize, Serialize};
10 use std::borrow::Borrow;
11
12 use crate::interface::*;
13
14 const RESERVED_WORDS: &[&str] = &[
15 "alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else",
16 "elsif", "END", "end", "ensure", "false", "for", "if", "module", "next", "nil", "not", "or",
17 "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless",
18 "until", "when", "while", "yield", "__FILE__", "__LINE__",
19 ];
20
21 fn is_reserved_word(word: &str) -> bool {
22 RESERVED_WORDS.contains(&word)
23 }
24
25 /// Get the canonical, unique-within-this-component name for a type.
26 ///
27 /// When generating helper code for foreign language bindings, it's sometimes useful to be
28 /// able to name a particular type in order to e.g. call a helper function that is specific
29 /// to that type. We support this by defining a naming convention where each type gets a
30 /// unique canonical name, constructed recursively from the names of its component types (if any).
31 pub fn canonical_name(t: &Type) -> String {
32 match t {
33 // Builtin primitive types, with plain old names.
34 Type::Int8 => "i8".into(),
35 Type::UInt8 => "u8".into(),
36 Type::Int16 => "i16".into(),
37 Type::UInt16 => "u16".into(),
38 Type::Int32 => "i32".into(),
39 Type::UInt32 => "u32".into(),
40 Type::Int64 => "i64".into(),
41 Type::UInt64 => "u64".into(),
42 Type::Float32 => "f32".into(),
43 Type::Float64 => "f64".into(),
44 Type::String => "string".into(),
45 Type::Bytes => "bytes".into(),
46 Type::Boolean => "bool".into(),
47 // API defined types.
48 // Note that these all get unique names, and the parser ensures that the names do not
49 // conflict with a builtin type. We add a prefix to the name to guard against pathological
50 // cases like a record named `SequenceRecord` interfering with `sequence<Record>`.
51 // However, types that support importing all end up with the same prefix of "Type", so
52 // that the import handling code knows how to find the remote reference.
53 Type::Object { name, .. } => format!("Type{name}"),
54 Type::Enum { name, .. } => format!("Type{name}"),
55 Type::Record { name, .. } => format!("Type{name}"),
56 Type::CallbackInterface { name, .. } => format!("CallbackInterface{name}"),
57 Type::Timestamp => "Timestamp".into(),
58 Type::Duration => "Duration".into(),
59 // Recursive types.
60 // These add a prefix to the name of the underlying type.
61 // The component API definition cannot give names to recursive types, so as long as the
62 // prefixes we add here are all unique amongst themselves, then we have no chance of
63 // acccidentally generating name collisions.
64 Type::Optional { inner_type } => format!("Optional{}", canonical_name(inner_type)),
65 Type::Sequence { inner_type } => format!("Sequence{}", canonical_name(inner_type)),
66 Type::Map {
67 key_type,
68 value_type,
69 } => format!(
70 "Map{}{}",
71 canonical_name(key_type).to_upper_camel_case(),
72 canonical_name(value_type).to_upper_camel_case()
73 ),
74 Type::Custom { name, .. } => format!("Type{name}"),
75 }
76 }
77
78 // Some config options for it the caller wants to customize the generated ruby.
79 // Note that this can only be used to control details of the ruby *that do not affect the underlying component*,
80 // since the details of the underlying component are entirely determined by the `ComponentInterface`.
81 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
82 pub struct Config {
83 pub(super) cdylib_name: Option<String>,
84 cdylib_path: Option<String>,
85 }
86
87 impl Config {
88 pub fn cdylib_name(&self) -> String {
89 self.cdylib_name
90 .clone()
91 .unwrap_or_else(|| "uniffi".to_string())
92 }
93
94 pub fn custom_cdylib_path(&self) -> bool {
95 self.cdylib_path.is_some()
96 }
97
98 pub fn cdylib_path(&self) -> String {
99 self.cdylib_path.clone().unwrap_or_default()
100 }
101 }
102
103 #[derive(Template)]
104 #[template(syntax = "rb", escape = "none", path = "wrapper.rb")]
105 pub struct RubyWrapper<'a> {
106 config: Config,
107 ci: &'a ComponentInterface,
108 }
109 impl<'a> RubyWrapper<'a> {
110 pub fn new(config: Config, ci: &'a ComponentInterface) -> Self {
111 Self { config, ci }
112 }
113 }
114
115 mod filters {
116 use super::*;
117
118 pub fn type_ffi(type_: &FfiType) -> Result<String, askama::Error> {
119 Ok(match type_ {
120 FfiType::Int8 => ":int8".to_string(),
121 FfiType::UInt8 => ":uint8".to_string(),
122 FfiType::Int16 => ":int16".to_string(),
123 FfiType::UInt16 => ":uint16".to_string(),
124 FfiType::Int32 => ":int32".to_string(),
125 FfiType::UInt32 => ":uint32".to_string(),
126 FfiType::Int64 => ":int64".to_string(),
127 FfiType::UInt64 => ":uint64".to_string(),
128 FfiType::Float32 => ":float".to_string(),
129 FfiType::Float64 => ":double".to_string(),
130 FfiType::Handle => ":uint64".to_string(),
131 FfiType::RustArcPtr(_) => ":pointer".to_string(),
132 FfiType::RustBuffer(_) => "RustBuffer.by_value".to_string(),
133 FfiType::RustCallStatus => "RustCallStatus".to_string(),
134 FfiType::ForeignBytes => "ForeignBytes".to_string(),
135 FfiType::Callback(_) => unimplemented!("FFI Callbacks not implemented"),
136 // Note: this can't just be `unimplemented!()` because some of the FFI function
137 // definitions use references. Those FFI functions aren't actually used, so we just
138 // pick something that runs and makes some sense. Revisit this once the references
139 // are actually implemented.
140 FfiType::Reference(_) | FfiType::MutReference(_) => ":pointer".to_string(),
141 FfiType::VoidPointer => ":pointer".to_string(),
142 FfiType::Struct(_) => {
143 unimplemented!("Structs are not implemented")
144 }
145 })
146 }
147
148 pub fn literal_rb(literal: &Literal) -> Result<String, askama::Error> {
149 Ok(match literal {
150 Literal::Boolean(v) => {
151 if *v {
152 "true".into()
153 } else {
154 "false".into()
155 }
156 }
157 // use the double-quote form to match with the other languages, and quote escapes.
158 Literal::String(s) => format!("\"{s}\""),
159 Literal::None => "nil".into(),
160 Literal::Some { inner } => literal_rb(inner)?,
161 Literal::EmptySequence => "[]".into(),
162 Literal::EmptyMap => "{}".into(),
163 Literal::Enum(v, type_) => match type_ {
164 Type::Enum { name, .. } => {
165 format!("{}::{}", class_name_rb(name)?, enum_name_rb(v)?)
166 }
167 _ => panic!("Unexpected type in enum literal: {type_:?}"),
168 },
169 // https://docs.ruby-lang.org/en/2.0.0/syntax/literals_rdoc.html
170 Literal::Int(i, radix, _) => match radix {
171 Radix::Octal => format!("0o{i:o}"),
172 Radix::Decimal => format!("{i}"),
173 Radix::Hexadecimal => format!("{i:#x}"),
174 },
175 Literal::UInt(i, radix, _) => match radix {
176 Radix::Octal => format!("0o{i:o}"),
177 Radix::Decimal => format!("{i}"),
178 Radix::Hexadecimal => format!("{i:#x}"),
179 },
180 Literal::Float(string, _type_) => string.clone(),
181 })
182 }
183
184 pub fn class_name_rb(nm: &str) -> Result<String, askama::Error> {
185 Ok(nm.to_string().to_upper_camel_case())
186 }
187
188 pub fn fn_name_rb(nm: &str) -> Result<String, askama::Error> {
189 Ok(nm.to_string().to_snake_case())
190 }
191
192 pub fn var_name_rb(nm: &str) -> Result<String, askama::Error> {
193 let nm = nm.to_string();
194 let prefix = if is_reserved_word(&nm) { "_" } else { "" };
195
196 Ok(format!("{prefix}{}", nm.to_snake_case()))
197 }
198
199 pub fn enum_name_rb(nm: &str) -> Result<String, askama::Error> {
200 Ok(nm.to_string().to_shouty_snake_case())
201 }
202
203 pub fn coerce_rb<S1: AsRef<str>, S2: AsRef<str>>(
204 nm: S1,
205 ns: S2,
206 type_: &Type,
207 ) -> Result<String, askama::Error> {
208 let nm = nm.as_ref();
209 let ns = ns.as_ref();
210 Ok(match type_ {
211 Type::Int8 => format!("{ns}::uniffi_in_range({nm}, \"i8\", -2**7, 2**7)"),
212 Type::Int16 => format!("{ns}::uniffi_in_range({nm}, \"i16\", -2**15, 2**15)"),
213 Type::Int32 => format!("{ns}::uniffi_in_range({nm}, \"i32\", -2**31, 2**31)"),
214 Type::Int64 => format!("{ns}::uniffi_in_range({nm}, \"i64\", -2**63, 2**63)"),
215 Type::UInt8 => format!("{ns}::uniffi_in_range({nm}, \"u8\", 0, 2**8)"),
216 Type::UInt16 => format!("{ns}::uniffi_in_range({nm}, \"u16\", 0, 2**16)"),
217 Type::UInt32 => format!("{ns}::uniffi_in_range({nm}, \"u32\", 0, 2**32)"),
218 Type::UInt64 => format!("{ns}::uniffi_in_range({nm}, \"u64\", 0, 2**64)"),
219 Type::Float32 | Type::Float64 => nm.to_string(),
220 Type::Boolean => format!("{nm} ? true : false"),
221 Type::Object { .. } | Type::Enum { .. } | Type::Record { .. } => nm.to_string(),
222 Type::String => format!("{ns}::uniffi_utf8({nm})"),
223 Type::Bytes => format!("{ns}::uniffi_bytes({nm})"),
224 Type::Timestamp | Type::Duration => nm.to_string(),
225 Type::CallbackInterface { .. } => {
226 panic!("No support for coercing callback interfaces yet")
227 }
228 Type::Optional { inner_type: t } => format!("({nm} ? {} : nil)", coerce_rb(nm, ns, t)?),
229 Type::Sequence { inner_type: t } => {
230 let coerce_code = coerce_rb("v", ns, t)?;
231 if coerce_code == "v" {
232 nm.to_string()
233 } else {
234 format!("{nm}.map {{ |v| {coerce_code} }}")
235 }
236 }
237 Type::Map { value_type: t, .. } => {
238 let k_coerce_code = coerce_rb("k", ns, &Type::String)?;
239 let v_coerce_code = coerce_rb("v", ns, t)?;
240
241 if k_coerce_code == "k" && v_coerce_code == "v" {
242 nm.to_string()
243 } else {
244 format!(
245 "{nm}.each.with_object({{}}) {{ |(k, v), res| res[{k_coerce_code}] = {v_coerce_code} }}"
246 )
247 }
248 }
249 Type::Custom { .. } => panic!("No support for custom types, yet"),
250 })
251 }
252
253 pub fn check_lower_rb<S: AsRef<str>>(nm: S, type_: &Type) -> Result<String, askama::Error> {
254 let nm = nm.as_ref();
255 Ok(match type_ {
256 Type::Object { name, .. } => {
257 format!("({}.uniffi_check_lower {nm})", class_name_rb(name)?)
258 }
259 Type::Enum { .. }
260 | Type::Record { .. }
261 | Type::Optional { .. }
262 | Type::Sequence { .. }
263 | Type::Map { .. } => format!(
264 "RustBuffer.check_lower_{}({})",
265 class_name_rb(&canonical_name(type_))?,
266 nm
267 ),
268 _ => "".to_owned(),
269 })
270 }
271
272 pub fn lower_rb(nm: &str, type_: &Type) -> Result<String, askama::Error> {
273 Ok(match type_ {
274 Type::Int8
275 | Type::UInt8
276 | Type::Int16
277 | Type::UInt16
278 | Type::Int32
279 | Type::UInt32
280 | Type::Int64
281 | Type::UInt64
282 | Type::Float32
283 | Type::Float64 => nm.to_string(),
284 Type::Boolean => format!("({nm} ? 1 : 0)"),
285 Type::String => format!("RustBuffer.allocFromString({nm})"),
286 Type::Bytes => format!("RustBuffer.allocFromBytes({nm})"),
287 Type::Object { name, .. } => format!("({}.uniffi_lower {nm})", class_name_rb(name)?),
288 Type::CallbackInterface { .. } => {
289 panic!("No support for lowering callback interfaces yet")
290 }
291 Type::Enum { .. }
292 | Type::Record { .. }
293 | Type::Optional { .. }
294 | Type::Sequence { .. }
295 | Type::Timestamp
296 | Type::Duration
297 | Type::Map { .. } => format!(
298 "RustBuffer.alloc_from_{}({})",
299 class_name_rb(&canonical_name(type_))?,
300 nm
301 ),
302 Type::Custom { .. } => panic!("No support for lowering custom types, yet"),
303 })
304 }
305
306 pub fn lift_rb(nm: &str, type_: &Type) -> Result<String, askama::Error> {
307 Ok(match type_ {
308 Type::Int8
309 | Type::UInt8
310 | Type::Int16
311 | Type::UInt16
312 | Type::Int32
313 | Type::UInt32
314 | Type::Int64
315 | Type::UInt64 => format!("{nm}.to_i"),
316 Type::Float32 | Type::Float64 => format!("{nm}.to_f"),
317 Type::Boolean => format!("1 == {nm}"),
318 Type::String => format!("{nm}.consumeIntoString"),
319 Type::Bytes => format!("{nm}.consumeIntoBytes"),
320 Type::Object { name, .. } => format!("{}.uniffi_allocate({nm})", class_name_rb(name)?),
321 Type::CallbackInterface { .. } => {
322 panic!("No support for lifting callback interfaces, yet")
323 }
324 Type::Enum { .. } => {
325 format!(
326 "{}.consumeInto{}",
327 nm,
328 class_name_rb(&canonical_name(type_))?
329 )
330 }
331 Type::Record { .. }
332 | Type::Optional { .. }
333 | Type::Sequence { .. }
334 | Type::Timestamp
335 | Type::Duration
336 | Type::Map { .. } => format!(
337 "{}.consumeInto{}",
338 nm,
339 class_name_rb(&canonical_name(type_))?
340 ),
341 Type::Custom { .. } => panic!("No support for lifting custom types, yet"),
342 })
343 }
344 }
345
346 #[cfg(test)]
347 mod test_type {
348 use super::*;
349
350 #[test]
351 fn test_canonical_names() {
352 // Non-exhaustive, but gives a bit of a flavour of what we want.
353 assert_eq!(canonical_name(&Type::UInt8), "u8");
354 assert_eq!(canonical_name(&Type::String), "string");
355 assert_eq!(canonical_name(&Type::Bytes), "bytes");
356 assert_eq!(
357 canonical_name(&Type::Optional {
358 inner_type: Box::new(Type::Sequence {
359 inner_type: Box::new(Type::Object {
360 module_path: "anything".to_string(),
361 name: "Example".into(),
362 imp: ObjectImpl::Struct,
363 })
364 })
365 }),
366 "OptionalSequenceTypeExample"
367 );
368 }
369 }
370
371 #[cfg(test)]
372 mod tests;