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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
use databake::{quote, CrateEnv, TokenStream};
use icu_provider::datagen::*;
use icu_provider::prelude::*;
use rayon::prelude::*;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashMap;
use std::fs::File;
use std::io::Write;
use std::path::PathBuf;
use std::sync::Mutex;
macro_rules! move_out {
($field:expr) => {{
let mut tmp = Default::default();
core::mem::swap(&mut tmp, &mut $field);
tmp
}};
}
// TokenStream isn't Send/Sync
type SyncTokenStream = String;
#[allow(clippy::type_complexity)]
pub(crate) struct BakedDataExporter {
// Input arguments
mod_directory: PathBuf,
pretty: bool,
insert_feature_gates: bool,
use_separate_crates: bool,
// Temporary storage for put_payload: key -> (bake -> [locale])
data: Mutex<HashMap<DataKey, HashMap<SyncTokenStream, Vec<String>>>>,
// All mod.rs files in the module tree. These can only be written after the last flush.
mod_files: Mutex<HashMap<PathBuf, BTreeSet<String>>>,
/// Information to generate implementations. This is populated by `flush` and consumed by `close`.
impl_data: Mutex<Vec<ImplData>>,
// List of dependencies used by baking.
dependencies: CrateEnv,
}
/// Data required to write the implementations
struct ImplData {
/// The marker of the key
marker: SyncTokenStream,
/// The path to the lookup function for this marker
lookup_ident: SyncTokenStream,
/// The feature gate for the marker
feature: SyncTokenStream,
}
impl BakedDataExporter {
pub fn new(
mod_directory: PathBuf,
pretty: bool,
insert_feature_gates: bool,
use_separate_crates: bool,
) -> Result<Self, DataError> {
if mod_directory.exists() {
std::fs::remove_dir(&mod_directory)
.map_err(|e| DataError::from(e).with_path_context(&mod_directory))?;
}
Ok(Self {
mod_directory,
pretty,
insert_feature_gates: insert_feature_gates && use_separate_crates,
use_separate_crates,
data: Default::default(),
mod_files: Default::default(),
impl_data: Default::default(),
dependencies: Default::default(),
})
}
fn write_to_file<P: AsRef<std::path::Path>>(
&self,
relative_path: P,
data: TokenStream,
is_expr: bool,
) -> Result<(), DataError> {
let path = self
.mod_directory
.join(&relative_path)
.with_extension(if is_expr { "rs.data" } else { "rs" });
let mut formatted = if self.pretty {
use rust_format::*;
RustFmt::from_config(
Config::new_str()
// We deal with line encoding later
.option("newline_style", "unix")
.option("normalize_doc_attributes", "true")
// Rustfmt silently gives up if it cannot achieve the max width, which happens for the root mod.rs
.option(
"max_width",
if relative_path.as_ref().as_os_str().to_str() == Some("mod") {
"150"
} else {
"100"
},
),
)
.format_tokens(if is_expr {
// Rustfmt cannot format Rust expressions, only full files. We need to wrap expressions in a main function
quote!(fn main() { #data })
} else {
data
})
.map_err(|e| {
DataError::custom("Formatting error")
.with_display_context(&e)
.with_path_context(&path)
})?
} else {
data.to_string()
};
if !self.use_separate_crates {
formatted = formatted
.replace("icu_", "icu::")
.replace("icu::provider", "icu_provider");
}
let formatted = if self.pretty && is_expr {
formatted = formatted.replace("\n ", "\n");
formatted
.strip_prefix("fn main() {\n")
.unwrap()
.strip_suffix("}\n")
.unwrap()
} else {
&formatted
};
std::fs::create_dir_all(&path.parent().unwrap())?;
let mut file = crlify::BufWriterWithLineEndingFix::new(
File::create(&path).map_err(|e| DataError::from(e).with_path_context(&path))?,
);
if !is_expr {
writeln!(file, "// @generated")
.map_err(|e| DataError::from(e).with_path_context(&path))?;
}
write!(file, "{formatted}").map_err(|e| DataError::from(e).with_path_context(&path))
}
fn print_deps(&mut self) {
let mut deps = move_out!(self.dependencies)
.into_iter()
.collect::<BTreeSet<_>>();
if !self.use_separate_crates {
deps.retain(|&krate| krate.starts_with("icu_provider") || !krate.starts_with("icu_"));
deps.insert("icu");
}
deps.insert("icu_provider");
// TODO: make locale fallback cfg'ed
deps.insert("icu_provider_adapters");
log::info!("The generated module requires the following crates:");
for crate_name in deps {
log::info!("{}", crate_name);
}
}
fn write_intermediate_mod_files(&mut self) -> Result<(), DataError> {
move_out!(self.mod_files)
.into_inner()
.expect("poison")
.into_par_iter()
.try_for_each(|(path, mods)| {
let mods = mods.into_iter().map(|p| p.parse::<TokenStream>().unwrap());
self.write_to_file(
&path.join("mod"),
quote! {
#(
pub mod #mods;
)*
},
false,
)
})?;
Ok(())
}
}
impl DataExporter for BakedDataExporter {
fn put_payload(
&self,
key: DataKey,
locale: &DataLocale,
payload: &DataPayload<ExportMarker>,
) -> Result<(), DataError> {
let payload = payload.tokenize(&self.dependencies);
self.data
.lock()
.expect("poison")
.entry(key)
.or_default()
.entry(payload.to_string())
.or_default()
.push(locale.to_string());
Ok(())
}
fn flush(&self, key: DataKey) -> Result<(), DataError> {
let marker =
syn::parse2::<syn::Path>(crate::registry::key_to_marker_bake(key, &self.dependencies))
.unwrap();
let is_datetime_skeletons =
marker.segments.iter().next_back().unwrap().ident == "DateSkeletonPatternsV1Marker";
let feature = if !self.insert_feature_gates {
quote!()
} else if is_datetime_skeletons {
quote! { #![cfg(feature = "icu_datetime_experimental")] }
} else {
let feature = marker.segments.iter().next().unwrap().ident.to_string();
if !feature.starts_with("icu_provider") {
quote! { #![cfg(feature = #feature)] }
} else {
quote!()
}
};
// Replace non-ident-allowed tokens. This can still fail if a segment starts with
// a token that is not allowed in an initial position.
let module_path = syn::parse_str::<syn::Path>(
&key.path()
.to_ascii_lowercase()
.replace('@', "_v")
.replace('/', "::"),
)
.map_err(|_| {
DataError::custom("Key component is not a valid Rust identifier").with_key(key)
})?;
let mut path = PathBuf::new();
for level in &module_path.segments {
self.mod_files
.lock()
.expect("poison")
.entry(path.clone())
.or_default()
.insert(level.ident.to_string());
path = path.join(level.ident.to_string());
}
let struct_type = if is_datetime_skeletons {
quote! {
&'static [(
&'static [::icu_datetime::fields::Field],
::icu_datetime::pattern::runtime::PatternPlurals<'static>
)]
}
} else {
quote! { <#marker as ::icu_provider::DataMarker>::Yokeable }
};
let mut map = BTreeMap::new();
let mut statics = BTreeMap::new();
let raw = self
.data
.lock()
.expect("poison")
.remove(&key)
.unwrap_or_default();
for (payload_bake_string, locales) in raw {
let file_name = locales.iter().min().unwrap();
let ident =
syn::parse_str::<syn::Ident>(&file_name.to_ascii_uppercase().replace('-', "_"))
.unwrap();
self.write_to_file(
&path.join(file_name),
payload_bake_string.parse().unwrap(),
true,
)?;
let file_name = format!("{file_name}.rs.data");
let statik = quote! { static #ident: DataStruct = include!(#file_name); };
statics.insert(file_name, statik);
map.extend(locales.into_iter().map(|l| (l, ident.clone())));
}
let (keys, values): (Vec<_>, Vec<_>) = map.into_iter().unzip();
let lookup = match keys.len() {
0 => {
quote! {
pub const fn lookup(_: &icu_provider::DataLocale) -> Option<&'static DataStruct> {
None
}
}
}
1 => {
let locale = &keys[0];
let cmp = if locale == "und" {
quote! {
locale.is_empty()
}
} else if icu_locid::Locale::try_from_bytes_with_single_variant_single_keyword_unicode_extension(locale.as_bytes()).is_ok() {
self.dependencies.insert("icu_locid");
quote! {
icu_provider::DataLocale::from(icu_locid::locale!(#locale)).eq(locale)
}
} else {
quote! {
locale.strict_cmp(#locale.as_bytes()).is_eq()
}
};
quote! {
pub fn lookup(locale: &icu_provider::DataLocale) -> Option<&'static DataStruct> {
// This repetition is a singleton
#cmp.then(|| #(&#values)*)
}
}
}
n => {
quote! {
pub fn lookup(locale: &icu_provider::DataLocale) -> Option<&'static DataStruct> {
static KEYS: [&str; #n] = [#(#keys),*];
static DATA: [&DataStruct; #n] = [#(&#values),*];
KEYS
.binary_search_by(|k| locale.strict_cmp(k.as_bytes()).reverse())
.ok()
.map(|i| unsafe {
// Safe because KEYS and DATA have the same length
*DATA.get_unchecked(i)
})
}
}
}
};
let statics = statics.values();
self.write_to_file(
&path.join("mod"),
quote! {
#feature
type DataStruct = #struct_type;
#lookup
#(#statics)*
},
false,
)?;
self.impl_data.lock().expect("poison").push(ImplData {
marker: quote!(#marker).to_string(),
lookup_ident: quote!(#module_path :: lookup).to_string(),
feature: feature.to_string().replacen("# ! [", "# [", 1),
});
Ok(())
}
fn close(&mut self) -> Result<(), DataError> {
// These are BTreeMaps keyed on the marker to keep the output sorted and stable
let mut data_impls = BTreeMap::new();
let mut any_consts = BTreeMap::new();
let mut any_cases = BTreeMap::new();
for data in move_out!(self.impl_data)
.into_inner()
.expect("poison")
.into_iter()
{
let feature = data.feature.parse::<TokenStream>().unwrap();
let marker = data.marker.parse::<TokenStream>().unwrap();
let lookup_ident = data.lookup_ident.parse::<TokenStream>().unwrap();
data_impls.insert(data.marker.clone(),
quote! {
#feature
impl DataProvider<#marker> for $provider {
fn load(
&self,
req: DataRequest,
) -> Result<DataResponse<#marker>, DataError> {
#lookup_ident(&req.locale)
.map(zerofrom::ZeroFrom::zero_from)
.map(DataPayload::from_owned)
.map(|payload| {
DataResponse {
metadata: Default::default(),
payload: Some(payload),
}
})
.ok_or_else(|| DataErrorKind::MissingLocale.with_req(#marker::KEY, req))
}
}
});
let hash_ident = data
.marker
.split(' ')
.next_back()
.unwrap()
.to_ascii_uppercase()
.parse::<TokenStream>()
.unwrap();
any_consts.insert(
data.marker.clone(),
quote! {
#feature
const #hash_ident: ::icu_provider::DataKeyHash = #marker::KEY.hashed();
},
);
any_cases.insert(
data.marker.clone(),
if data.marker
== ":: icu_datetime :: provider :: calendar :: DateSkeletonPatternsV1Marker"
{
quote! {
#feature
#hash_ident => {
#lookup_ident(&req.locale)
.map(zerofrom::ZeroFrom::zero_from)
.map(DataPayload::<#marker>::from_owned)
.map(DataPayload::wrap_into_any_payload)
}
}
} else {
quote! {
#feature
#hash_ident => #lookup_ident(&req.locale).map(AnyPayload::from_static_ref),
}
},
);
}
let any_code = if any_cases.is_empty() {
quote! {
Err(DataErrorKind::MissingDataKey.with_req(key, req))
}
} else {
let any_consts = any_consts.values();
let any_cases = any_cases.values();
quote! {
#(#any_consts)*
match key.hashed() {
#(#any_cases)*
_ => return Err(DataErrorKind::MissingDataKey.with_req(key, req)),
}
.map(|payload| AnyResponse {
payload: Some(payload),
metadata: Default::default(),
})
.ok_or_else(|| DataErrorKind::MissingLocale.with_req(key, req))
}
};
let mods = self
.mod_files
.get_mut()
.expect("poison")
.remove(&PathBuf::new())
.unwrap_or_default()
.into_iter()
.map(|p| p.parse::<TokenStream>().unwrap());
let data_impls = data_impls.values();
self.write_to_file(
PathBuf::from("mod"),
quote! {
#(
mod #mods;
)*
use ::icu_provider::prelude::*;
/// Implement [`DataProvider<M>`] on the given struct using the data
/// hardcoded in this module. This allows the struct to be used with
/// `icu`'s `_unstable` constructors.
///
/// This macro can only be called from its definition-site, i.e. right
/// after `include!`-ing the generated module.
///
/// ```compile_fail
/// struct MyDataProvider;
/// include!("/path/to/generated/mod.rs");
/// impl_data_provider(MyDataProvider);
/// ```
#[allow(unused_macros)]
macro_rules! impl_data_provider {
($provider:path) => {
#(#data_impls)*
}
}
/// Implement [`AnyProvider`] on the given struct using the data
/// hardcoded in this module. This allows the struct to be used with
/// `icu`'s `_any` constructors.
///
/// This macro can only be called from its definition-site, i.e. right
/// after `include!`-ing the generated module.
///
/// ```compile_fail
/// struct MyAnyProvider;
/// include!("/path/to/generated/mod.rs");
/// impl_any_provider(MyAnyProvider);
/// ```
#[allow(unused_macros)]
macro_rules! impl_any_provider {
($provider:path) => {
impl AnyProvider for $provider {
fn load_any(&self, key: DataKey, req: DataRequest) -> Result<AnyResponse, DataError> {
#any_code
}
}
}
}
pub struct BakedDataProvider;
impl_data_provider!(BakedDataProvider);
},
false,
)?;
self.write_to_file(
PathBuf::from("any"),
quote! {
impl_any_provider!(BakedDataProvider);
},
false,
)?;
self.write_intermediate_mod_files()?;
self.print_deps();
Ok(())
}
}