1mod scoped_locales;
38pub use scoped_locales::{generate_locales, render_crate_locales};
39
40use std::fmt::Write as _;
41use std::path::{Path, PathBuf};
42
43pub mod bridge;
44pub mod permissions;
45pub mod swiftui;
46
47pub fn app_title() -> Result<String, String> {
58 println!("cargo:rerun-if-env-changed=DAY_APP_TITLE");
59 println!("cargo:rerun-if-changed=Day.toml");
60 if let Ok(title) = std::env::var("DAY_APP_TITLE") {
61 return Ok(title);
62 }
63 let root = PathBuf::from(env("CARGO_MANIFEST_DIR")?);
64 let source = std::fs::read_to_string(root.join("Day.toml"))
65 .map_err(|e| format!("day-build: reading Day.toml: {e}"))?;
66 manifest_title(&source, &env("CARGO_PKG_NAME")?)
67}
68
69fn manifest_title(source: &str, package_name: &str) -> Result<String, String> {
70 let manifest: toml::Value =
71 toml::from_str(source).map_err(|e| format!("day-build: parsing Day.toml: {e}"))?;
72 match manifest.get("app").and_then(|app| app.get("title")) {
73 Some(title) => title
74 .as_str()
75 .map(str::to_owned)
76 .ok_or_else(|| "day-build: app.title must be a string".to_string()),
77 None => Ok(package_name.to_owned()),
78 }
79}
80
81#[derive(Clone, Copy, Debug, Default, PartialEq)]
86pub struct WindowGeometry {
87 pub size: Option<(f64, f64)>,
88 pub min_size: Option<(f64, f64)>,
89}
90
91pub fn window_geometry() -> Result<WindowGeometry, String> {
99 let root = PathBuf::from(env("CARGO_MANIFEST_DIR")?);
100 match std::fs::read_to_string(root.join("Day.toml")) {
101 Ok(source) => manifest_window(&source),
102 Err(_) => Ok(WindowGeometry::default()),
103 }
104}
105
106fn manifest_window(source: &str) -> Result<WindowGeometry, String> {
107 let manifest: toml::Value =
108 toml::from_str(source).map_err(|e| format!("day-build: parsing Day.toml: {e}"))?;
109 let Some(window) = manifest.get("window") else {
110 return Ok(WindowGeometry::default());
111 };
112 let points = |key: &str| -> Result<Option<f64>, String> {
113 match window.get(key) {
114 None => Ok(None),
115 Some(v) => v
116 .as_float()
117 .or_else(|| v.as_integer().map(|i| i as f64))
118 .map(Some)
119 .ok_or_else(|| format!("day-build: window.{key} must be a number")),
120 }
121 };
122 let pair = |w: &str, h: &str, default: (f64, f64)| -> Result<Option<(f64, f64)>, String> {
123 Ok(match (points(w)?, points(h)?) {
124 (None, None) => None,
125 (w, h) => Some((w.unwrap_or(default.0), h.unwrap_or(default.1))),
126 })
127 };
128 Ok(WindowGeometry {
129 size: pair("width", "height", (480.0, 640.0))?,
130 min_size: pair("min_width", "min_height", (320.0, 400.0))?,
131 })
132}
133
134#[cfg(test)]
135mod endonym_tests {
136 use super::endonym;
137
138 #[test]
139 fn a_tag_resolves_to_its_language_s_own_name() {
140 assert_eq!(endonym("fr"), Some("Français"));
141 assert_eq!(endonym("fr-FR"), Some("Français"));
142 assert_eq!(endonym("pt-BR"), Some("Português (Brasil)"));
143 assert_eq!(endonym("zh-Hans-CN"), Some("简体中文"));
144 assert_eq!(endonym("zh-Hant-TW"), Some("繁體中文"));
145 assert_eq!(endonym("tlh"), None);
146 }
147}
148
149#[cfg(test)]
150mod window_geometry_tests {
151 use super::{WindowGeometry, manifest_window};
152
153 #[test]
154 fn declared_keys_reach_the_geometry_and_missing_ones_default() {
155 let declared = "[window]\nwidth = 960\nheight = 640.0\nmin_width = 300\n";
156 assert_eq!(
157 manifest_window(declared).unwrap(),
158 WindowGeometry {
159 size: Some((960.0, 640.0)),
160 min_size: Some((300.0, 400.0)),
161 }
162 );
163 assert_eq!(manifest_window("[app]").unwrap(), WindowGeometry::default());
164 assert!(manifest_window("[window]\nwidth = 'wide'").is_err());
165 }
166}
167
168#[cfg(test)]
169mod app_title_tests {
170 use super::manifest_title;
171
172 #[test]
173 fn metadata_title_supports_renames_and_toml_escaping() {
174 assert_eq!(
175 manifest_title("[app]\ntitle = 'Fork \"Games\" 🎲'", "fork-games").unwrap(),
176 "Fork \"Games\" 🎲"
177 );
178 assert_eq!(manifest_title("[app]", "fork-games").unwrap(), "fork-games");
179 assert!(manifest_title("[app]\ntitle = 123", "fork-games").is_err());
180 }
181}
182
183#[derive(Debug, Clone, PartialEq, Eq)]
186pub struct Entry {
187 pub symbol: String,
188 pub value: String,
189 pub source: String,
190}
191
192#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct StrEntry {
197 pub key: String,
198 pub params: Vec<StrParam>,
199 pub doc: String,
200}
201
202#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct StrParam {
207 pub name: String,
208 pub numeric: bool,
209}
210
211#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct LocaleEntry {
216 pub locale: String,
217 pub sources: Vec<PathBuf>,
218}
219
220#[derive(Debug, Default, Clone, PartialEq, Eq)]
222pub struct ResourcePlan {
223 pub images: Vec<Entry>,
224 pub vectors: Vec<Entry>,
227 pub assets: AssetNode,
231 pub fonts: Vec<Entry>,
232 pub strings: Vec<StrEntry>,
234 pub locales: Vec<LocaleEntry>,
237}
238
239pub fn prebuild_project() -> Result<(), String> {
259 generate_resources()
260}
261
262pub fn generate_resources() -> Result<(), String> {
274 let root = PathBuf::from(env("CARGO_MANIFEST_DIR")?);
275 let out = PathBuf::from(env("OUT_DIR")?);
276 let resources = match std::env::var("DAY_RESOURCE_ROOT") {
281 Ok(dir) if !dir.trim().is_empty() => PathBuf::from(dir),
282 _ => root.join("resource"),
283 };
284 println!("cargo:rerun-if-env-changed=DAY_RESOURCE_ROOT");
285 let plan = plan_resources_in(&resources)?;
286 let title = app_title().ok();
287 let mut code = render_app(&plan, title.as_deref(), window_geometry()?);
288 code.push_str(&web_resources::generate(&resources)?);
289 code.push_str(&render_shortcuts(&launcher_shortcuts(&root)?));
290 std::fs::write(out.join("day_resources.rs"), code)
291 .map_err(|e| format!("day-build: writing day_resources.rs: {e}"))?;
292 watch_resources(&root.join("resource"), "resource");
297 println!("cargo:rerun-if-env-changed=DAY_RESOURCE_OVERLAY");
302 if let Ok(overlay) = std::env::var("DAY_RESOURCE_OVERLAY")
303 && !overlay.trim().is_empty()
304 {
305 let dir = PathBuf::from(&overlay);
306 let shown = dir.display().to_string();
307 watch_resources(&dir, &shown);
308 }
309 swiftui::generate_bindings(&root, &out)?;
313 println!("cargo:rerun-if-changed=Cargo.toml");
314 Ok(())
315}
316
317fn launcher_shortcuts(root: &Path) -> Result<Vec<(String, String)>, String> {
320 let Ok(source) = std::fs::read_to_string(root.join("Day.toml")) else {
321 return Ok(Vec::new());
322 };
323 println!("cargo:rerun-if-changed=Day.toml");
324 let manifest: toml::Value =
325 toml::from_str(&source).map_err(|e| format!("day-build: parsing Day.toml: {e}"))?;
326 let Some(list) = manifest.get("shortcuts").and_then(|v| v.as_array()) else {
327 return Ok(Vec::new());
328 };
329 list.iter()
330 .map(|entry| {
331 let field = |name: &str| {
332 entry
333 .get(name)
334 .and_then(|v| v.as_str())
335 .map(str::to_owned)
336 .ok_or_else(|| {
337 format!("day-build: [[shortcuts]] entry needs a string `{name}`")
338 })
339 };
340 Ok((field("route")?, field("label")?))
341 })
342 .collect()
343}
344
345fn render_shortcuts(shortcuts: &[(String, String)]) -> String {
349 if shortcuts.is_empty() {
350 return String::new();
351 }
352 let mut s = String::from(
353 "\n/// The app's `[[shortcuts]]` from Day.toml, registered for the menus Day builds while \
354 the app runs.\n#[cfg(not(target_arch = \"wasm32\"))]\n\
355 #[::day::linkme::distributed_slice(::day::LAUNCHER_SHORTCUTS)]\n\
356 #[linkme(crate = ::day::linkme)]\n\
357 static __DAY_LAUNCHER_SHORTCUTS: &[(&str, &str)] = &[\n",
358 );
359 for (route, label) in shortcuts {
360 let _ = writeln!(s, " ({route:?}, {label:?}),");
361 }
362 s.push_str("];\n");
363 s
364}
365
366fn watch_resources(dir: &Path, shown: &str) {
371 if !dir.is_dir() {
372 return;
373 }
374 println!("cargo:rerun-if-changed={shown}");
375 for bucket in ["images", "vectors", "assets", "fonts", "locales"] {
376 if dir.join(bucket).is_dir() {
377 println!("cargo:rerun-if-changed={shown}/{bucket}");
378 }
379 }
380}
381
382fn env(key: &str) -> Result<String, String> {
383 std::env::var(key).map_err(|_| format!("day-build: ${key} is not set (call from a build.rs)"))
384}
385
386pub fn plan_resources(root: &Path) -> Result<ResourcePlan, String> {
392 plan_resources_in(&root.join("resource"))
393}
394
395pub fn plan_resources_in(resource: &Path) -> Result<ResourcePlan, String> {
403 Ok(ResourcePlan {
404 images: plan_images(&resource.join("images"))?,
405 vectors: plan_vectors(&resource.join("vectors"))?,
406 assets: plan_assets(&resource.join("assets"))?,
407 fonts: plan_fonts(&resource.join("fonts"))?,
408 strings: plan_strings(&resource.join("locales"))?,
409 locales: plan_locales(&resource.join("locales")),
410 })
411}
412
413fn list_files(dir: &Path) -> Vec<PathBuf> {
415 let mut files: Vec<PathBuf> = std::fs::read_dir(dir)
416 .into_iter()
417 .flatten()
418 .flatten()
419 .map(|e| e.path())
420 .filter(|p| {
421 p.is_file()
422 && !p
423 .file_name()
424 .and_then(|n| n.to_str())
425 .unwrap_or("")
426 .starts_with('.')
427 })
428 .collect();
429 files.sort();
430 files
431}
432
433fn plan_vectors(dir: &Path) -> Result<Vec<Entry>, String> {
443 let mut out: Vec<Entry> = Vec::new();
444 let mut names: std::collections::BTreeSet<String> = std::collections::BTreeSet::default();
445 let entries: Vec<PathBuf> = std::fs::read_dir(dir)
446 .into_iter()
447 .flatten()
448 .flatten()
449 .map(|e| e.path())
450 .collect();
451 let mut sorted = entries;
452 sorted.sort();
453 for path in sorted {
454 let fname = path
455 .file_name()
456 .and_then(|n| n.to_str())
457 .unwrap_or_default();
458 if fname.starts_with('.') {
459 continue;
460 }
461 let stem = match (path.is_file(), path.is_dir()) {
462 (true, _) if fname.to_ascii_lowercase().ends_with(".svg") => path
463 .file_stem()
464 .and_then(|s| s.to_str())
465 .unwrap_or_default()
466 .to_string(),
467 (_, true) if fname.to_ascii_lowercase().ends_with(".symbolset") => {
468 fname[..fname.len() - ".symbolset".len()].to_string()
469 }
470 _ => continue,
471 };
472 let sane = sanitize_ident(&stem);
473 if sane != stem {
474 return Err(format!(
475 "day-build: vector {stem:?} ({}) is not a portable resource name — rename it so \
476 its stem is lowercase [a-z0-9_] (e.g. `{sane}`).",
477 display(&path)
478 ));
479 }
480 if !names.insert(stem.clone()) {
481 return Err(format!(
482 "day-build: two entries map to vector {stem:?} — keep one .svg or .symbolset per name."
483 ));
484 }
485 out.push(Entry {
486 symbol: stem.clone(),
487 value: stem,
488 source: display(&path),
489 });
490 }
491 Ok(out)
492}
493
494fn plan_images(dir: &Path) -> Result<Vec<Entry>, String> {
495 let mut seen: std::collections::BTreeMap<String, (Vec<u32>, String)> =
497 std::collections::BTreeMap::default();
498 for path in list_files(dir) {
499 let stem = path
500 .file_stem()
501 .and_then(|s| s.to_str())
502 .unwrap_or_default()
503 .to_string();
504 let (base, scale) = parse_scale(&stem);
505 let src = display(&path);
506 let sane = sanitize_ident(&base);
507 if sane != base {
508 return Err(format!(
509 "day-build: image {base:?} ({src}) is not a portable resource name — it resolves \
510 to {sane:?} on Android/HarmonyOS but {base:?} on Apple/GTK/Qt. Rename the file so \
511 its stem is lowercase [a-z0-9_] (e.g. `{sane}`)."
512 ));
513 }
514 let ent = seen
515 .entry(base.clone())
516 .or_insert_with(|| (Vec::new(), src.clone()));
517 if ent.0.contains(&scale) {
518 return Err(format!(
519 "day-build: two files map to image {base:?} at the same scale ({}, {src}) — keep \
520 one file per image (HiDPI variants use an `@2x`/`@3x` suffix).",
521 ent.1
522 ));
523 }
524 ent.0.push(scale);
525 }
526 Ok(seen
527 .into_iter()
528 .map(|(base, (_, src))| Entry {
529 symbol: base.clone(),
530 value: base,
531 source: src,
532 })
533 .collect())
534}
535
536#[derive(Debug, Default, Clone, PartialEq, Eq)]
541pub struct AssetNode {
542 pub path: String,
543 pub files: Vec<Entry>,
544 pub dirs: Vec<(String, AssetNode)>,
546}
547
548fn plan_assets(dir: &Path) -> Result<AssetNode, String> {
554 plan_asset_dir(dir, "")
555}
556
557fn plan_asset_dir(dir: &Path, rel: &str) -> Result<AssetNode, String> {
558 let mut files = Vec::new();
559 for path in list_files(dir) {
560 let fname = path
561 .file_name()
562 .and_then(|n| n.to_str())
563 .unwrap_or_default()
564 .to_string();
565 let value = if rel.is_empty() {
566 fname.clone()
567 } else {
568 format!("{rel}/{fname}")
569 };
570 files.push(Entry {
571 symbol: sanitize_ident(&fname),
572 value,
573 source: display(&path),
574 });
575 }
576 let mut dirs = Vec::new();
577 let mut subdirs: Vec<PathBuf> = std::fs::read_dir(dir)
578 .into_iter()
579 .flatten()
580 .flatten()
581 .map(|e| e.path())
582 .filter(|p| {
583 p.is_dir()
584 && !p
585 .file_name()
586 .and_then(|n| n.to_str())
587 .unwrap_or("")
588 .starts_with('.')
589 })
590 .collect();
591 subdirs.sort();
592 for sub in subdirs {
593 let dname = sub
594 .file_name()
595 .and_then(|n| n.to_str())
596 .unwrap_or_default()
597 .to_string();
598 let sub_rel = if rel.is_empty() {
599 dname.clone()
600 } else {
601 format!("{rel}/{dname}")
602 };
603 dirs.push((sanitize_ident(&dname), plan_asset_dir(&sub, &sub_rel)?));
604 }
605 let mut probe = files.clone();
607 for (sym, node) in &dirs {
608 probe.push(Entry {
609 symbol: sym.clone(),
610 value: node.path.clone(),
611 source: format!("resource/assets/{} (directory)", node.path),
612 });
613 }
614 dedup_symbols(probe, "asset")?;
615 Ok(AssetNode {
616 path: rel.to_string(),
617 files,
618 dirs,
619 })
620}
621
622fn plan_fonts(dir: &Path) -> Result<Vec<Entry>, String> {
626 let mut entries = Vec::new();
627 for path in list_files(dir) {
628 let ext = path
629 .extension()
630 .and_then(|e| e.to_str())
631 .map_or_default(str::to_ascii_lowercase);
632 if !matches!(ext.as_str(), "ttf" | "otf") {
633 continue; }
635 let src = display(&path);
636 let bytes = std::fs::read(&path).map_err(|e| format!("day-build: reading {src}: {e}"))?;
637 let names = day_fonts::parse_font_names(&bytes)
638 .ok_or_else(|| format!("day-build: {src}: not a recognizable font (no name table)"))?;
639 entries.push(Entry {
640 symbol: day_fonts::font_ident(&names.family),
641 value: names.family,
642 source: src,
643 });
644 }
645 dedup_symbols(entries, "font")
646}
647
648fn dedup_symbols(entries: Vec<Entry>, kind: &str) -> Result<Vec<Entry>, String> {
650 let mut seen: std::collections::BTreeMap<String, String> =
651 std::collections::BTreeMap::default();
652 for e in &entries {
653 if let Some(prev) = seen.insert(e.symbol.clone(), e.source.clone()) {
654 return Err(format!(
655 "day-build: {kind}s {} and {} both map to the symbol `{}` — rename one so they \
656 differ after sanitization to [a-z0-9_].",
657 prev, e.source, e.symbol
658 ));
659 }
660 }
661 Ok(entries)
662}
663
664fn ftl_files(dir: &Path) -> Vec<PathBuf> {
666 let mut out = Vec::new();
667 let mut stack = vec![dir.to_path_buf()];
668 while let Some(d) = stack.pop() {
669 let Ok(entries) = std::fs::read_dir(&d) else {
670 continue;
671 };
672 for e in entries.flatten() {
673 let p = e.path();
674 if p.is_dir() {
675 stack.push(p);
676 } else if p.extension().is_some_and(|x| x == "ftl") {
677 out.push(p);
678 }
679 }
680 }
681 out.sort();
682 out
683}
684
685#[must_use]
700pub fn res_str_ident(key: &str) -> String {
701 key.replace('.', "_")
702}
703
704#[must_use]
709pub fn message_texts(ftl_src: &str) -> Vec<(String, String)> {
710 ftl_messages(ftl_src)
711 .into_iter()
712 .filter(|m| !m.key.contains('.'))
713 .map(|m| (m.key, m.value_text))
714 .collect()
715}
716
717#[must_use]
718pub fn message_keys(ftl_src: &str) -> Vec<String> {
719 ftl_messages(ftl_src)
720 .into_iter()
721 .map(|m| m.key)
722 .filter(|k| !k.contains('.'))
723 .collect()
724}
725
726fn plan_strings(dir: &Path) -> Result<Vec<StrEntry>, String> {
734 plan_strings_from_files(&ftl_files(dir))
735}
736
737fn plan_strings_from_files(files: &[PathBuf]) -> Result<Vec<StrEntry>, String> {
738 use std::collections::btree_map::Entry;
739 let mut agreed: std::collections::BTreeMap<String, (Params, String)> =
741 std::collections::BTreeMap::default();
742 let mut docs: std::collections::BTreeMap<String, (String, bool)> =
744 std::collections::BTreeMap::default();
745 for path in files {
746 let src = std::fs::read_to_string(path)
747 .map_err(|e| format!("day-build: reading {}: {e}", display(path)))?;
748 let loc = display(path);
749 let is_en = locale_of(path) == "en";
750 for msg in ftl_messages(&src) {
751 let ident_ok = match msg.key.split_once('.') {
752 Some((m, a)) => is_rust_ident(m) && is_rust_ident(a),
755 None => is_rust_ident(&msg.key),
756 };
757 if !ident_ok {
758 return Err(format!(
759 "day-build: localization key {:?} ({loc}) is not a valid Rust identifier — \
760 rename it to snake_case (e.g. `{}`) in every resource/locales/*/*.ftl (Fluent \
761 allows `-`, Rust identifiers do not).",
762 msg.key,
763 msg.key.replace(['-', '.'], "_")
764 ));
765 }
766 let have_en = matches!(docs.get(&msg.key), Some((_, true)));
768 if !have_en && (is_en || !docs.contains_key(&msg.key)) {
769 docs.insert(msg.key.clone(), (msg.value_text, is_en));
770 }
771 match agreed.entry(msg.key.clone()) {
773 Entry::Vacant(v) => {
774 v.insert((msg.params, loc.clone()));
775 }
776 Entry::Occupied(mut o) => {
777 let (prev, prev_loc) = o.get_mut();
778 let prev_names: Vars = prev.keys().cloned().collect();
779 let this_names: Vars = msg.params.keys().cloned().collect();
780 if prev_names != this_names {
781 return Err(format!(
782 "day-build: localization key {:?} references different parameters across \
783 locales — {prev_loc} has {{{}}}, {loc} has {{{}}}. Every locale's \
784 message must use the same `$variables`.",
785 msg.key,
786 comma(&prev_names),
787 comma(&this_names)
788 ));
789 }
790 for (name, numeric) in msg.params {
791 if numeric && let Some(v) = prev.get_mut(&name) {
792 *v = true;
793 }
794 }
795 }
796 }
797 }
798 }
799 {
802 let mut fn_names: std::collections::BTreeMap<String, &String> =
803 std::collections::BTreeMap::default();
804 for key in agreed.keys() {
805 let fn_name = res_str_ident(key);
806 if let Some(prev) = fn_names.insert(fn_name.clone(), key) {
807 return Err(format!(
808 "day-build: localization keys {prev:?} and {key:?} both generate \
809 `res::str::{fn_name}()` — rename one (a `message.attr` attribute \
810 flattens to `message_attr`)."
811 ));
812 }
813 }
814 }
815 Ok(agreed
816 .into_iter()
817 .map(|(key, (params, _))| {
818 let doc = docs.remove(&key).map_or_default(|(t, _)| t);
819 StrEntry {
820 key,
821 params: params
822 .into_iter()
823 .map(|(name, numeric)| StrParam { name, numeric })
824 .collect(),
825 doc,
826 }
827 })
828 .collect())
829}
830
831fn comma(names: &Vars) -> String {
832 names.iter().cloned().collect::<Vec<_>>().join(", ")
833}
834
835fn plan_locales(dir: &Path) -> Vec<LocaleEntry> {
845 let mut by_locale: std::collections::BTreeMap<String, Vec<PathBuf>> =
846 std::collections::BTreeMap::default();
847 for path in ftl_files(dir) {
848 let locale = locale_of(&path);
849 if locale.is_empty() || path.parent() == Some(dir) {
852 continue;
853 }
854 by_locale.entry(locale).or_default().push(path);
855 }
856 by_locale
857 .into_iter()
858 .map(|(locale, sources)| LocaleEntry { locale, sources })
859 .collect()
860}
861
862fn default_locale(locales: &[LocaleEntry]) -> String {
867 if locales.iter().any(|l| l.locale == "en") {
868 return "en".to_string();
869 }
870 locales
871 .first()
872 .map_or_else(|| "en".to_string(), |l| l.locale.clone())
873}
874
875fn locale_of(path: &Path) -> String {
877 path.parent()
878 .and_then(|p| p.file_name())
879 .map_or_default(|n| n.to_string_lossy().into_owned())
880}
881
882struct FtlMessage {
884 key: String,
885 params: Params,
886 value_text: String,
887}
888
889fn ftl_messages(src: &str) -> Vec<FtlMessage> {
894 use fluent_syntax::ast::Entry;
895 let res = match fluent_syntax::parser::parse(src) {
896 Ok(r) => r,
897 Err((r, _errs)) => r,
898 };
899 let mut out = Vec::new();
900 for entry in &res.body {
901 if let Entry::Message(m) = entry {
902 let mut params = Params::new();
903 let value_text = match &m.value {
904 Some(value) => {
905 collect_pattern_vars(value, &mut params, false);
906 pattern_text(value)
907 }
908 None => String::new(),
909 };
910 out.push(FtlMessage {
911 key: m.id.name.to_string(),
912 params,
913 value_text,
914 });
915 for attr in &m.attributes {
916 let mut params = Params::new();
917 collect_pattern_vars(&attr.value, &mut params, false);
918 out.push(FtlMessage {
919 key: format!("{}.{}", m.id.name, attr.id.name),
920 params,
921 value_text: pattern_text(&attr.value),
922 });
923 }
924 }
925 }
926 out
927}
928
929#[cfg(test)]
930mod span_tests {
931 use super::*;
932
933 #[test]
937 fn key_offsets_point_at_the_message_not_a_mention_of_it() {
938 let src = "# greeting is the one below\ngreeting = Hello\nfarewell = Bye\n";
939 let offsets: std::collections::BTreeMap<String, usize> =
940 ftl_key_offsets(src).into_iter().collect();
941
942 let greeting = offsets["greeting"];
943 assert_eq!(&src[greeting..greeting + "greeting".len()], "greeting");
944 assert_eq!(
945 line_col(src, greeting),
946 (2, 1),
947 "the message, not the comment"
948 );
949 let farewell = offsets["farewell"];
950 assert_eq!(line_col(src, farewell), (3, 1));
951 }
952
953 #[test]
955 fn attributes_get_their_own_offset() {
956 let src = "open = Open\n .key = o\n";
957 let offsets: std::collections::BTreeMap<String, usize> =
958 ftl_key_offsets(src).into_iter().collect();
959 assert_eq!(line_col(src, offsets["open"]), (1, 1));
960 assert_eq!(
961 line_col(src, offsets["open.key"]),
962 (2, 6),
963 "on the attribute's own line"
964 );
965 }
966
967 #[test]
970 fn function_calls_carry_their_position() {
971 let src = "count = You have { NUMBER($n, style: \"decimal\") } left\nother = plain\n";
972 let calls = function_calls(src);
973 assert_eq!(calls.len(), 1, "{calls:?}");
974 assert_eq!(&src[calls[0].offset..calls[0].offset + 6], "NUMBER");
975 let (line, col) = line_col(src, calls[0].offset);
976 assert_eq!(line, 1);
977 assert_eq!(col, 20, "the column the call starts at");
978 }
979
980 #[test]
982 fn columns_count_characters_not_bytes() {
983 let src = "gruss = Grüße\nzweite = x\n";
984 let at = src.find("zweite").expect("key");
985 assert_eq!(line_col(src, at), (2, 1));
986 let inner = src.find("ße").expect("inner");
988 assert_eq!(line_col(src, inner).1, 12);
989 }
990}
991
992type Vars = std::collections::BTreeSet<String>;
993type Params = std::collections::BTreeMap<String, bool>;
995
996fn collect_pattern_vars(p: &fluent_syntax::ast::Pattern<&str>, out: &mut Params, numeric: bool) {
997 use fluent_syntax::ast::PatternElement;
998 for el in &p.elements {
999 if let PatternElement::Placeable { expression } = el {
1000 collect_expr_vars(expression, out, numeric);
1001 }
1002 }
1003}
1004
1005fn collect_expr_vars(e: &fluent_syntax::ast::Expression<&str>, out: &mut Params, numeric: bool) {
1006 use fluent_syntax::ast::Expression;
1007 match e {
1008 Expression::Inline(ie) => collect_inline_vars(ie, out, numeric),
1009 Expression::Select { selector, variants } => {
1010 collect_inline_vars(selector, out, is_number_select(variants));
1013 for v in variants {
1014 collect_pattern_vars(&v.value, out, false);
1015 }
1016 }
1017 }
1018}
1019
1020fn collect_inline_vars(
1021 ie: &fluent_syntax::ast::InlineExpression<&str>,
1022 out: &mut Params,
1023 numeric: bool,
1024) {
1025 use fluent_syntax::ast::InlineExpression as X;
1026 match ie {
1027 X::VariableReference { id } => {
1028 *out.entry(id.name.to_string()).or_insert(false) |= numeric;
1029 }
1030 X::Placeable { expression } => collect_expr_vars(expression, out, numeric),
1031 X::FunctionReference { id, arguments } => {
1032 let num = id.name.eq_ignore_ascii_case("NUMBER");
1037 for a in &arguments.positional {
1038 collect_inline_vars(a, out, num);
1039 }
1040 for n in &arguments.named {
1041 collect_inline_vars(&n.value, out, false);
1042 }
1043 }
1044 X::TermReference {
1045 arguments: Some(arguments),
1046 ..
1047 } => {
1048 for a in &arguments.positional {
1049 collect_inline_vars(a, out, false);
1050 }
1051 for n in &arguments.named {
1052 collect_inline_vars(&n.value, out, false);
1053 }
1054 }
1055 _ => {}
1056 }
1057}
1058
1059#[must_use]
1074pub fn offset_in(src: &str, part: &str) -> Option<usize> {
1075 let (base, at) = (src.as_ptr() as usize, part.as_ptr() as usize);
1076 (at >= base && at + part.len() <= base + src.len()).then_some(at - base)
1077}
1078
1079#[must_use]
1082pub fn line_col(src: &str, offset: usize) -> (usize, usize) {
1083 let upto = &src[..offset.min(src.len())];
1084 let line = upto.matches('\n').count() + 1;
1085 let col = upto.rsplit('\n').next().unwrap_or("").chars().count() + 1;
1086 (line, col)
1087}
1088
1089#[must_use]
1092pub fn ftl_key_offsets(src: &str) -> Vec<(String, usize)> {
1093 use fluent_syntax::ast::Entry;
1094 let res = match fluent_syntax::parser::parse(src) {
1095 Ok(r) => r,
1096 Err((r, _errs)) => r,
1097 };
1098 let mut out = Vec::new();
1099 for entry in &res.body {
1100 if let Entry::Message(m) = entry {
1101 let at = offset_in(src, m.id.name).unwrap_or(0);
1102 out.push((m.id.name.to_string(), at));
1103 for attr in &m.attributes {
1104 out.push((
1105 format!("{}.{}", m.id.name, attr.id.name),
1106 offset_in(src, attr.id.name).unwrap_or(at),
1107 ));
1108 }
1109 }
1110 }
1111 out
1112}
1113
1114#[derive(Debug, Clone, PartialEq)]
1115pub struct FtlCall {
1116 pub key: String,
1118 pub name: String,
1120 pub named: Vec<(String, String)>,
1123 pub offset: usize,
1126}
1127
1128#[must_use]
1131pub fn function_calls(src: &str) -> Vec<FtlCall> {
1132 use fluent_syntax::ast::Entry;
1133 let res = match fluent_syntax::parser::parse(src) {
1134 Ok(r) => r,
1135 Err((r, _errs)) => r,
1136 };
1137 let mut out = Vec::new();
1138 for entry in &res.body {
1139 if let Entry::Message(m) = entry
1140 && let Some(value) = &m.value
1141 {
1142 collect_pattern_calls(src, value, m.id.name, &mut out);
1143 }
1144 }
1145 out
1146}
1147
1148fn collect_pattern_calls(
1149 src: &str,
1150 p: &fluent_syntax::ast::Pattern<&str>,
1151 key: &str,
1152 out: &mut Vec<FtlCall>,
1153) {
1154 use fluent_syntax::ast::PatternElement;
1155 for el in &p.elements {
1156 if let PatternElement::Placeable { expression } = el {
1157 collect_expr_calls(src, expression, key, out);
1158 }
1159 }
1160}
1161
1162fn collect_expr_calls(
1163 src: &str,
1164 e: &fluent_syntax::ast::Expression<&str>,
1165 key: &str,
1166 out: &mut Vec<FtlCall>,
1167) {
1168 use fluent_syntax::ast::Expression;
1169 match e {
1170 Expression::Inline(ie) => collect_inline_calls(src, ie, key, out),
1171 Expression::Select { selector, variants } => {
1172 collect_inline_calls(src, selector, key, out);
1173 for v in variants {
1174 collect_pattern_calls(src, &v.value, key, out);
1175 }
1176 }
1177 }
1178}
1179
1180fn collect_inline_calls(
1181 src: &str,
1182 ie: &fluent_syntax::ast::InlineExpression<&str>,
1183 key: &str,
1184 out: &mut Vec<FtlCall>,
1185) {
1186 use fluent_syntax::ast::InlineExpression as X;
1187 match ie {
1188 X::FunctionReference { id, arguments } => {
1189 let named = arguments
1190 .named
1191 .iter()
1192 .filter_map(|n| {
1193 let value = match &n.value {
1194 X::StringLiteral { value } | X::NumberLiteral { value } => {
1195 value.to_string()
1196 }
1197 _ => return None,
1198 };
1199 Some((n.name.name.to_string(), value))
1200 })
1201 .collect();
1202 out.push(FtlCall {
1203 key: key.to_string(),
1204 name: id.name.to_string(),
1205 named,
1206 offset: offset_in(src, id.name).unwrap_or(0),
1207 });
1208 for a in &arguments.positional {
1209 collect_inline_calls(src, a, key, out);
1210 }
1211 }
1212 X::Placeable { expression } => collect_expr_calls(src, expression, key, out),
1213 _ => {}
1214 }
1215}
1216
1217fn is_number_select(variants: &[fluent_syntax::ast::Variant<&str>]) -> bool {
1221 use fluent_syntax::ast::VariantKey;
1222 const PLURAL: &[&str] = &["zero", "one", "two", "few", "many"];
1223 variants.iter().any(|v| match &v.key {
1224 VariantKey::NumberLiteral { .. } => true,
1225 VariantKey::Identifier { name } => PLURAL.contains(&name.to_ascii_lowercase().as_str()),
1226 })
1227}
1228
1229fn pattern_text(p: &fluent_syntax::ast::Pattern<&str>) -> String {
1233 use fluent_syntax::ast::PatternElement;
1234 let mut s = String::new();
1235 for el in &p.elements {
1236 match el {
1237 PatternElement::TextElement { value } => s.push_str(value),
1238 PatternElement::Placeable { expression } => s.push_str(&placeable_text(expression)),
1239 }
1240 }
1241 s.split_whitespace()
1242 .collect::<Vec<_>>()
1243 .join(" ")
1244 .replace('`', "'")
1245}
1246
1247fn placeable_text(e: &fluent_syntax::ast::Expression<&str>) -> String {
1248 use fluent_syntax::ast::{Expression, InlineExpression as X};
1249 match e {
1250 Expression::Inline(X::VariableReference { id }) => format!("{{ ${} }}", id.name),
1251 Expression::Inline(X::StringLiteral { value }) => format!("{{ \"{value}\" }}"),
1252 Expression::Select {
1253 selector: X::VariableReference { id },
1254 ..
1255 } => format!("{{ ${} -> … }}", id.name),
1256 _ => "{ … }".to_string(),
1257 }
1258}
1259
1260fn is_rust_ident(s: &str) -> bool {
1263 let mut chars = s.chars();
1264 let Some(first) = chars.next() else {
1265 return false;
1266 };
1267 (first.is_ascii_alphabetic() || first == '_')
1268 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
1269 && s != "_"
1270}
1271
1272#[must_use]
1276pub fn render(plan: &ResourcePlan) -> String {
1277 render_app(plan, None, WindowGeometry::default())
1278}
1279
1280#[must_use]
1283pub fn render_app(plan: &ResourcePlan, app_title: Option<&str>, window: WindowGeometry) -> String {
1284 let mut s = String::new();
1285 s.push_str("// @generated by day-build — do not edit.\n");
1286 s.push_str("// Regenerated on every build from resource/{images,assets,fonts,locales}.\n\n");
1287 render_bucket(&mut s, "images", "ImageName", &plan.images);
1291 render_bucket(&mut s, "vectors", "VectorName", &plan.vectors);
1292 render_assets(&mut s, &plan.assets);
1293 render_bucket(&mut s, "fonts", "FontFamily", &plan.fonts);
1294 render_strings(&mut s, &plan.strings);
1295 render_locales(&mut s, &plan.locales);
1296 render_window_options(&mut s, &plan.strings, app_title, window);
1297 s
1298}
1299
1300fn render_locales(s: &mut String, locales: &[LocaleEntry]) {
1310 render_locales_for(s, locales, None);
1311}
1312
1313fn render_locales_for(s: &mut String, locales: &[LocaleEntry], scope: Option<&str>) {
1314 s.push_str("#[allow(dead_code)]\npub mod locales {\n");
1315 let _ = writeln!(
1316 s,
1317 " /// The fallback locale — the one whose strings show when the running locale has no\n\
1318 \x20 /// translation for a key.\n pub const DEFAULT: &str = {:?};\n",
1319 default_locale(locales)
1320 );
1321 s.push_str(
1322 " /// Every locale under `resource/locales/`, embedded at build time: one\n\
1323 \x20 /// `(tag, fluent-source)` pair per directory.\n\
1324 \x20 pub const CATALOG: &[(&str, &str)] = &[\n",
1325 );
1326 for l in locales {
1327 let manifest_dir = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from);
1328 let sources: Vec<String> = l
1329 .sources
1330 .iter()
1331 .map(|p| include_source(p, manifest_dir.as_deref()))
1332 .collect();
1333 let src = if sources.is_empty() {
1335 "\"\"".to_string()
1336 } else if sources.len() == 1 {
1337 sources.into_iter().next().unwrap_or_default()
1338 } else {
1339 format!("concat!({}, \"\\n\")", sources.join(", \"\\n\", "))
1340 };
1341 let _ = writeln!(s, " ({:?}, {src}),", l.locale);
1342 }
1343 s.push_str(" ];\n\n");
1344 s.push_str(
1345 " /// Every bundled locale as `(tag, display name)`, for language pickers. The name\n\
1346 \x20 /// is the catalog's own `language_name` message, else the language's own\n\
1347 \x20 /// name for itself, else the tag (docs/localization.md).\n\
1348 \x20 pub const ALL: &[(&str, &str)] = &[\n",
1349 );
1350 for l in locales {
1351 let _ = writeln!(
1352 s,
1353 " ({:?}, {:?}),",
1354 l.locale,
1355 language_name(l)
1356 .or_else(|| endonym(&l.locale).map(str::to_owned))
1357 .unwrap_or_else(|| l.locale.clone())
1358 );
1359 }
1360 s.push_str(" ];\n\n");
1361 if let Some(name) = scope {
1362 let _ = writeln!(
1363 s,
1364 " /// Private namespace; ordinary app installation never replaces this catalog.\n\
1365 pub static SCOPE: day_localization_ui::Catalog = day_localization_ui::Catalog {{ name: {name:?}, default: DEFAULT, locales: CATALOG }};\n\
1366 /// Register for qualified scripting lookups. Accessors also do this automatically.\n\
1367 pub fn register() {{ day_localization_ui::register_catalog(&SCOPE); }}"
1368 );
1369 } else {
1370 s.push_str(
1371 " /// Register [`CATALOG`] under [`DEFAULT`] — call once, before the first localized\n\
1372 \x20 /// string is read (the top of the app's `root()`). For a different fallback:\n\
1373 \x20 /// `day::install_locales(\"fr\", res::locales::CATALOG)`.\n\
1374 \x20 pub fn install() {\n day::install_locales(DEFAULT, CATALOG);\n }\n",
1375 );
1376 }
1377 s.push_str("}\n\n");
1378}
1379
1380fn endonym(tag: &str) -> Option<&'static str> {
1387 const NAMES: &[(&str, &str)] = &[
1388 ("ar", "العربية"),
1389 ("bg", "Български"),
1390 ("ca", "Català"),
1391 ("cs", "Čeština"),
1392 ("da", "Dansk"),
1393 ("de", "Deutsch"),
1394 ("el", "Ελληνικά"),
1395 ("en", "English"),
1396 ("en-GB", "English (UK)"),
1397 ("es", "Español"),
1398 ("es-MX", "Español (México)"),
1399 ("et", "Eesti"),
1400 ("fa", "فارسی"),
1401 ("fi", "Suomi"),
1402 ("fil", "Filipino"),
1403 ("fr", "Français"),
1404 ("fr-CA", "Français (Canada)"),
1405 ("he", "עברית"),
1406 ("hi", "हिन्दी"),
1407 ("hr", "Hrvatski"),
1408 ("hu", "Magyar"),
1409 ("id", "Bahasa Indonesia"),
1410 ("it", "Italiano"),
1411 ("ja", "日本語"),
1412 ("ko", "한국어"),
1413 ("lt", "Lietuvių"),
1414 ("lv", "Latviešu"),
1415 ("ms", "Bahasa Melayu"),
1416 ("nb", "Norsk bokmål"),
1417 ("nl", "Nederlands"),
1418 ("no", "Norsk"),
1419 ("pl", "Polski"),
1420 ("pt", "Português"),
1421 ("pt-BR", "Português (Brasil)"),
1422 ("pt-PT", "Português (Portugal)"),
1423 ("ro", "Română"),
1424 ("ru", "Русский"),
1425 ("sk", "Slovenčina"),
1426 ("sl", "Slovenščina"),
1427 ("sr", "Српски"),
1428 ("sv", "Svenska"),
1429 ("th", "ไทย"),
1430 ("tr", "Türkçe"),
1431 ("uk", "Українська"),
1432 ("vi", "Tiếng Việt"),
1433 ("zh", "中文"),
1434 ("zh-CN", "简体中文"),
1435 ("zh-Hans", "简体中文"),
1436 ("zh-Hant", "繁體中文"),
1437 ("zh-HK", "繁體中文(香港)"),
1438 ("zh-TW", "繁體中文"),
1439 ];
1440 let find = |t: &str| {
1441 NAMES
1442 .iter()
1443 .find(|(k, _)| k.eq_ignore_ascii_case(t))
1444 .map(|(_, v)| *v)
1445 };
1446 let mut parts = tag.split(['-', '_']);
1447 let lang = parts.next()?;
1448 let script = parts.next().filter(|p| p.len() == 4);
1449 find(tag)
1450 .or_else(|| script.and_then(|s| find(&format!("{lang}-{s}"))))
1451 .or_else(|| find(lang))
1452}
1453
1454fn language_name(l: &LocaleEntry) -> Option<String> {
1455 for path in &l.sources {
1456 let Ok(text) = std::fs::read_to_string(path) else {
1457 continue;
1458 };
1459 for line in text.lines() {
1460 if let Some(value) = line.strip_prefix("language_name") {
1461 let value = value.trim_start();
1462 if let Some(value) = value.strip_prefix('=') {
1463 let value = value.trim();
1464 if !value.is_empty() {
1465 return Some(value.to_string());
1466 }
1467 }
1468 }
1469 }
1470 }
1471 None
1472}
1473
1474fn render_strings(s: &mut String, entries: &[StrEntry]) {
1478 render_strings_for(s, entries, "day", "day::tr(");
1479}
1480
1481fn render_strings_for(s: &mut String, entries: &[StrEntry], api: &str, constructor: &str) {
1482 s.push_str("#[allow(dead_code, unused_imports, non_snake_case, clippy::too_many_arguments)]\n");
1483 s.push_str("pub mod str {\n");
1484 let _ = writeln!(s, " pub use ::{api}::res::str::*;");
1488 for e in entries {
1489 let generics: Vec<String> = (0..e.params.len()).map(|i| format!("M{i}")).collect();
1493 let bound = |p: &StrParam, i: usize| {
1494 let ty = if p.numeric {
1495 "IntoNumberFArg"
1496 } else {
1497 "IntoFArg"
1498 };
1499 format!("impl {api}::{ty}<M{i}>")
1500 };
1501 let doc = if e.doc.is_empty() {
1503 format!("`{}`", e.key)
1504 } else {
1505 format!("`{}` — `{}`", e.key, e.doc)
1506 };
1507 let fn_name = ident_token(&res_str_ident(&e.key));
1508 if e.params.len() >= 2 {
1509 let struct_name = pascal_case(&res_str_ident(&e.key));
1513 let type_params: Vec<String> = (0..e.params.len()).map(|i| format!("A{i}")).collect();
1514 let fields: Vec<String> = e
1515 .params
1516 .iter()
1517 .enumerate()
1518 .map(|(i, p)| format!("pub {}: A{i}", ident_token(&sanitize_ident(&p.name))))
1519 .collect();
1520 let _ = writeln!(
1521 s,
1522 " /// The arguments of `{}`: `{}`.\n pub struct {struct_name}<{}> {{ {} }}",
1523 e.key,
1524 e.params
1525 .iter()
1526 .map(|p| p.name.as_str())
1527 .collect::<Vec<_>>()
1528 .join("`, `"),
1529 type_params.join(", "),
1530 fields.join(", "),
1531 );
1532 let bounds: Vec<String> = e
1533 .params
1534 .iter()
1535 .enumerate()
1536 .map(|(i, p)| {
1537 let ty = if p.numeric {
1538 "IntoNumberFArg"
1539 } else {
1540 "IntoFArg"
1541 };
1542 format!("A{i}: {api}::{ty}<M{i}>")
1543 })
1544 .collect();
1545 let mut body = format!("{constructor}{:?})", e.key);
1546 for p in &e.params {
1547 let _ = write!(
1548 body,
1549 ".arg({:?}, args.{})",
1550 p.name,
1551 ident_token(&sanitize_ident(&p.name))
1552 );
1553 }
1554 let _ = writeln!(
1555 s,
1556 " /// {doc}\n pub fn {fn_name}<{}, {}>(args: {struct_name}<{}>) -> {api}::LocalizedText {{ {body} }}",
1557 generics.join(", "),
1558 bounds.join(", "),
1559 type_params.join(", "),
1560 );
1561 continue;
1562 }
1563 let sig_params: Vec<String> = e
1564 .params
1565 .iter()
1566 .enumerate()
1567 .map(|(i, p)| format!("{}: {}", ident_token(&sanitize_ident(&p.name)), bound(p, i)))
1568 .collect();
1569 let generic_list = if generics.is_empty() {
1570 String::new()
1571 } else {
1572 format!("<{}>", generics.join(", "))
1573 };
1574 let mut body = format!("{constructor}{:?})", e.key);
1575 for p in &e.params {
1576 let _ = write!(
1577 body,
1578 ".arg({:?}, {})",
1579 p.name,
1580 ident_token(&sanitize_ident(&p.name))
1581 );
1582 }
1583 let _ = writeln!(
1584 s,
1585 " /// {doc}\n pub fn {fn_name}{generic_list}({}) -> {api}::LocalizedText {{ {body} }}",
1586 sig_params.join(", "),
1587 );
1588 }
1589 s.push_str("}\n\n");
1590}
1591
1592#[must_use]
1594pub fn pascal_case(ident: &str) -> String {
1595 let mut out = String::with_capacity(ident.len());
1596 let mut upper = true;
1597 for c in ident.chars() {
1598 if c == '_' {
1599 upper = true;
1600 } else if upper {
1601 out.extend(c.to_uppercase());
1602 upper = false;
1603 } else {
1604 out.push(c);
1605 }
1606 }
1607 out
1608}
1609
1610fn render_window_options(
1615 s: &mut String,
1616 strings: &[StrEntry],
1617 app_title: Option<&str>,
1618 window: WindowGeometry,
1619) {
1620 let has_title = strings
1621 .iter()
1622 .any(|e| e.key == "app_title" && e.params.is_empty());
1623 s.push_str(
1624 "/// The options every window of this app starts from (docs/windows.md): the locale\n\
1625 /// catalog, the localized title, the Day.toml `[window]` size, and the version from\n\
1626 /// Cargo.toml. Chain the rest; `.title(..)` after it names a window of its own.\n\
1627 #[allow(dead_code)]\n\
1628 pub fn window_options() -> day::WindowOptions {\n\
1629 \x20 day::WindowOptions::default()\n\
1630 \x20 .locales(locales::DEFAULT, locales::CATALOG)\n",
1631 );
1632 if has_title {
1633 s.push_str(" .title_fn(|| str::app_title().format())\n");
1634 } else if let Some(title) = app_title {
1635 let _ = writeln!(s, " .title({title:?})");
1636 }
1637 if let Some((w, h)) = window.size {
1638 let _ = writeln!(s, " .size({w:?}, {h:?})");
1639 }
1640 if let Some((w, h)) = window.min_size {
1641 let _ = writeln!(s, " .min_size({w:?}, {h:?})");
1642 }
1643 s.push_str(" .version(env!(\"CARGO_PKG_VERSION\"))\n}\n\n");
1644}
1645
1646fn render_assets(s: &mut String, root: &AssetNode) {
1651 s.push_str("#[allow(non_upper_case_globals, dead_code, unused_imports)]\n");
1652 render_asset_node(s, "assets", root, 0);
1653 s.push('\n');
1654}
1655
1656fn render_asset_node(s: &mut String, module: &str, node: &AssetNode, depth: usize) {
1657 let pad = " ".repeat(depth);
1658 let _ = writeln!(s, "{pad}pub mod {} {{", ident_token(module));
1659 let _ = writeln!(s, "{pad} use day::{{AssetDir, AssetName}};");
1660 for e in &node.files {
1661 let _ = writeln!(
1662 s,
1663 "{pad} /// `{}`\n{pad} pub const {}: AssetName = AssetName::from_static({:?});",
1664 e.source,
1665 ident_token(&e.symbol),
1666 e.value,
1667 );
1668 }
1669 for (sym, sub) in &node.dirs {
1670 let _ = writeln!(
1671 s,
1672 "{pad} /// `resource/assets/{}` (directory)\n{pad} pub const {}: AssetDir = AssetDir::from_static({:?});",
1673 sub.path,
1674 ident_token(sym),
1675 sub.path,
1676 );
1677 render_asset_node(s, sym, sub, depth + 1);
1678 }
1679 let _ = writeln!(s, "{pad}}}");
1680}
1681
1682fn render_bucket(s: &mut String, module: &str, ty: &str, entries: &[Entry]) {
1683 s.push_str("#[allow(non_upper_case_globals, dead_code, unused_imports)]\n");
1684 let _ = writeln!(s, "pub mod {module} {{\n use day::{ty};");
1685 for e in entries {
1686 let _ = writeln!(
1687 s,
1688 " /// `{}`\n pub const {}: {ty} = {ty}::from_static({:?});",
1689 e.source,
1690 ident_token(&e.symbol),
1691 e.value,
1692 );
1693 }
1694 s.push_str("}\n\n");
1695}
1696
1697fn ident_token(sym: &str) -> String {
1699 const KEYWORDS: &[&str] = &[
1700 "as", "break", "const", "continue", "dyn", "else", "enum", "extern", "false", "fn", "for",
1701 "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
1702 "static", "struct", "trait", "true", "type", "union", "unsafe", "use", "where", "while",
1703 "async", "await", "try", "gen", "abstract", "become", "box", "do", "final", "macro",
1704 "override", "priv", "typeof", "unsized", "virtual", "yield",
1705 ];
1706 if KEYWORDS.contains(&sym) {
1707 format!("r#{sym}")
1708 } else {
1709 sym.to_string()
1710 }
1711}
1712
1713fn parse_scale(stem: &str) -> (String, u32) {
1715 if let Some((base, tail)) = stem.rsplit_once('@')
1716 && let Some(digits) = tail.strip_suffix('x')
1717 && let Ok(scale) = digits.parse::<u32>()
1718 && scale >= 1
1719 {
1720 return (base.to_string(), scale);
1721 }
1722 (stem.to_string(), 1)
1723}
1724
1725#[must_use]
1729pub fn sanitize_ident(name: &str) -> String {
1730 let mut s: String = name
1731 .chars()
1732 .map(|c| {
1733 let c = c.to_ascii_lowercase();
1734 if c.is_ascii_alphanumeric() || c == '_' {
1735 c
1736 } else {
1737 '_'
1738 }
1739 })
1740 .collect();
1741 if !s.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) {
1742 s.insert(0, 'r');
1743 }
1744 s
1745}
1746
1747fn include_source(path: &Path, manifest_dir: Option<&Path>) -> String {
1758 if let Some(rel) = manifest_dir.and_then(|root| path.strip_prefix(root).ok()) {
1759 let rel: Vec<String> = rel
1760 .components()
1761 .map(|c| c.as_os_str().to_string_lossy().into_owned())
1762 .collect();
1763 return format!(
1764 "include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), {:?}))",
1765 format!("/{}", rel.join("/"))
1766 );
1767 }
1768 format!("include_str!({:?})", path.display().to_string())
1769}
1770
1771fn display(path: &Path) -> String {
1773 let comps: Vec<_> = path.components().collect();
1776 let n = comps.len();
1777 let start = n.saturating_sub(3);
1778 comps[start..]
1779 .iter()
1780 .map(|c| c.as_os_str().to_string_lossy())
1781 .collect::<Vec<_>>()
1782 .join("/")
1783}
1784
1785#[cfg(test)]
1786mod tests {
1787 use super::*;
1788
1789 fn tmp(label: &str) -> PathBuf {
1790 let d = std::env::temp_dir().join(format!("day-build-{}-{label}", std::process::id()));
1792 let _ = std::fs::remove_dir_all(&d);
1793 d
1794 }
1795
1796 fn touch(dir: &Path, name: &str, bytes: &[u8]) {
1797 std::fs::create_dir_all(dir).unwrap();
1798 std::fs::write(dir.join(name), bytes).unwrap();
1799 }
1800
1801 #[test]
1802 fn sanitize_matches_strictest_rules() {
1803 assert_eq!(sanitize_ident("nav_system"), "nav_system");
1804 assert_eq!(sanitize_ident("Nav-System"), "nav_system");
1805 assert_eq!(sanitize_ident("123"), "r123");
1806 assert_eq!(sanitize_ident("numbers.bin"), "numbers_bin");
1807 }
1808
1809 #[test]
1810 fn images_dedup_scale_variants_and_key_on_stem() {
1811 let root = tmp("images-dedup");
1812 let img = root.join("resource/images");
1813 touch(&img, "nav_system.png", b"x");
1814 touch(&img, "day_logo.png", b"x");
1815 touch(&img, "day_logo@2x.png", b"x"); let plan = plan_resources(&root).unwrap();
1817 let syms: Vec<_> = plan.images.iter().map(|e| e.symbol.as_str()).collect();
1818 assert_eq!(syms, vec!["day_logo", "nav_system"]);
1819 assert_eq!(plan.images[0].value, "day_logo");
1820 std::fs::remove_dir_all(&root).ok();
1821 }
1822
1823 #[test]
1824 fn non_portable_image_stem_is_rejected() {
1825 let root = tmp("non-portable");
1826 touch(&root.join("resource/images"), "Nav-System.png", b"x");
1827 let err = plan_resources(&root).unwrap_err();
1828 assert!(err.contains("portable"), "{err}");
1829 assert!(err.contains("nav_system"), "{err}"); std::fs::remove_dir_all(&root).ok();
1831 }
1832
1833 #[test]
1834 fn same_stem_same_scale_collides() {
1835 let root = tmp("collide");
1836 let img = root.join("resource/images");
1837 touch(&img, "logo.png", b"x");
1838 touch(&img, "logo.jpg", b"x"); let err = plan_resources(&root).unwrap_err();
1840 assert!(err.contains("same scale"), "{err}");
1841 std::fs::remove_dir_all(&root).ok();
1842 }
1843
1844 #[test]
1845 fn asset_symbol_sanitized_value_verbatim() {
1846 let root = tmp("assets");
1847 touch(&root.join("resource/assets"), "numbers.bin", b"x");
1848 let plan = plan_resources(&root).unwrap();
1849 assert_eq!(plan.assets.files[0].symbol, "numbers_bin");
1850 assert_eq!(plan.assets.files[0].value, "numbers.bin");
1851 std::fs::remove_dir_all(&root).ok();
1852 }
1853
1854 #[test]
1855 fn asset_tree_nests_modules_and_dir_consts() {
1856 let root = tmp("assets-tree");
1857 touch(&root.join("resource/assets"), "top.bin", b"x");
1858 touch(
1859 &root.join("resource/assets/web/minisite"),
1860 "index.html",
1861 b"x",
1862 );
1863 touch(
1864 &root.join("resource/assets/web/minisite/css"),
1865 "style.css",
1866 b"x",
1867 );
1868 let plan = plan_resources(&root).unwrap();
1869 let web = &plan.assets.dirs[0];
1871 assert_eq!(web.0, "web");
1872 let mini = &web.1.dirs[0];
1873 assert_eq!(mini.1.path, "web/minisite");
1874 assert_eq!(mini.1.files[0].value, "web/minisite/index.html");
1875 assert_eq!(
1876 mini.1.dirs[0].1.files[0].value,
1877 "web/minisite/css/style.css"
1878 );
1879 let code = render(&plan);
1880 assert!(
1881 code.contains("pub const top_bin: AssetName = AssetName::from_static(\"top.bin\");")
1882 );
1883 assert!(code.contains("pub const web: AssetDir = AssetDir::from_static(\"web\");"));
1884 assert!(code.contains("pub mod web {"));
1885 assert!(
1886 code.contains(
1887 "pub const minisite: AssetDir = AssetDir::from_static(\"web/minisite\");"
1888 )
1889 );
1890 assert!(code.contains(
1891 "pub const index_html: AssetName = AssetName::from_static(\"web/minisite/index.html\");"
1892 ));
1893 assert!(code.contains(
1894 "pub const style_css: AssetName = AssetName::from_static(\"web/minisite/css/style.css\");"
1895 ));
1896 std::fs::remove_dir_all(&root).ok();
1897 }
1898
1899 #[test]
1900 fn asset_file_and_dir_symbol_collision_errors() {
1901 let root = tmp("assets-collide");
1905 touch(&root.join("resource/assets"), "site.old", b"x");
1906 touch(&root.join("resource/assets/site-old"), "x.bin", b"x");
1907 let err = plan_resources(&root).unwrap_err();
1908 assert!(err.contains("site_old"), "{err}");
1909 std::fs::remove_dir_all(&root).ok();
1910 }
1911
1912 #[test]
1913 fn render_shape_is_typed_and_lowercase() {
1914 let plan = ResourcePlan {
1915 images: vec![Entry {
1916 symbol: "nav_system".into(),
1917 value: "nav_system".into(),
1918 source: "resource/images/nav_system.png".into(),
1919 }],
1920 ..Default::default()
1921 };
1922 let code = render(&plan);
1923 assert!(code.contains("#[allow(non_upper_case_globals, dead_code, unused_imports)]"));
1924 assert!(code.contains("pub mod images {"));
1925 assert!(code.contains("use day::ImageName;"));
1926 assert!(
1927 code.contains(
1928 "pub const nav_system: ImageName = ImageName::from_static(\"nav_system\");"
1929 )
1930 );
1931 }
1932
1933 #[test]
1934 fn keyword_symbol_becomes_raw_ident() {
1935 let plan = ResourcePlan {
1936 images: vec![Entry {
1937 symbol: "type".into(),
1938 value: "type".into(),
1939 source: "resource/images/type.png".into(),
1940 }],
1941 ..Default::default()
1942 };
1943 assert!(render(&plan).contains("pub const r#type: ImageName"));
1944 }
1945
1946 #[test]
1947 fn missing_dirs_yield_empty_plan() {
1948 let root = tmp("missing-dirs");
1949 std::fs::create_dir_all(&root).unwrap();
1950 let plan = plan_resources(&root).unwrap();
1951 assert!(plan.images.is_empty() && plan.fonts.is_empty());
1952 assert!(plan.assets.files.is_empty() && plan.assets.dirs.is_empty());
1953 assert_eq!(plan.strings, [] as [StrEntry; 0]);
1954 std::fs::remove_dir_all(&root).ok();
1955 }
1956
1957 fn ftl(root: &Path, locale: &str, body: &str) {
1958 let dir = root.join("resource/locales").join(locale);
1959 std::fs::create_dir_all(&dir).unwrap();
1960 std::fs::write(dir.join("app.ftl"), body).unwrap();
1961 }
1962
1963 fn entry<'a>(plan: &'a ResourcePlan, key: &str) -> &'a StrEntry {
1964 plan.strings
1965 .iter()
1966 .find(|e| e.key == key)
1967 .expect("key present")
1968 }
1969 fn names(e: &StrEntry) -> Vec<&str> {
1970 e.params.iter().map(|p| p.name.as_str()).collect()
1971 }
1972
1973 #[test]
1974 fn extracts_keys_params_numeric_and_doc() {
1975 let root = tmp("str-extract");
1976 ftl(
1980 &root,
1981 "en",
1982 "nav_home = Home\n\
1983 greeting = Hello, { $name }!\n\
1984 counter_value = { $count ->\n [one] { $count } click\n *[other] { $count } clicks\n}\n",
1985 );
1986 let plan = plan_resources(&root).unwrap();
1987 assert_eq!(names(entry(&plan, "nav_home")), [] as [&str; 0]);
1988 assert_eq!(names(entry(&plan, "greeting")), vec!["name"]);
1989 assert_eq!(entry(&plan, "greeting").doc, "Hello, { $name }!"); assert!(!entry(&plan, "greeting").params[0].numeric);
1991 assert_eq!(names(entry(&plan, "counter_value")), vec!["count"]);
1993 assert!(entry(&plan, "counter_value").params[0].numeric);
1994 std::fs::remove_dir_all(&root).ok();
1995 }
1996
1997 #[test]
1998 fn string_select_selector_is_not_numeric() {
1999 let root = tmp("str-gender");
2000 ftl(
2002 &root,
2003 "en",
2004 "hi = { $gender ->\n [male] Mr\n [female] Ms\n *[other] Mx\n} { $name }\n",
2005 );
2006 let plan = plan_resources(&root).unwrap();
2007 let g = entry(&plan, "hi");
2008 assert!(
2009 !g.params
2010 .iter()
2011 .find(|p| p.name == "gender")
2012 .unwrap()
2013 .numeric
2014 );
2015 assert!(!g.params.iter().find(|p| p.name == "name").unwrap().numeric);
2016 std::fs::remove_dir_all(&root).ok();
2017 }
2018
2019 #[test]
2020 fn numeric_is_ored_across_locales() {
2021 let root = tmp("str-numeric-or");
2022 ftl(
2025 &root,
2026 "en",
2027 "n = { $count ->\n [one] one\n *[other] many\n}\n",
2028 );
2029 ftl(&root, "zh", "n = { $count } times\n");
2030 let plan = plan_resources(&root).unwrap();
2031 assert!(entry(&plan, "n").params[0].numeric);
2032 std::fs::remove_dir_all(&root).ok();
2033 }
2034
2035 #[test]
2036 fn message_keys_lists_message_ids_only() {
2037 let keys = message_keys("a = x\n# comment\n-term = y\nb = { $v }\n");
2039 assert_eq!(keys, vec!["a".to_string(), "b".to_string()]);
2040 }
2041
2042 #[test]
2043 fn kebab_key_is_rejected() {
2044 let root = tmp("str-kebab");
2045 ftl(&root, "en", "nav-home = Home\n");
2046 let err = plan_resources(&root).unwrap_err();
2047 assert!(err.contains("not a valid Rust identifier"), "{err}");
2048 assert!(err.contains("nav_home"), "{err}"); std::fs::remove_dir_all(&root).ok();
2050 }
2051
2052 #[test]
2053 fn cross_locale_param_disagreement_is_rejected() {
2054 let root = tmp("str-params");
2055 ftl(&root, "en", "greeting = Hello, { $name }!\n");
2056 ftl(&root, "fr", "greeting = Bonjour, { $nom }!\n");
2057 let err = plan_resources(&root).unwrap_err();
2058 assert!(err.contains("different parameters"), "{err}");
2059 std::fs::remove_dir_all(&root).ok();
2060 }
2061
2062 #[test]
2063 fn renders_param_typed_functions() {
2064 let p = |name: &str, numeric: bool| StrParam {
2065 name: name.into(),
2066 numeric,
2067 };
2068 let plan = ResourcePlan {
2069 strings: vec![
2070 StrEntry {
2071 key: "hello_world".into(),
2072 params: vec![],
2073 doc: "Hello!".into(),
2074 },
2075 StrEntry {
2076 key: "counter_value".into(),
2077 params: vec![p("count", true)], doc: "{ $count -> … }".into(),
2079 },
2080 StrEntry {
2081 key: "deviceinfo_system".into(),
2082 params: vec![p("name", false), p("version", false)],
2083 doc: String::new(),
2084 },
2085 ],
2086 ..Default::default()
2087 };
2088 let code = render(&plan);
2089 assert!(code.contains("pub mod str {"));
2090 assert!(code.contains("pub use ::day::res::str::*;"));
2092 assert!(code.contains("/// `hello_world` — `Hello!`")); assert!(
2094 code.contains(
2095 "pub fn hello_world() -> day::LocalizedText { day::tr(\"hello_world\") }"
2096 )
2097 );
2098 assert!(code.contains(
2100 "pub fn counter_value<M0>(count: impl day::IntoNumberFArg<M0>) -> day::LocalizedText { day::tr(\"counter_value\").arg(\"count\", count) }"
2101 ));
2102 assert!(
2105 code.contains("pub struct DeviceinfoSystem<A0, A1> { pub name: A0, pub version: A1 }")
2106 );
2107 assert!(code.contains(
2108 "pub fn deviceinfo_system<M0, M1, A0: day::IntoFArg<M0>, A1: day::IntoFArg<M1>>(args: DeviceinfoSystem<A0, A1>) -> day::LocalizedText { day::tr(\"deviceinfo_system\").arg(\"name\", args.name).arg(\"version\", args.version) }"
2109 ));
2110 assert!(code.contains("pub fn window_options() -> day::WindowOptions {"));
2113 assert!(code.contains(".version(env!(\"CARGO_PKG_VERSION\"))"));
2114 }
2115
2116 #[test]
2119 fn message_attributes_generate_dotted_tr_accessors() {
2120 let root = tmp("attr-accessors");
2121 ftl(&root, "en", "menu_group = Group\n .key = g\n");
2122 ftl(&root, "fr", "menu_group = Grouper\n");
2125 let entries = plan_strings(&root.join("resource/locales")).expect("plan");
2126 let plan = ResourcePlan {
2127 strings: entries,
2128 ..Default::default()
2129 };
2130 let code = render(&plan);
2131 assert!(
2132 code.contains("pub fn menu_group() -> day::LocalizedText { day::tr(\"menu_group\") }")
2133 );
2134 assert!(
2135 code.contains(
2136 "pub fn menu_group_key() -> day::LocalizedText { day::tr(\"menu_group.key\") }"
2137 ),
2138 "{code}"
2139 );
2140 }
2141
2142 #[test]
2143 fn an_attribute_colliding_with_a_message_fn_name_is_a_build_error() {
2144 let root = tmp("attr-collision");
2145 ftl(
2146 &root,
2147 "en",
2148 "menu_group = Group\n .key = g\nmenu_group_key = Shadow\n",
2149 );
2150 let err = plan_strings(&root.join("resource/locales")).expect_err("must collide");
2151 assert!(err.contains("menu_group_key"), "{err}");
2152 }
2153
2154 #[test]
2157 fn locales_are_discovered_and_sorted() {
2158 let root = tmp("locales-discover");
2159 ftl(&root, "en", "hello = Hello");
2160 ftl(&root, "fr", "hello = Bonjour");
2161 ftl(&root, "zh-CN", "hello = 你好");
2162 let plan = plan_resources(&root).unwrap();
2163 let tags: Vec<_> = plan.locales.iter().map(|l| l.locale.as_str()).collect();
2164 assert_eq!(tags, vec!["en", "fr", "zh-CN"]); assert!(plan.locales.iter().all(|l| l.sources.len() == 1));
2166 std::fs::remove_dir_all(&root).ok();
2167 }
2168
2169 #[test]
2170 fn locale_catalog_renders_embedded_sources() {
2171 let root = tmp("locales-render");
2172 ftl(&root, "en", "hello = Hello");
2173 ftl(&root, "fr", "hello = Bonjour");
2174 let plan = plan_resources(&root).unwrap();
2175 let code = render(&plan);
2176 assert!(code.contains("pub mod locales {"));
2177 assert!(code.contains("pub const DEFAULT: &str = \"en\";"));
2178 assert!(code.contains("pub const CATALOG: &[(&str, &str)] = &["));
2179 let en = &plan
2185 .locales
2186 .iter()
2187 .find(|l| l.locale == "en")
2188 .unwrap()
2189 .sources[0];
2190 assert!(
2191 en.is_absolute() && en.ends_with("en/app.ftl"),
2192 "{}",
2193 en.display()
2194 );
2195 assert!(
2196 code.contains(&format!(
2197 "(\"en\", include_str!({:?}))",
2198 en.display().to_string()
2199 )),
2200 "{code}"
2201 );
2202 assert!(code.contains("day::install_locales(DEFAULT, CATALOG);"));
2203 std::fs::remove_dir_all(&root).ok();
2204 }
2205
2206 #[test]
2207 fn sources_inside_the_crate_are_named_from_the_manifest_dir() {
2208 let root = Path::new("/work/My App");
2209 let inside = root
2210 .join("resource")
2211 .join("locales")
2212 .join("fr")
2213 .join("app.ftl");
2214 assert_eq!(
2215 include_source(&inside, Some(root)),
2216 "include_str!(concat!(env!(\"CARGO_MANIFEST_DIR\"), \"/resource/locales/fr/app.ftl\"))"
2217 );
2218 let elsewhere = Path::new("/tmp/rebuild/src/My App");
2221 assert_eq!(
2222 include_source(
2223 &elsewhere.join("resource/locales/fr/app.ftl"),
2224 Some(elsewhere)
2225 ),
2226 include_source(&inside, Some(root))
2227 );
2228 let outside = Path::new("/elsewhere/resource/locales/fr/app.ftl");
2230 assert_eq!(
2231 include_source(outside, Some(root)),
2232 format!("include_str!({:?})", outside.display().to_string())
2233 );
2234 }
2235
2236 #[test]
2237 fn several_ftl_files_in_one_locale_concatenate() {
2238 let root = tmp("locales-multifile");
2239 ftl(&root, "en", "hello = Hello"); let dir = root.join("resource/locales/en");
2241 std::fs::write(dir.join("errors.ftl"), "oops = Oops").unwrap();
2242 let plan = plan_resources(&root).unwrap();
2243 assert_eq!(plan.locales.len(), 1, "one bundle per locale, not per file");
2244 assert_eq!(plan.locales[0].sources.len(), 2);
2245 let keys: Vec<_> = plan.strings.iter().map(|e| e.key.as_str()).collect();
2248 assert_eq!(keys, vec!["hello", "oops"]);
2249 let code = render(&plan);
2250 assert_eq!(code.matches("(\"en\", concat!(").count(), 1);
2254 assert!(code.contains("concat!(include_str!("), "{code}");
2255 std::fs::remove_dir_all(&root).ok();
2256 }
2257
2258 #[test]
2259 fn default_locale_prefers_en_then_first() {
2260 let root = tmp("locales-default-en");
2261 ftl(&root, "fr", "hello = Bonjour");
2262 ftl(&root, "en", "hello = Hello");
2263 assert_eq!(
2264 default_locale(&plan_resources(&root).unwrap().locales),
2265 "en"
2266 );
2267 std::fs::remove_dir_all(&root).ok();
2268
2269 let root = tmp("locales-default-noen");
2271 ftl(&root, "fr", "hello = Bonjour");
2272 ftl(&root, "ar", "hello = مرحبا");
2273 assert_eq!(
2274 default_locale(&plan_resources(&root).unwrap().locales),
2275 "ar"
2276 );
2277 std::fs::remove_dir_all(&root).ok();
2278 }
2279
2280 #[test]
2281 fn no_locales_yields_an_empty_catalog() {
2282 let root = tmp("locales-none");
2285 touch(&root.join("resource/images"), "logo.png", b"x");
2286 let plan = plan_resources(&root).unwrap();
2287 assert_eq!(plan.locales, [] as [LocaleEntry; 0]);
2288 let code = render(&plan);
2289 assert!(code.contains("pub const DEFAULT: &str = \"en\";"));
2290 assert!(code.contains("pub const CATALOG: &[(&str, &str)] = &[\n ];"));
2291 std::fs::remove_dir_all(&root).ok();
2292 }
2293
2294 #[test]
2295 fn stray_ftl_outside_a_locale_dir_is_ignored() {
2296 let root = tmp("locales-stray");
2298 ftl(&root, "en", "hello = Hello");
2299 std::fs::write(root.join("resource/locales/loose.ftl"), "stray = Stray").unwrap();
2300 let plan = plan_resources(&root).unwrap();
2301 let tags: Vec<_> = plan.locales.iter().map(|l| l.locale.as_str()).collect();
2302 assert_eq!(tags, vec!["en"]);
2303 std::fs::remove_dir_all(&root).ok();
2304 }
2305}
2306
2307mod web_resources;