Skip to main content

day_build/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-build: resource-constant codegen for a Day app's `build.rs` (DESIGN.md §18.5).
5//!
6//! An app's `build.rs` calls [`prebuild_project`], the one entry point a Day project needs. It
7//! performs [`generate_resources`], which scans the project's
8//! `resource/{images,assets,fonts}` directories and writes typed symbolic constants to
9//! `$OUT_DIR/day_resources.rs`:
10//!
11//! ```text
12//! pub mod images { use day::ImageName;
13//!     pub const nav_system: ImageName = ImageName::from_static("nav_system"); }
14//! pub mod assets { use day::AssetName;
15//!     pub const numbers_bin: AssetName = AssetName::from_static("numbers.bin"); }
16//! pub mod fonts  { use day::FontFamily;
17//!     pub const pacifico: FontFamily = FontFamily::from_static("Pacifico"); }
18//! pub mod locales { pub const DEFAULT: &str = "en";
19//!     pub const CATALOG: &[(&str, &str)] = &[("en", include_str!("…/en/app.ftl")), …];
20//!     pub const ALL: &[(&str, &str)] = &[("en", "English"), …];  // tag + self-name
21//!     pub fn install() { day::install_locales(DEFAULT, CATALOG) } }
22//! ```
23//!
24//! The app surfaces it once (`pub mod res { include!(concat!(env!("OUT_DIR"), "/day_resources.rs")); }`)
25//! and then writes `image(res::images::nav_system)`; a typo is a compile error and the resource is
26//! guaranteed bundled. `cargo:rerun-if-changed` on each resource dir regenerates when a file is
27//! added or removed.
28//!
29//! This crate is also the canonical source of the resource-name → identifier rules: the CLI stagers
30//! (`day-cli/src/resources`) reuse [`sanitize_ident`] and the derivation helpers here so the string
31//! baked into a constant is exactly the name staged into each backend's native store.
32//!
33//! For the same reason it owns [`permissions`]: the CLI generates each platform's permission
34//! declarations from that table while `day-part-permissions` queries the same permissions at
35//! runtime, and the two must never disagree (docs/permissions.md).
36
37mod 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
47/// The app's display title for embedding in its UI from `build.rs`.
48///
49/// `day build` supplies `DAY_APP_TITLE` after resolving flavor and target overrides. A plain
50/// Cargo build reads `[app].title` from Day.toml, falling back to the Cargo package name.
51/// Registers both inputs so changing the title invalidates the generated output.
52///
53/// # Errors
54///
55/// Returns an error when `DAY_APP_TITLE` is unset and `CARGO_MANIFEST_DIR` or `CARGO_PKG_NAME` is
56/// unset, Day.toml cannot be read or parsed, or `app.title` is not a string.
57pub 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/// The window geometry Day.toml `[window]` declares, for the generated `res::window_options()`:
82/// `size` when it names `width` or `height`, `min_size` when it names `min_width` or
83/// `min_height`. A key left out takes the CLI's default (480x640, minimum 320x400). No Day.toml,
84/// or no `[window]`, declares nothing, and the window keeps `WindowOptions`' own defaults.
85#[derive(Clone, Copy, Debug, Default, PartialEq)]
86pub struct WindowGeometry {
87    pub size: Option<(f64, f64)>,
88    pub min_size: Option<(f64, f64)>,
89}
90
91/// Read [`WindowGeometry`] from the project's Day.toml (registered for rerun by
92/// [`app_title`]).
93///
94/// # Errors
95///
96/// Returns an error when `CARGO_MANIFEST_DIR` is unset, Day.toml does not parse, or a `[window]`
97/// value has the wrong type. A missing Day.toml yields the default geometry.
98pub 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/// A single generated constant: its Rust `symbol`, the `value` string it wraps (the wire name the
184/// backend resolves by), and the `source` file (for the doc comment).
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub struct Entry {
187    pub symbol: String,
188    pub value: String,
189    pub source: String,
190}
191
192/// A generated localization function: the Fluent message `key` (the Rust fn name), its sorted
193/// `params` (each `$variable` the message references, agreed across all locales), and `doc` (the
194/// reference-locale value text, for the generated doc comment).
195#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct StrEntry {
197    pub key: String,
198    pub params: Vec<StrParam>,
199    pub doc: String,
200}
201
202/// One generated function parameter: the Fluent `$variable` name and whether it is used as a
203/// **number** (a plural/`select` selector or `NUMBER()` argument), which types it as
204/// `IntoNumberFArg` instead of `IntoFArg`, so a string can't be passed where a plural count is needed.
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct StrParam {
207    pub name: String,
208    pub numeric: bool,
209}
210
211/// One locale's catalog: the directory name under `resource/locales/` (the tag apps pass to
212/// `set_locale`) and every `.ftl` beneath it, sorted. Multiple files concatenate into the single
213/// source string the Fluent bundle is built from.
214#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct LocaleEntry {
216    pub locale: String,
217    pub sources: Vec<PathBuf>,
218}
219
220/// The full set of constants to emit, grouped by bucket.
221#[derive(Debug, Default, Clone, PartialEq, Eq)]
222pub struct ResourcePlan {
223    pub images: Vec<Entry>,
224    /// `resource/vectors/`: SVG glyphs (and `.symbolset` bundles), typed as `res::vectors::…`
225    /// `VectorName` constants (docs/vectors.md).
226    pub vectors: Vec<Entry>,
227    /// `resource/assets/`: a tree (§18.5). Directories nest, rendered as nested modules with an
228    /// `AssetDir` const per folder and an `AssetName` const per file (values are `/`-relative
229    /// paths). Top-level files keep the flat form older apps compiled against.
230    pub assets: AssetNode,
231    pub fonts: Vec<Entry>,
232    /// Localization keys → `res::str::<key>(params…)` functions (§18.5).
233    pub strings: Vec<StrEntry>,
234    /// The locales themselves → the `res::locales` catalog (§18.5), so an app registers them
235    /// with one call instead of a hand-maintained `include_str!` list.
236    pub locales: Vec<LocaleEntry>,
237}
238
239/// Everything a Day project's `build.rs` has to do, in one call:
240///
241/// ```text
242/// // build.rs
243/// fn main() {
244///     day_build::prebuild_project().expect("day-build: prebuild");
245/// }
246/// ```
247///
248/// Today that is the resource codegen of [`generate_resources`], and nothing else. It exists as
249/// its own name so that a step day-build needs to add later — another codegen pass, a manifest
250/// check, a stamp — arrives in every project that already calls this, rather than as a second
251/// line every app has to be told to add.
252///
253/// An app that wants only part of it can keep calling the narrower functions; they stay public.
254///
255/// # Errors
256///
257/// Returns the errors of [`generate_resources`].
258pub fn prebuild_project() -> Result<(), String> {
259    generate_resources()
260}
261
262/// Scan `resource/{images,assets,fonts}` under `CARGO_MANIFEST_DIR`, emit
263/// `$OUT_DIR/day_resources.rs`, and register the resource dirs for `cargo:rerun-if-changed`.
264/// Returns `Err` (with a fix hint) on a name that is not portable or a symbol collision; the app
265/// `build.rs` should `.expect(...)` this so the problem fails the build loudly.
266///
267/// [`prebuild_project`] is what a scaffolded `build.rs` calls; this is the one step it performs.
268///
269/// # Errors
270///
271/// Returns an error when `CARGO_MANIFEST_DIR` or `OUT_DIR` is unset, a resource name is not
272/// portable or collides with another, Day.toml is invalid, or the generated file cannot be written.
273pub fn generate_resources() -> Result<(), String> {
274    let root = PathBuf::from(env("CARGO_MANIFEST_DIR")?);
275    let out = PathBuf::from(env("OUT_DIR")?);
276    // A build flavor may ship a different `resource/` tree (docs/flavors.md): `day build --flavor`
277    // merges the app's with the flavor's overlay and names the result here, so the generated
278    // constants and the compiled-in strings are the flavor's, not the base app's. Unset for a
279    // plain build, which is every build that is not flavored.
280    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    // Regenerate when a resource is added/removed/renamed (a proc-macro could not do this
293    // reliably). `resource/` itself is registered so a bucket created later still triggers a
294    // rerun (creating a subdirectory changes the parent's mtime), and the no-op pass an Xcode
295    // phase makes after `day build` has already compiled stays a no-op.
296    watch_resources(&root.join("resource"), "resource");
297    // A flavor's overlay, when this build has one. The merged tree DAY_RESOURCE_ROOT names is not
298    // watched: `day build --flavor` rewrites it on every run, so depending on it would recompile
299    // the app crate every time. What a person edits is the app's tree and the overlay, so those
300    // are what a rebuild follows.
301    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    // Typed constructors for the SwiftUI views exported by declared local SwiftPM packages
310    // (docs/swiftui.md): always written, surfaced by an app that wants them via
311    // `pub mod swiftui { include!(concat!(env!("OUT_DIR"), "/day_swiftui.rs")); }`.
312    swiftui::generate_bindings(&root, &out)?;
313    println!("cargo:rerun-if-changed=Cargo.toml");
314    Ok(())
315}
316
317/// The `[[shortcuts]]` Day.toml declares, as `(route, label key)` pairs in declaration order
318/// (docs/deep-links.md "Launcher shortcuts"). No Day.toml, or none declared, is an empty list.
319fn 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
345/// Register the shortcuts into the binary for the menus built at run time (the macOS Dock menu):
346/// a link-time entry in `day::LAUNCHER_SHORTCUTS`, so no app code has to hand them over. Nothing
347/// is emitted for an app without shortcuts, nor on wasm, where `linkme` does not link.
348fn 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
366/// Register one resource tree for `cargo:rerun-if-changed`, by the path cargo should print.
367///
368/// Only the buckets that exist: cargo treats a missing `rerun-if-changed` path as always stale,
369/// and naming an absent `resource/assets` once made every app rebuild on every cargo run.
370fn 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
386/// Scan and validate a project's resources into a [`ResourcePlan`] (the pure, testable core).
387///
388/// # Errors
389///
390/// Returns the errors of [`plan_resources_in`].
391pub fn plan_resources(root: &Path) -> Result<ResourcePlan, String> {
392    plan_resources_in(&root.join("resource"))
393}
394
395/// The same, given the resource tree itself rather than the project root: what a flavored build
396/// passes, because its tree is the merge of the app's and the flavor's and lives under `build/`.
397///
398/// # Errors
399///
400/// Returns an error, with a fix hint, when a resource name is not portable, two resources produce
401/// the same symbol, or a locale catalog is invalid.
402pub 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
413/// Top-level, non-hidden files in `dir`, sorted by name for deterministic output.
414fn 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
433/// Images: the constant is keyed on the file **stem** (with any `@Nx` HiDPI suffix stripped), which
434/// is the name `image("…")` resolves by. The stem must be *portable* (identical after
435/// [`sanitize_ident`]) because Apple/GTK/Qt resolve it verbatim while Android/ArkUI re-sanitize it;
436/// a non-portable stem would silently resolve to two different names across toolkits, so it is a hard
437/// error with a rename hint. `foo.png` + `foo@2x.png` collapse to one constant; two *distinct* files
438/// claiming the same stem at the same scale collide.
439/// Vectors (docs/vectors.md): `resource/vectors/*.svg` files plus `*.symbolset` bundle
440/// directories, keyed on the stem. Same portability rule as images: every backend resolves the
441/// stem, Android/HarmonyOS re-sanitize it.
442fn 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    // stem -> (scales seen, first source path)
496    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/// One directory level of the assets tree (§18.5). `path` is the folder's `/`-relative path under
537/// `resource/assets/` (`""` at the root); each child directory renders as both an `AssetDir` const
538/// and a nested module sharing its name, so `res::assets::web::minisite` names the folder and
539/// `res::assets::web::minisite::index_html` a file within it.
540#[derive(Debug, Default, Clone, PartialEq, Eq)]
541pub struct AssetNode {
542    pub path: String,
543    pub files: Vec<Entry>,
544    /// `(module/const symbol, subtree)`, sorted by symbol.
545    pub dirs: Vec<(String, AssetNode)>,
546}
547
548/// Data assets: a recursive tree. Each file constant wraps the `/`-relative path (the exact
549/// string `resource("…")` resolves by) with the symbol sanitized from the file name alone
550/// (`numbers.bin` → `numbers_bin`); each directory yields an `AssetDir` const plus a nested
551/// module. File and directory symbols share one namespace per level (both are consts), so a
552/// collision at any level is a build error naming both sources.
553fn 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    // Files and directories land in one const namespace per module, so validate them jointly.
606    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
622/// Fonts: the constant wraps the **family name** parsed from the sfnt `name` table (what
623/// `Font::custom` resolves by, *not* the file name), with the symbol derived by the same
624/// `font_ident` rule the runtimes use (`"Special Elite"` → `special_elite`).
625fn 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; // non-font files are ignored (matches scan_fonts, which errors at stage time)
634        }
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
648/// Reject two entries whose symbols collide after sanitization (they would define the same constant).
649fn 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
664/// Recursively collect every `*.ftl` under `dir` (sorted, for deterministic diagnostics/output).
665fn 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/// The message keys defined in a Fluent source (terms/comments ignored, and attributes too:
686/// a locale that omits `menu_group.key` inherits the default locale's shortcut, so the
687/// coverage lint must not demand attributes everywhere). Public so the CLI lint
688/// (`day lint` fluent coverage) shares this one `fluent-syntax` parser with the codegen and
689/// the runtime resolver, instead of a hand-rolled line scanner.
690/// The `res::str` function name a localization key generates.
691///
692/// A Fluent attribute entry is `message.attr`, and its generated accessor flattens both halves into
693/// one identifier: `menu_group.key` is reached as `res::str::menu_group_key()`. Anything asking
694/// "is this key referenced?" has to know that, or a key used through its generated function looks
695/// unused and the reference looks like a key that does not exist.
696///
697/// The flattening is injective by construction: the string planner fails the build when two keys
698/// generate the same name.
699#[must_use]
700pub fn res_str_ident(key: &str) -> String {
701    key.replace('.', "_")
702}
703
704/// Message key → value text for every message in a Fluent resource (attributes excluded;
705/// placeables rendered as `{ $var }`), for tooling that reads a catalog message as data rather
706/// than as UI copy: the permission reasons `day build` writes into each platform's manifest
707/// (docs/permissions.md, "Localized reasons").
708#[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
726/// Localization keys → parameter-typed `res::str` functions. Parses each `.ftl` with
727/// `fluent-syntax` (the same syntax `fluent-bundle` resolves at runtime), collects every message's
728/// `$variable` set (and which vars are numeric: plural/`select` selectors), unions keys across
729/// locales, and enforces two build-time rules: each key must be a valid Rust identifier (the
730/// kebab→snake forcing rule) and all locales must agree on a key's parameter names. A param is
731/// typed numeric if *any* locale uses it numerically; the generated doc shows the value from the
732/// reference locale (`en` if present).
733fn 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    // key -> (params: name -> numeric, the locale file that first defined it)
740    let mut agreed: std::collections::BTreeMap<String, (Params, String)> =
741        std::collections::BTreeMap::default();
742    // key -> (reference value text, whether it came from `en`)
743    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                // `message.attr` (an attribute entry): both halves become one generated fn
753                // name, `message_attr`, so both must be identifiers.
754                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            // Doc: prefer the `en` value, else keep the first one seen.
767            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            // Params: names must agree across locales; numeric is the OR across locales.
772            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    // An attribute's generated fn is `message_attr`; it must not collide with a message
800    // of that name (or another attribute flattening to it).
801    {
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
835/// Group `resource/locales/<locale>/**/*.ftl` by locale directory: the catalog `res::locales`
836/// renders. Locales are discovered, never listed: adding or deleting a locale directory is the
837/// entire act of adding or dropping a language, with no source list to keep in step (the
838/// `cargo:rerun-if-changed` on `resource/locales` in [`generate_resources`] is what makes the
839/// directory itself a build input).
840///
841/// Not fallible: unlike [`plan_strings`], which validates keys and parameters, a locale
842/// directory carries no name rules of its own. A tag that Fluent can't parse degrades to `en`
843/// at runtime (`day_localization::build_bundles`), which is the engine's call, not the build's.
844fn 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        // A stray `.ftl` directly in `resource/locales/` has the bucket itself as its parent and
850        // names no locale, so skip it rather than inventing a `locales` language.
851        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
862/// The fallback locale for the generated `install()`: `en` when the app ships it, else the first
863/// locale alphabetically (a single-locale app gets its own language; a multi-locale app without
864/// English gets a deterministic pick). Apps needing another default call
865/// `install_locales(other, res::locales::CATALOG)`; the catalog stays generated either way.
866fn 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
875/// The locale directory name of a `resource/locales/<locale>/*.ftl` path (its parent dir name).
876fn 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
882/// One parsed Fluent message: its key, `$variables` (name → used-as-a-number), and value text.
883struct FtlMessage {
884    key: String,
885    params: Params,
886    value_text: String,
887}
888
889/// Parse a Fluent resource → one [`FtlMessage`] per message, plus one per message attribute
890/// under the dotted key `message.attr` (how a localized keyboard-shortcut key rides beside
891/// its command's label, docs/localization.md; terms/comments/junk ignored; a parse error on
892/// an unrelated entry is tolerated and the partial resource is still walked).
893fn 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    /// Offsets have to be positions in the source, not a text search: a key named in a
934    /// comment above the message would make a search land a line early, and an editor would then
935    /// squiggle the comment.
936    #[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    /// Attributes carry their own position, so a shortcut label's finding lands on the attribute.
954    #[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    /// A function call is reported where it is written, which is why `FtlCall` carries an
968    /// offset rather than anchoring every option finding to line 1.
969    #[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    /// Columns count characters, because that is what an editor means by a column.
981    #[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        // A multi-byte char earlier on the same line must not inflate the column.
987        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>;
993/// `$variable` name → whether it is used numerically (plural/`select` selector or `NUMBER()` arg).
994type 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            // A plural/number select makes its nav host numeric; a string select (`$gender ->
1011            // [male]…`) does not. Variant bodies are ordinary (non-numeric) context.
1012            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            // The built-in `NUMBER(...)` forces its positional arg numeric; named options don't.
1033            // `DATETIME(...)` does not: its argument is an ISO-8601 string (or an
1034            // epoch number the app formats itself), so the generated `res::str` fn keeps the
1035            // general `IntoFArg` bound (docs/localization.md "Formatted values").
1036            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/// One `FUNC(...)` call in a message value; `day lint` validates function names and option
1060/// values across every locale file with this (the shared fluent-syntax parse, like
1061/// [`message_keys`]).
1062/// Byte offset of `part` within `src`, when `part` is a subslice of it.
1063///
1064/// `fluent_syntax::parser::parse` is generic over the slice type and, given a `&str`, hands back
1065/// an AST whose identifiers and literals borrow straight from the source, so their addresses are
1066/// positions in it. That is all the span information there is: the 0.12 AST carries no explicit
1067/// spans, and re-finding a key by text search would land on the first comment that mentions it.
1068/// The byte offset of `part` within `src`, when `part` is a subslice of it.
1069///
1070/// Parsers here hand back `&str` views into the source rather than spans, so the only way to say
1071/// where a fragment came from is to compare addresses. Returns `None` for a string that merely
1072/// looks alike but was allocated elsewhere, which is what makes it safe to call on anything.
1073#[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/// The 1-based line and column of a byte offset, for callers that report positions to a human or
1080/// an editor. Columns count CHARACTERS rather than bytes, which is what an editor's column means.
1081#[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/// Every message key in a Fluent resource with the byte offset of its identifier, which turns a
1090/// coverage finding into a diagnostic on the right line rather than on line 1.
1091#[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    /// The message key the call appears under.
1117    pub key: String,
1118    /// The function name as written (`NUMBER`, `DATETIME`, …).
1119    pub name: String,
1120    /// Named options with their literal values (`style: "percent"` → `("style", "percent")`;
1121    /// non-literal option values are omitted).
1122    pub named: Vec<(String, String)>,
1123    /// Byte offset of the function name in the source, so a bad option can be reported where it
1124    /// is written rather than against the whole file.
1125    pub offset: usize,
1126}
1127
1128/// Every function call in every message of a Fluent resource (parse errors tolerated; the
1129/// partial resource is walked, matching [`message_keys`]).
1130#[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
1217/// Whether a `select` is a **plural / number** select (nav host is a number) rather than a string
1218/// select (e.g. `$gender -> [male] [female]`): true if any variant key is a number literal or a CLDR
1219/// plural category other than the ambiguous `other` (which both plural and string selects use).
1220fn 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
1229/// A one-line, human-readable rendering of a message value for the generated doc comment
1230/// (`Hello, { $name }!`, `{ $count -> … }`), whitespace collapsed. Backticks are stripped so the
1231/// value can be wrapped in a doc-comment code span.
1232fn 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
1260/// A valid Rust identifier: leading `[A-Za-z_]`, remaining `[A-Za-z0-9_]`, and not the bare `_`.
1261/// Keyword idents still count as valid; `ident_token` raw-escapes them at render time.
1262fn 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/// Render a plan to the `day_resources.rs` source text. This file is `include!`d inside the app's
1273/// `pub mod res { … }`, so the lint waivers are **outer** attributes on each bucket module (an inner
1274/// `#![…]` is not valid at an `include!` site) and cover a bucket with no constants (unused `use`).
1275#[must_use]
1276pub fn render(plan: &ResourcePlan) -> String {
1277    render_app(plan, None, WindowGeometry::default())
1278}
1279
1280/// [`render`] with the app's Day.toml identity: its title for `window_options()` when the
1281/// catalog has no `app_title` message, and its `[window]` geometry.
1282#[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    // `locales::install()` names `day::install_locales`, so the generated file needs the umbrella
1288    // crate in scope wherever it is included, the same assumption the other buckets make with
1289    // `day::ImageName`.
1290    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
1300/// Render the `locales` bucket: the app's whole Fluent catalog, embedded. `install()` is the
1301/// one-liner an app's `root()` calls; the source list can't drift from the directory because
1302/// it is the directory.
1303///
1304/// A relative `include_str!` would resolve against `$OUT_DIR`, where this file is `include!`d
1305/// from, rather than the crate, so each source is named from the crate root through
1306/// [`include_source`]. Several `.ftl` files
1307/// in one locale directory `concat!` into a single source (Fluent bundles are per-locale, and
1308/// `day_localization::install` keys them by tag, so two entries for one tag would shadow, not merge).
1309fn 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        // `concat!` of one argument is the identity, so the single-file case stays readable.
1334        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
1380/// A locale's self-name: the value of the `language_name` message in its catalog, read at
1381/// build time. A line scan, not a Fluent parse: the convention is a single-line literal
1382/// message (`language_name = Français`), and anything fancier falls back to the tag.
1383/// Each language's name for itself, for the language picker when a catalog has no
1384/// `language_name` message: the exact tag first, then its language-script prefix
1385/// (`zh-Hans-CN` → `zh-Hans`), then the bare language.
1386fn 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
1474/// Render the `str` bucket: one `pub fn` per localization key whose signature carries the message's
1475/// parameters, so `res::str::greeting(name)` == `tr("greeting").arg("name", name)`, checked at
1476/// compile time (a missing key or wrong arity is an error).
1477fn 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    // Day's own strings (`day_cancel`, `day_about_website`, …) sit beside the crate's, so every
1485    // localized string is named the same way. The glob loses to an item of the same name, so a
1486    // message the crate defines under a core key overrides that accessor, as it overrides the text.
1487    let _ = writeln!(s, "    pub use ::{api}::res::str::*;");
1488    for e in entries {
1489        // Each param is `impl day::IntoFArg<Mn>`, or `IntoNumberFArg` when the message uses it as a
1490        // plural/`select` selector (a distinct marker generic per arg). The Rust parameter ident is
1491        // sanitized while the `.arg("…")` string stays the exact Fluent variable.
1492        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        // Doc shows the key + the reference-locale value, so IDE hover reveals the actual text.
1502        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            // Two or more arguments take one named-field struct, so same-typed arguments can
1510            // never be swapped silently and a translation adding a variable cannot change the
1511            // meaning of an existing call (docs/localization.md).
1512            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/// `items_moved` → `ItemsMoved`: the name of a message's argument struct.
1593#[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
1610/// Render `window_options()`: the options every window of the app starts from, with the
1611/// catalog, the localized title (the `app_title` message when the catalog has one, else the
1612/// manifest's title), the Day.toml `[window]` geometry, and the version from Cargo
1613/// (docs/windows.md).
1614fn 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
1646/// Render the assets tree (§18.5): one module per directory, an `AssetDir` const beside each
1647/// nested module (same name; consts and modules live in different namespaces), an `AssetName`
1648/// const per file. The root module is `assets`, matching the flat form apps already compile
1649/// against for top-level files.
1650fn 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
1697/// Wrap a Rust keyword symbol as a raw identifier so a resource named e.g. `type` still compiles.
1698fn 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
1713/// Split a `foo@2x` stem into (`"foo"`, 2); a bare `foo` yields (`"foo"`, 1).
1714fn 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/// Sanitize a name to the strictest platform identifier rules (Android `R` / ArkUI): lowercase, only
1726/// `[a-z0-9_]`, forced leading letter. The canonical copy: the CLI stagers re-export this so the
1727/// staged native name and the generated constant string agree by construction.
1728#[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
1747/// The `include_str!` for one embedded source file.
1748///
1749/// A file inside the crate is named from `env!("CARGO_MANIFEST_DIR")`, never by its absolute
1750/// path, so the generated text is the same wherever the project sits. That is what makes a
1751/// release binary reproducible from another directory (`day rebuild`, §20.3): rustc records
1752/// source positions as offsets into every file it loaded, a crate that calls into this module
1753/// loads this file too, and a path spelled out here would change its length, shift every later
1754/// offset, and change the binary's `ThinLTO` symbol suffixes with them. A file outside the crate (a
1755/// flavor's merged tree under another root) keeps its absolute path; `{:?}` escapes either into a
1756/// valid Rust literal, Windows separators included.
1757fn 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
1771/// A project-relative-ish display path for error messages / doc comments (`resource/images/x.png`).
1772fn display(path: &Path) -> String {
1773    // Keep the last three components (`resource/<bucket>/<file>`) when present: stable across
1774    // machines and enough to locate the file.
1775    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        // Unique per test so the parallel test threads never clobber each other's dirs.
1791        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"); // HiDPI variant of the same logical image
1816        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}"); // suggests the fix
1830        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"); // two distinct files, both stem `logo`, scale 1
1839        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        // Values are `/`-relative paths; symbols come from the leaf name alone.
1870        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        // A file and a directory cannot share a literal name on disk, but their SYMBOLS can
1902        // collide after sanitization: `site.old` (file) and `site-old/` (dir) both map to
1903        // `site_old`, and both land in the same module's const namespace.
1904        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        // `counter_value` uses $count in a plural select (multiline): same variable set as a flat
1977        // value, and numeric (a plural nav host); `greeting` has one non-numeric param; `nav_home`
1978        // has none. The doc captures the reference-locale value text (#5).
1979        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 }!"); // #5
1990        assert!(!entry(&plan, "greeting").params[0].numeric);
1991        // #2: a plural-select nav host is typed numeric.
1992        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        // A `select` on a string (gender) must not force its nav host numeric.
2001        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        // `en` uses $count as a plural nav host (numeric); `zh` uses it as a flat interpolation.
2023        // The param must be numeric because some locale needs a number.
2024        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        // Public parser shared with `day lint`: messages only (terms/comments excluded).
2038        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}"); // suggests the fix
2049        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)], // numeric plural → IntoNumberFArg
2078                    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        // Day's core accessors sit beside the app's (`res::str::day_cancel()`).
2091        assert!(code.contains("pub use ::day::res::str::*;"));
2092        assert!(code.contains("/// `hello_world` — `Hello!`")); // #5: doc shows the value
2093        assert!(
2094            code.contains(
2095                "pub fn hello_world() -> day::LocalizedText { day::tr(\"hello_world\") }"
2096            )
2097        );
2098        // #2: a numeric param is `IntoNumberFArg`; non-numeric stays `IntoFArg`.
2099        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        // #3: two or more arguments take a named-field struct, so same-typed arguments cannot
2103        // be swapped silently (docs/localization.md).
2104        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        // `window_options()` carries the catalog and the version; without an `app_title`
2111        // message the manifest title is used when one is given.
2112        assert!(code.contains("pub fn window_options() -> day::WindowOptions {"));
2113        assert!(code.contains(".version(env!(\"CARGO_PKG_VERSION\"))"));
2114    }
2115
2116    // ---- Attributes: localized shortcut keys ride beside their command's label ----
2117
2118    #[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        // fr omits `.key`: the runtime falls back to the default locale's, and the codegen
2123        // still emits one accessor from the union.
2124        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    // ---- The `locales` catalog: the app's whole language list, discovered not declared ----
2155
2156    #[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"]); // sorted → deterministic output
2165        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        // Absolute paths: the generated file is `include!`d from $OUT_DIR, so a relative
2180        // `include_str!` would resolve against the wrong directory. Compare against the plan's
2181        // own source path, not a re-`join`ed one: on Windows, discovery separates components
2182        // with `\` where a joined `"a/b"` literal keeps its `/`, so the strings differ even
2183        // when the paths agree. `ends_with` compares components, so it holds on both.
2184        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        // The same file from another checkout renders the same text, so nothing about the
2219        // directory reaches the compiler's source map.
2220        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        // Outside the crate (a flavor's merged tree) the absolute path stays.
2229        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"); // app.ftl
2240        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        // Both keys are still generated, and the sources join into one catalog entry (a second
2246        // entry for the same tag would shadow the first in day_localization's per-locale bundle map).
2247        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        // The two files concatenate into a single `("en", concat!(…))` CATALOG entry. Match the
2251        // concat!-tagged form specifically: the `ALL` language-picker array carries a
2252        // `("en", "en")` pair of its own, so a bare `("en", ` count would see both.
2253        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        // No English: the first tag alphabetically, so the pick is deterministic.
2270        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        // An app with no `resource/locales/` still compiles: `install()` registers nothing and
2283        // day-localization's built-in core catalog keeps answering framework keys.
2284        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        // `resource/locales/loose.ftl` names no language; it must not become a `locales` locale.
2297        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;