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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#![warn(rust_2018_idioms, unused_qualifications)]
#![allow(unknown_lints)]
const BINDGEN_VERSION: &str = env!("CARGO_PKG_VERSION");
use anyhow::{anyhow, bail, Context, Result};
use camino::{Utf8Path, Utf8PathBuf};
use fs_err::{self as fs, File};
use serde::{Deserialize, Serialize};
use std::io::prelude::*;
use std::io::ErrorKind;
use std::{collections::HashMap, env, process::Command, str::FromStr};
pub mod backend;
pub mod bindings;
pub mod interface;
pub mod macro_metadata;
pub mod scaffolding;
pub use interface::ComponentInterface;
use scaffolding::RustScaffolding;
pub trait BindingGeneratorConfig: for<'de> Deserialize<'de> {
fn get_entry_from_bindings_table(bindings: &toml::Value) -> Option<toml::Value>;
fn get_config_defaults(ci: &ComponentInterface) -> Vec<(String, toml::Value)>;
}
fn load_bindings_config<BC: BindingGeneratorConfig>(
ci: &ComponentInterface,
crate_root: &Utf8Path,
config_file_override: Option<&Utf8Path>,
) -> Result<BC> {
let mut config_map: toml::value::Table =
match load_bindings_config_toml::<BC>(crate_root, config_file_override)? {
Some(value) => value
.try_into()
.context("Bindings config must be a TOML table")?,
None => toml::map::Map::new(),
};
for (key, value) in BC::get_config_defaults(ci) {
config_map.entry(key).or_insert(value);
}
toml::Value::from(config_map)
.try_into()
.context("Generating bindings config from toml::Value")
}
#[derive(Clone, Debug, Hash, PartialEq, PartialOrd, Ord, Eq)]
pub struct EmptyBindingGeneratorConfig;
impl BindingGeneratorConfig for EmptyBindingGeneratorConfig {
fn get_entry_from_bindings_table(_bindings: &toml::Value) -> Option<toml::Value> {
None
}
fn get_config_defaults(_ci: &ComponentInterface) -> Vec<(String, toml::Value)> {
Vec::new()
}
}
impl<'de> Deserialize<'de> for EmptyBindingGeneratorConfig {
fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
Ok(EmptyBindingGeneratorConfig)
}
}
fn load_bindings_config_toml<BC: BindingGeneratorConfig>(
crate_root: &Utf8Path,
config_file_override: Option<&Utf8Path>,
) -> Result<Option<toml::Value>> {
let config_path = match config_file_override {
Some(cfg) => cfg.to_owned(),
None => crate_root.join("uniffi.toml"),
};
if !config_path.exists() {
return Ok(None);
}
let contents = fs::read_to_string(&config_path)
.with_context(|| format!("Failed to read config file from {config_path}"))?;
let full_config = toml::Value::from_str(&contents)
.with_context(|| format!("Failed to parse config file {config_path}"))?;
Ok(full_config
.get("bindings")
.and_then(BC::get_entry_from_bindings_table))
}
pub trait BindingGenerator: Sized {
type Config: BindingGeneratorConfig;
fn write_bindings(
&self,
ci: ComponentInterface,
config: Self::Config,
out_dir: &Utf8Path,
) -> Result<()>;
}
pub fn generate_external_bindings(
binding_generator: impl BindingGenerator,
udl_file: impl AsRef<Utf8Path>,
config_file_override: Option<impl AsRef<Utf8Path>>,
out_dir_override: Option<impl AsRef<Utf8Path>>,
) -> Result<()> {
let out_dir_override = out_dir_override.as_ref().map(|p| p.as_ref());
let config_file_override = config_file_override.as_ref().map(|p| p.as_ref());
let crate_root = guess_crate_root(udl_file.as_ref())?;
let out_dir = get_out_dir(udl_file.as_ref(), out_dir_override)?;
let component = parse_udl(udl_file.as_ref()).context("Error parsing UDL")?;
let bindings_config = load_bindings_config(&component, crate_root, config_file_override)?;
binding_generator.write_bindings(component, bindings_config, &out_dir)
}
pub fn generate_component_scaffolding(
udl_file: &Utf8Path,
config_file_override: Option<&Utf8Path>,
out_dir_override: Option<&Utf8Path>,
format_code: bool,
) -> Result<()> {
let component = parse_udl(udl_file)?;
let _config = get_config(
&component,
guess_crate_root(udl_file)?,
config_file_override,
);
let file_stem = udl_file.file_stem().context("not a file")?;
let filename = format!("{file_stem}.uniffi.rs");
let out_path = get_out_dir(udl_file, out_dir_override)?.join(filename);
let mut f = File::create(&out_path)?;
write!(f, "{}", RustScaffolding::new(&component)).context("Failed to write output file")?;
if format_code {
format_code_with_rustfmt(&out_path)?;
}
Ok(())
}
pub fn generate_bindings(
udl_file: &Utf8Path,
config_file_override: Option<&Utf8Path>,
target_languages: Vec<&str>,
out_dir_override: Option<&Utf8Path>,
library_file: Option<&Utf8Path>,
try_format_code: bool,
) -> Result<()> {
let mut component = parse_udl(udl_file)?;
if let Some(library_file) = library_file {
macro_metadata::add_to_ci_from_library(&mut component, library_file)?;
}
let crate_root = &guess_crate_root(udl_file)?;
let config = get_config(&component, crate_root, config_file_override)?;
let out_dir = get_out_dir(udl_file, out_dir_override)?;
for language in target_languages {
bindings::write_bindings(
&config.bindings,
&component,
&out_dir,
language.try_into()?,
try_format_code,
)?;
}
Ok(())
}
pub fn dump_json(library_path: &Utf8Path) -> Result<String> {
let metadata = macro_metadata::extract_from_library(library_path)?;
Ok(serde_json::to_string_pretty(&metadata)?)
}
pub fn print_json(library_path: &Utf8Path) -> Result<()> {
println!("{}", dump_json(library_path)?);
Ok(())
}
pub fn guess_crate_root(udl_file: &Utf8Path) -> Result<&Utf8Path> {
let path_guess = udl_file
.parent()
.context("UDL file has no parent folder!")?
.parent()
.context("UDL file has no grand-parent folder!")?;
if !path_guess.join("Cargo.toml").is_file() {
bail!("UDL file does not appear to be inside a crate")
}
Ok(path_guess)
}
fn get_config(
component: &ComponentInterface,
crate_root: &Utf8Path,
config_file_override: Option<&Utf8Path>,
) -> Result<Config> {
let default_config: Config = component.into();
let config_file = match config_file_override {
Some(cfg) => Some(cfg.to_owned()),
None => crate_root.join("uniffi.toml").canonicalize_utf8().ok(),
};
match config_file {
Some(path) => {
let contents = fs::read_to_string(&path)
.with_context(|| format!("Failed to read config file from {path}"))?;
let loaded_config: Config = toml::de::from_str(&contents)
.with_context(|| format!("Failed to generate config from file {path}"))?;
Ok(loaded_config.merge_with(&default_config))
}
None => Ok(default_config),
}
}
fn get_out_dir(udl_file: &Utf8Path, out_dir_override: Option<&Utf8Path>) -> Result<Utf8PathBuf> {
Ok(match out_dir_override {
Some(s) => {
fs::create_dir_all(s)?;
s.canonicalize_utf8().context("Unable to find out-dir")?
}
None => udl_file
.parent()
.context("File has no parent directory")?
.to_owned(),
})
}
fn parse_udl(udl_file: &Utf8Path) -> Result<ComponentInterface> {
let udl = fs::read_to_string(udl_file)
.with_context(|| format!("Failed to read UDL from {udl_file}"))?;
ComponentInterface::from_webidl(&udl).context("Failed to parse UDL")
}
fn format_code_with_rustfmt(path: &Utf8Path) -> Result<()> {
let status = Command::new("rustfmt").arg(path).status().map_err(|e| {
let ctx = match e.kind() {
ErrorKind::NotFound => "formatting was requested, but rustfmt was not found",
_ => "unknown error when calling rustfmt",
};
anyhow!(e).context(ctx)
})?;
if !status.success() {
bail!("rustmt failed when formatting scaffolding. Note: --no-format can be used to skip formatting");
}
Ok(())
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct Config {
#[serde(default)]
bindings: bindings::Config,
}
impl From<&ComponentInterface> for Config {
fn from(ci: &ComponentInterface) -> Self {
Config {
bindings: ci.into(),
}
}
}
pub trait MergeWith {
fn merge_with(&self, other: &Self) -> Self;
}
impl MergeWith for Config {
fn merge_with(&self, other: &Self) -> Self {
Config {
bindings: self.bindings.merge_with(&other.bindings),
}
}
}
impl<T: Clone> MergeWith for Option<T> {
fn merge_with(&self, other: &Self) -> Self {
match (self, other) {
(Some(_), _) => self.clone(),
(None, Some(_)) => other.clone(),
(None, None) => None,
}
}
}
impl<V: Clone> MergeWith for HashMap<String, V> {
fn merge_with(&self, other: &Self) -> Self {
let mut merged = HashMap::new();
for (key, value) in other.iter().chain(self) {
merged.insert(key.clone(), value.clone());
}
merged
}
}
#[allow(dead_code)]
mod __unused {
const _: &[u8] = include_bytes!("../askama.toml");
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_guessing_of_crate_root_directory_from_udl_file() {
let this_crate_root = Utf8PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let example_crate_root = this_crate_root
.parent()
.expect("should have a parent directory")
.join("./examples/arithmetic");
assert_eq!(
guess_crate_root(&example_crate_root.join("./src/arthmetic.udl")).unwrap(),
example_crate_root
);
let not_a_crate_root = &this_crate_root.join("./src/templates");
assert!(guess_crate_root(¬_a_crate_root.join("./src/example.udl")).is_err());
}
}