Skip to main content

logicaffeine_compile/
loader.rs

1//! Module loader for multi-file LOGOS projects.
2//!
3//! Handles resolution and loading of module sources from various URI schemes,
4//! with caching to prevent duplicate loading.
5//!
6//! # Supported URI Schemes
7//!
8//! | Scheme | Example | Description |
9//! |--------|---------|-------------|
10//! | `file:` | `file:./geometry.md` | Local filesystem (relative) |
11//! | `logos:` | `logos:std` | Built-in standard library |
12//! | (none) | `geometry.md` | Defaults to `file:` scheme |
13//!
14//! # Security
15//!
16//! The loader prevents path traversal attacks by checking that resolved
17//! paths remain within the project root directory.
18//!
19//! # Caching
20//!
21//! Modules are cached by their normalized URI. The same module loaded from
22//! different base paths will be cached separately.
23//!
24//! # Example
25//!
26//! ```no_run
27//! # use logicaffeine_compile::loader::Loader;
28//! # use std::path::{Path, PathBuf};
29//! # fn main() -> Result<(), String> {
30//! # let project_root = PathBuf::from(".");
31//! let mut loader = Loader::new(project_root);
32//! let source = loader.resolve(Path::new("main.md"), "file:./lib/math.md")?;
33//! println!("Loaded: {}", source.path.display());
34//! # Ok(())
35//! # }
36//! ```
37
38use std::collections::HashMap;
39use std::fs;
40use std::path::{Path, PathBuf};
41
42pub use crate::stdlib_text::defined_names_with_visibility;
43pub(crate) use crate::stdlib_text::{defined_names, function_header, module_code, strip_note_blocks};
44use crate::stdlib_text::{
45    builtin_backed, fn_section_name, function_section_ranges, is_ident_byte, may_name,
46    references, whole_words,
47};
48
49/// Resolve a requested module path to a concrete file: the exact path if it
50/// exists, otherwise `<path>.lg` then `<path>.md` — so `Import Geometry.`
51/// (whose URI is the extension-less `./geometry`) finds `geometry.lg` or
52/// `geometry.md`. Failing that, a DIRECTORY / barrel module: `Import Lexer.`
53/// resolves `lexer/lexer.lg` (self-descriptive), then `lexer/mod.lg`, then their
54/// `.md` variants — so a whole subsystem is one import. Returns the actual file
55/// path, or `None` if none exists.
56///
57/// File resolution is tried BEFORE the directory probe, so a real `lexer.lg`
58/// beside a `lexer/` directory always wins (adding a directory never silently
59/// shadows an existing module file).
60fn resolve_module_file(requested: &Path) -> Option<PathBuf> {
61    if requested.is_file() {
62        return Some(requested.to_path_buf());
63    }
64    for ext in ["lg", "md"] {
65        let candidate = requested.with_extension(ext);
66        if candidate.is_file() {
67            return Some(candidate);
68        }
69    }
70    if requested.is_dir() {
71        if let Some(dirname) = requested.file_name().and_then(|s| s.to_str()) {
72            let candidates = [
73                requested.join(format!("{dirname}.lg")),
74                requested.join(format!("{dirname}.md")),
75                requested.join("mod.lg"),
76                requested.join("mod.md"),
77            ];
78            for candidate in candidates {
79                if candidate.is_file() {
80                    return Some(candidate);
81                }
82            }
83        }
84    }
85    None
86}
87
88/// Suggest the closest existing sibling module for a mistyped bare import
89/// (`Import Geometrey.` → "did you mean `Geometry`?"). Compares case-insensitively
90/// (imports are Capitalized, files lowercase) over the `.lg`/`.md` stems beside
91/// the requested path, within a small edit distance.
92fn suggest_sibling_module(requested: &Path, name: &str) -> Option<String> {
93    let dir = requested.parent()?;
94    let mut stems: Vec<String> = Vec::new();
95    for entry in std::fs::read_dir(dir).ok()?.flatten() {
96        let path = entry.path();
97        let is_module = path
98            .extension()
99            .and_then(|e| e.to_str())
100            .is_some_and(|e| e == "lg" || e == "md");
101        if is_module {
102            if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
103                stems.push(stem.to_lowercase());
104            }
105        }
106    }
107    let refs: Vec<&str> = stems.iter().map(String::as_str).collect();
108    let target = name.to_lowercase();
109    logicaffeine_language::suggest::find_similar(&target, &refs, 3).map(|s| {
110        let mut chars = s.chars();
111        match chars.next() {
112            Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
113            None => s.to_string(),
114        }
115    })
116}
117
118/// A loaded module's source content and metadata.
119#[derive(Debug, Clone)]
120pub struct ModuleSource {
121    /// The source content of the module
122    pub content: String,
123    /// The resolved path (for error reporting and relative resolution)
124    pub path: PathBuf,
125}
126
127/// A declared dependency's resolved root: the alias an `Import <Name>.` binds to
128/// (matched case-insensitively against the bare import name) and the
129/// canonicalized directory its modules live under. Populated from a project's
130/// `Largo.toml` `[dependencies]`; empty for a single-project build.
131#[derive(Debug, Clone)]
132pub struct DepRoot {
133    /// The dependency name (its `[dependencies]` key / `Import` alias).
134    pub name: String,
135    /// The canonicalized directory the dependency's modules live under.
136    pub root: PathBuf,
137}
138
139/// Module loader that handles multiple URI schemes.
140///
141/// Caches loaded modules to prevent duplicate loading and supports
142/// cycle detection through the cache.
143pub struct Loader {
144    /// Cache of loaded modules (URI -> ModuleSource)
145    cache: HashMap<String, ModuleSource>,
146    /// Root directory of the project (for relative path resolution)
147    root_path: PathBuf,
148    /// Declared dependency roots ([`DepRoot`]). An `Import <Name>.` whose bare
149    /// name matches a dependency resolves against that dependency's root, and the
150    /// containment gate ADMITS every declared root (canonicalized) in addition to
151    /// the project root — so a linked dependency lives legally OUTSIDE the project
152    /// root while an undeclared `..` escape is still refused.
153    dep_roots: Vec<DepRoot>,
154    /// The directory holding this project's `Largo.toml`, found by walking up from
155    /// [`root_path`](Self::root_path) — `None` for a `.lg` that is not in a project
156    /// (a scratch file, a doc example), which then resolves exactly as it always did.
157    ///
158    /// ★ IT IS WHAT MAKES A BARE `Import <Name>.` MEAN "a module of THIS PROJECT".
159    /// The loader used to search only the importing file's own directory, so a page in
160    /// `pages/` could not reach `src/shared.lg` — the one type a page and its server
161    /// agree about was unreachable from the page. It is also the containment root, so
162    /// a page may legally name a module in a sibling directory of the same project.
163    project_root: Option<PathBuf>,
164}
165
166/// The directory holding the nearest `Largo.toml` at or above `start`.
167///
168/// Discovered rather than threaded through every caller deliberately: `largo build`, `largo test`,
169/// the LSP and a plain `assemble_project` must agree about what a bare name means, and three
170/// callers passing it separately is three chances for them to disagree.
171fn find_project_root(start: &Path) -> Option<PathBuf> {
172    let mut dir = Some(start);
173    while let Some(d) = dir {
174        if d.join("Largo.toml").is_file() {
175            return Some(d.to_path_buf());
176        }
177        dir = d.parent();
178    }
179    None
180}
181
182impl Loader {
183    /// Creates a new Loader with the given root path.
184    pub fn new(root_path: PathBuf) -> Self {
185        Loader {
186            cache: HashMap::new(),
187            project_root: find_project_root(&root_path),
188            root_path,
189            dep_roots: Vec::new(),
190        }
191    }
192
193    /// Creates a Loader that additionally admits the declared dependency roots —
194    /// the seam that links `path`/`git`-local packages into the closure.
195    pub fn with_dep_roots(root_path: PathBuf, dep_roots: Vec<DepRoot>) -> Self {
196        Loader {
197            cache: HashMap::new(),
198            project_root: find_project_root(&root_path),
199            root_path,
200            dep_roots,
201        }
202    }
203
204    /// Resolves a URI to a module source.
205    ///
206    /// Supports:
207    /// - `file:./path.md` - Local filesystem (relative to base_path)
208    /// - `logos:std` - Built-in standard library
209    /// - `logos:core` - Built-in core types
210    pub fn resolve(&mut self, base_path: &Path, uri: &str) -> Result<&ModuleSource, String> {
211        // Normalize the URI for caching
212        let cache_key = self.normalize_uri(base_path, uri)?;
213
214        // Check cache first
215        if self.cache.contains_key(&cache_key) {
216            return Ok(&self.cache[&cache_key]);
217        }
218
219        // Load based on scheme
220        let source = if uri.starts_with("file:") {
221            self.load_file(base_path, uri)?
222        } else if uri.starts_with("logos:") {
223            self.load_intrinsic(uri)?
224        } else if uri.starts_with("https://") || uri.starts_with("http://") {
225            // Remote loading not supported in base loader
226            return Err(format!(
227                "Remote module loading not supported for '{}'. \
228                 Use the CLI's 'logos fetch' command to download dependencies locally.",
229                uri
230            ));
231        } else {
232            // Default to file: scheme if no scheme provided
233            self.load_file(base_path, &format!("file:{}", uri))?
234        };
235
236        // Cache and return
237        self.cache.insert(cache_key.clone(), source);
238        Ok(&self.cache[&cache_key])
239    }
240
241    /// Normalizes a URI for consistent caching.
242    fn normalize_uri(&self, base_path: &Path, uri: &str) -> Result<String, String> {
243        if uri.starts_with("file:") {
244            let path_str = uri.trim_start_matches("file:");
245            let base_dir = base_path.parent().unwrap_or(&self.root_path);
246            let resolved = base_dir.join(path_str);
247            Ok(format!("file:{}", resolved.display()))
248        } else {
249            Ok(uri.to_string())
250        }
251    }
252
253    /// Loads a module from the local filesystem.
254    fn load_file(&self, base_path: &Path, uri: &str) -> Result<ModuleSource, String> {
255        let path_str = uri.trim_start_matches("file:");
256
257        // Resolve relative to the base file's directory
258        let base_dir = base_path.parent().unwrap_or(&self.root_path);
259        let requested = base_dir.join(path_str);
260
261        // Resolve the concrete file: the exact path, or — for a bare `Import
262        // Name` whose URI carries no extension — `<name>.lg` / `<name>.md`.
263        // Failing that, a bare `Import <Dep>.` may name a DECLARED dependency,
264        // whose modules live outside the project (`resolve_in_dep_roots`).
265        let resolved_path = resolve_module_file(&requested)
266            .or_else(|| self.resolve_in_project(&requested))
267            .or_else(|| self.resolve_in_dep_roots(&requested))
268            .ok_or_else(|| {
269            let name = requested
270                .file_name()
271                .and_then(|s| s.to_str())
272                .unwrap_or("module");
273            let dir = requested
274                .parent()
275                .and_then(|p| p.to_str())
276                .filter(|s| !s.is_empty())
277                .unwrap_or(".");
278            if requested.extension().is_some() {
279                format!("could not find the module file `{}` (looked in {dir})", requested.display())
280            } else {
281                let hint = suggest_sibling_module(&requested, name)
282                    .map(|s| format!(" — did you mean `{s}`?"))
283                    .unwrap_or_default();
284                format!(
285                    "could not find a module named `{name}` — looked for `{name}.lg` and `{name}.md` in {dir}{hint}"
286                )
287            }
288        })?;
289
290        // Security: FAIL-CLOSED path containment. Canonicalize the resolved file
291        // and reject BEFORE reading if it escapes EVERY allowed root — the project
292        // root PLUS each declared dependency root — or if it can't be
293        // canonicalized (never fall back to a permissive check). A declared
294        // dependency legally lives outside the project root; an UNdeclared `..`
295        // escape matches no allowed root and is refused. `logos:` intrinsics never
296        // reach here.
297        let canonical_path = resolved_path.canonicalize().map_err(|_| {
298            format!(
299                "Security: cannot verify that `{}` is within the project root",
300                resolved_path.display()
301            )
302        })?;
303        if !self.is_within_an_allowed_root(&canonical_path)? {
304            return Err(format!("Security: `{uri}` escapes the project root"));
305        }
306
307        // Read the file — only after the containment gate has passed.
308        let content = fs::read_to_string(&resolved_path)
309            .map_err(|e| format!("Failed to read '{}': {}", resolved_path.display(), e))?;
310
311        Ok(ModuleSource {
312            content,
313            path: resolved_path,
314        })
315    }
316
317    /// Resolve a bare `Import <Dep>.` (URI `file:./<dep>`) against a DECLARED
318    /// dependency's root when in-project resolution failed. The import's bare name
319    /// (the requested path's final component, extension stripped) is matched
320    /// case-insensitively against each declared dependency, and within that
321    /// dependency's root the module is found the same way the loader finds any
322    /// module: `<root>/<dep>.lg|.md`, the barrel `<root>/<dep>/…`, or the
323    /// dependency's own `src/<dep>.lg|.md` / `src/main.lg|.md` project layout.
324    /// `None` when no dependency matches or the module isn't found in its root.
325    /// A bare `Import <Name>.` that named no module beside the importing file: look for it in the
326    /// PROJECT's own module directories — `src/` first, then the project root.
327    ///
328    /// ★ THE IMPORTING FILE'S OWN DIRECTORY IS SEARCHED FIRST, by the caller, and that order is the
329    /// decision: a module beside you is the one you meant. Preferring `src/` would silently change
330    /// which file an existing project's import resolves to, which is behaviour nobody edited.
331    ///
332    /// Only a BARE name reaches here — one with an extension is an explicit path that says exactly
333    /// where to look, and second-guessing it would resolve `from "old/thing.lg"` to a different file.
334    fn resolve_in_project(&self, requested: &Path) -> Option<PathBuf> {
335        if requested.extension().is_some() {
336            return None;
337        }
338        let root = self.project_root.as_ref()?;
339        let name = requested.file_name()?;
340        let candidates = [root.join("src").join(name), root.join(name)];
341        candidates.iter().find_map(|c| resolve_module_file(c))
342    }
343
344    fn resolve_in_dep_roots(&self, requested: &Path) -> Option<PathBuf> {
345        if self.dep_roots.is_empty() {
346            return None;
347        }
348        let stem = requested
349            .file_name()
350            .and_then(|s| s.to_str())
351            .map(|n| n.rsplit_once('.').map(|(s, _)| s).unwrap_or(n))?;
352        let stem_lc = stem.to_lowercase();
353        let dep = self
354            .dep_roots
355            .iter()
356            .find(|d| d.name.to_lowercase() == stem_lc)?;
357        // Candidate module locations within the dependency's root, in priority
358        // order: a flat module beside the root, its `src/` project layout, then
359        // the dependency's conventional entry.
360        let candidates = [
361            dep.root.join(stem),
362            dep.root.join("src").join(stem),
363            dep.root.join("src").join("main"),
364        ];
365        for candidate in candidates {
366            if let Some(found) = resolve_module_file(&candidate) {
367                return Some(found);
368            }
369        }
370        None
371    }
372
373    /// True when `canonical_path` is contained within the project root OR any
374    /// declared dependency root (all canonicalized). Fail-closed: a project root
375    /// that can't be canonicalized is a hard error.
376    fn is_within_an_allowed_root(&self, canonical_path: &Path) -> Result<bool, String> {
377        let canonical_root = self.root_path.canonicalize().map_err(|_| {
378            format!(
379                "Security: cannot verify the project root `{}`",
380                self.root_path.display()
381            )
382        })?;
383        if canonical_path.starts_with(&canonical_root) {
384            return Ok(true);
385        }
386        // The PROJECT root, when the entry sits in a subdirectory of one (`pages/app.lg` has
387        // `pages/` as its base). Without it a page could not name a module in `src/` even by an
388        // explicit path — the widening above would find the file and the gate would refuse it.
389        // An import that escapes the project ENTIRELY is still refused, which is the gate's job.
390        if let Some(project) = &self.project_root {
391            if let Ok(p) = project.canonicalize() {
392                if canonical_path.starts_with(&p) {
393                    return Ok(true);
394                }
395            }
396        }
397        for dep in &self.dep_roots {
398            // A dep root is already canonicalized at resolution time; canonicalize
399            // again defensively (cheap, and robust to a caller passing a raw path).
400            if let Ok(dep_root) = dep.root.canonicalize() {
401                if canonical_path.starts_with(&dep_root) {
402                    return Ok(true);
403                }
404            } else if canonical_path.starts_with(&dep.root) {
405                return Ok(true);
406            }
407        }
408        Ok(false)
409    }
410
411    /// Loads a built-in module (embedded at compile time).
412    fn load_intrinsic(&self, uri: &str) -> Result<ModuleSource, String> {
413        let name = uri.trim_start_matches("logos:");
414
415        match name {
416            "std" => Ok(ModuleSource {
417                content: include_str!("../assets/std/std.lg").to_string(),
418                path: PathBuf::from("logos:std"),
419            }),
420            "core" => Ok(ModuleSource {
421                content: include_str!("../assets/std/core.lg").to_string(),
422                path: PathBuf::from("logos:core"),
423            }),
424            _ => Err(format!("Unknown intrinsic module: '{}'", uri)),
425        }
426    }
427
428    /// Checks if a module has already been loaded (for cycle detection).
429    pub fn is_loaded(&self, uri: &str) -> bool {
430        self.cache.contains_key(uri)
431    }
432
433    /// Returns all loaded module URIs (for debugging).
434    pub fn loaded_modules(&self) -> Vec<&str> {
435        self.cache.keys().map(|s| s.as_str()).collect()
436    }
437}
438
439// ─── Standard-library prelude (Phase 10) ────────────────────────────────────
440//
441// The concurrency / net / io / crdt vocabulary, embedded at compile time and made
442// available WITHOUT an explicit import. To keep non-stdlib programs byte-identical
443// (the AOT hot-path contract), a module is prepended ONLY when the program
444// references that module's vocabulary — and per-module, so a program that names a
445// pure net/io type is not forced async by the concurrency helpers it never uses.
446// A `## NoPrelude` line opts out entirely.
447
448/// ★ THE MIME TABLE LIVES IN ONE PLACE, AND THAT PLACE IS `static.lg`. ★
449///
450/// A content type decides whether a browser RUNS a file, renders it, or downloads it — so it is
451/// not cosmetic: a stylesheet typed `text/plain` is ignored, a wasm module typed
452/// `application/octet-stream` fails `instantiateStreaming`, and a page with no charset renders a
453/// visitor's name as mojibake.
454///
455/// TWO different things ask the question. A DEPLOYED LOGOS program answers it by calling
456/// `static.lg`'s `contentTypeFor`; `largo serve` and `largo build` answer it as the tool
457/// assembling a site. When those were two tables they had already DRIFTED — `text/css` against
458/// `text/css; charset=utf-8`, and six types the LOGOS side did not know at all, so a deployed
459/// site served its own fonts as `application/octet-stream`. A file typed one way in development
460/// and another in production is the single worst place for a difference to appear.
461///
462/// So there is ONE table and the tool READS IT, rather than two tables held in agreement by a
463/// test. `static.lg` is the source because framework logic belongs in LOGOS, where every tier
464/// runs it; adding a type there is the only edit an author ever makes, and largo picks it up with
465/// no second place to remember.
466pub fn content_type_for(path: &str) -> &'static str {
467    static TABLE: std::sync::OnceLock<Vec<(String, &'static str)>> = std::sync::OnceLock::new();
468    let table = TABLE.get_or_init(|| parse_content_types(STD_STATIC));
469    let lower = path.to_ascii_lowercase();
470    for (suffix, ty) in table {
471        if lower.ends_with(suffix) {
472            return ty;
473        }
474    }
475    // The same download-never-guess default `contentTypeFor` ends with. Guessing `text/html` for
476    // an unknown file would let an uploaded file be served as a PAGE — a stored-XSS delivery path.
477    "application/octet-stream"
478}
479
480/// Read `contentTypeFor`'s `If endsWith(p, ".ext") …: Return "type".` chain out of `static.lg`,
481/// in source order — the same order a LOGOS reader evaluates it in, so `.woff2` is tested before
482/// `.woff` exactly as the file writes it.
483fn parse_content_types(source: &str) -> Vec<(String, &'static str)> {
484    let body = match source.split("## To contentTypeFor").nth(1) {
485        Some(rest) => rest.split("\n## ").next().unwrap_or(rest),
486        None => return Vec::new(),
487    };
488    let mut out = Vec::new();
489    let mut pending: Vec<String> = Vec::new();
490    for line in body.lines() {
491        let line = line.trim();
492        if let Some(rest) = line.strip_prefix("If endsWith(p, \"") {
493            if let Some(suffix) = rest.split('"').next() {
494                pending.push(suffix.to_ascii_lowercase());
495            }
496        } else if let Some(rest) = line.strip_prefix("Return \"") {
497            if let Some(ty) = rest.split('"').next() {
498                // The trailing bare `Return "application/octet-stream".` has no `If` in front of
499                // it: it is the default, not an extension's answer, so it binds nothing.
500                let ty: &'static str = Box::leak(ty.to_string().into_boxed_str());
501                for suffix in pending.drain(..) {
502                    out.push((suffix, ty));
503                }
504            }
505        }
506    }
507    out
508}
509
510// The prelude's modules, embedded by the build script from `stdlib_text::PRELUDE_FILES`: `STD_<STEM>` for each
511// and `PRELUDE_MODULES` in splice order, with the index `stdlib_text::index` derives from them once per build
512// (`PRELUDE_NAMES`, `PRELUDE_NATIVES`, `PRELUDE_PULLS`, `PRELUDE_MENTIONS_TEXT_FROM_BYTES`, `PRELUDE_SPLICE`,
513// `LIBRARY_SECTIONS`).
514include!(concat!(env!("OUT_DIR"), "/stdlib_index.rs"));
515
516/// Does the user `source` itself define `name`? If so, the user's definition wins at every
517/// call the program writes (see [`apply_prelude_mapped`]).
518fn defines(source: &str, name: &str) -> bool {
519    defined_names(source).iter().any(|n| n == name)
520}
521
522/// The names a program binds LOCALLY — the program's own names, distinct from the top-level
523/// `## To`/`## A` declarations [`defined_names`] reports, split by whether a CALL can reach them.
524///
525/// * `callables` — `Let <name> be (<params>) -> …` closures. A call `name(…)` resolves to a
526///   top-level function before a local, so a closure sharing a stdlib function's name is a
527///   declaration in every sense that matters: the stdlib function must be renamed out of its way.
528/// * `values` — every other `Let`, loop variable (`Repeat for x in`, `For each x in`) and
529///   parameter. A value and a function of the same name coexist (`words` reads the variable,
530///   `words(s)` calls the function), so such a name neither suppresses nor renames anything; it
531///   only stops counting as a *use* of the stdlib name unless it is actually called
532///   (`item 1 of perm` is not a use of math.lg's `perm`).
533///
534/// Used ONLY by [`apply_prelude`]; kept out of `defined_names` so downstream consumers (the
535/// assembler's `fn_index`/closure bookkeeping) never see local variables as top-level definitions.
536struct LocalBindings {
537    callables: Vec<String>,
538    values: Vec<String>,
539}
540
541fn local_bindings(source: &str) -> LocalBindings {
542    fn plain_ident(s: &str) -> Option<&str> {
543        let s = s.trim();
544        (!s.is_empty() && s.chars().all(|c| c.is_alphanumeric() || c == '_')).then_some(s)
545    }
546    let mut callables = Vec::new();
547    let mut values = Vec::new();
548    for line in source.lines() {
549        let t = line.trim();
550        if let Some(rest) = t.strip_prefix("Let ") {
551            let rest = rest.strip_prefix("mutable ").unwrap_or(rest);
552            if let Some((name, value)) = rest.split_once(" be ") {
553                if let Some(name) = plain_ident(name) {
554                    let value = value.trim_start();
555                    if value.starts_with('(') && value.contains(") ->") {
556                        callables.push(name.to_string());
557                    } else {
558                        values.push(name.to_string());
559                    }
560                }
561            }
562        }
563        for head in ["Repeat for ", "For each "] {
564            if let Some(rest) = t.strip_prefix(head) {
565                if let Some((name, _)) = rest.split_once(" in ") {
566                    if let Some(name) = plain_ident(name) {
567                        values.push(name.to_string());
568                    }
569                }
570            }
571        }
572        // Parameters: `(name: Type` in a `## To` header or a closure literal.
573        if t.starts_with("## To ") || t.contains(") ->") {
574            let mut from = 0;
575            while let Some(off) = t[from..].find(':') {
576                let colon = from + off;
577                from = colon + 1;
578                let before = t[..colon].trim_end();
579                let word_start = before
580                    .rfind(|c: char| !(c.is_alphanumeric() || c == '_'))
581                    .map(|i| i + 1)
582                    .unwrap_or(0);
583                let opener = before[..word_start].trim_end();
584                if opener.ends_with('(') || opener.ends_with(',') {
585                    if let Some(name) = plain_ident(&before[word_start..]) {
586                        values.push(name.to_string());
587                    }
588                }
589            }
590        }
591    }
592    LocalBindings { callables, values }
593}
594
595/// The reserved spelling a stdlib definition takes when the program declares the same name
596/// itself. The double underscore is what no LOGOS author writes and what no stdlib name contains;
597/// a type or variant keeps its capital (the parser reads a capitalized word as a type name).
598fn hygienic_name(name: &str) -> String {
599    if name.starts_with(|c: char| c.is_ascii_uppercase()) {
600        format!("Std__{name}")
601    } else {
602        format!("__std_{name}")
603    }
604}
605
606/// Rename, inside spliced STDLIB code, every definition of and reference to a name the program
607/// declares itself, so the program's definition and the library's coexist and library code keeps
608/// reaching the library's own.
609///
610/// * A capitalized name (type or variant) is renamed at every whole-word code occurrence — field
611///   and local names are lowercase, so a capitalized collision can only ever mean the type.
612/// * A lowercase name (function) is renamed only where it names the FUNCTION: its `## To` header,
613///   a call `name(`, `Call name`, and a spawn `task to name`. A stdlib local or field that happens
614///   to share the name (`pi`, `gamma`, `cookie`) is a different entity and is left alone; the
615///   stdlib never passes its own functions as values (locked by `stdlib_user_name_hygiene`).
616///
617/// String literals are opaque except for `{…}` interpolation holes, which are code. Char literals
618/// (`` `"` ``) are opaque.
619fn rename_for_hygiene(code: &str, renames: &std::collections::HashMap<String, String>) -> String {
620    if renames.is_empty() {
621        return code.to_string();
622    }
623    let bytes = code.as_bytes();
624    let mut out = String::with_capacity(code.len() + renames.len() * 16);
625    let mut copied = 0;
626    let mut in_string = false;
627    let mut interp_depth = 0usize;
628    let mut i = 0;
629    while i < bytes.len() {
630        let b = bytes[i];
631        if in_string && interp_depth == 0 {
632            match b {
633                b'\\' => i += 2,
634                b'"' => {
635                    in_string = false;
636                    i += 1;
637                }
638                b'{' if bytes.get(i + 1) == Some(&b'{') => i += 2,
639                b'{' => {
640                    interp_depth = 1;
641                    i += 1;
642                }
643                _ => i += 1,
644            }
645            continue;
646        }
647        if interp_depth > 0 {
648            match b {
649                b'{' => {
650                    interp_depth += 1;
651                    i += 1;
652                    continue;
653                }
654                b'}' => {
655                    interp_depth -= 1;
656                    i += 1;
657                    continue;
658                }
659                _ => {}
660            }
661        } else {
662            match b {
663                b'"' => {
664                    in_string = true;
665                    i += 1;
666                    continue;
667                }
668                b'`' => {
669                    let close = code[i + 1..].find(|c| c == '`' || c == '\n');
670                    i = match close {
671                        Some(off) if bytes[i + 1 + off] == b'`' => i + off + 2,
672                        _ => i + 1,
673                    };
674                    continue;
675                }
676                _ => {}
677            }
678        }
679        let starts_ident =
680            (b.is_ascii_alphabetic() || b == b'_') && (i == 0 || !is_ident_byte(bytes[i - 1]));
681        if !starts_ident {
682            i += 1;
683            continue;
684        }
685        let start = i;
686        while i < bytes.len() && is_ident_byte(bytes[i]) {
687            i += 1;
688        }
689        let word = &code[start..i];
690        let Some(hidden) = renames.get(word) else {
691            continue;
692        };
693        let names_the_definition = if word.starts_with(|c: char| c.is_ascii_uppercase()) {
694            true
695        } else {
696            let line_start = code[..start].rfind('\n').map(|p| p + 1).unwrap_or(0);
697            let header_name = fn_section_name(&code[line_start..]);
698            let mut before = code[..start].trim_end().rsplit(char::is_whitespace);
699            let prev = before.next();
700            bytes.get(i) == Some(&b'(')
701                || (header_name.as_deref() == Some(word)
702                    && code[line_start..start].trim_start().starts_with("## To "))
703                || prev == Some("Call")
704                || (prev == Some("to") && before.next() == Some("task"))
705        };
706        if names_the_definition {
707            out.push_str(&code[copied..start]);
708            out.push_str(hidden);
709            copied = i;
710        }
711    }
712    out.push_str(&code[copied..]);
713    out
714}
715
716/// The full embedded prelude — every module's CODE concatenated (what
717/// [`apply_prelude`] prepends), documentation notes stripped. Identical bytes
718/// on every target (`include_str!` is compile-time).
719pub fn prelude() -> String {
720    PRELUDE_MODULES
721        .iter()
722        .map(|src| strip_note_blocks(module_code(src)))
723        .collect::<Vec<_>>()
724        .join("\n\n")
725}
726
727/// The RAW embedded stdlib module sources, `## Note` documentation included —
728/// the seam the LSP reads literate docs from (`teach::extract_literate_docs`).
729pub fn prelude_module_sources() -> &'static [&'static str] {
730    &PRELUDE_MODULES
731}
732
733/// Every identifier the prelude defines (across all modules) — derived from the modules.
734pub fn prelude_vocabulary() -> Vec<String> {
735    PRELUDE_NAMES
736        .iter()
737        .flat_map(|names| names.iter().map(|n| n.to_string()))
738        .collect()
739}
740
741/// Module `idx`'s code as the prelude splices it, rebuilt from the source runs the build script found
742/// ([`crate::stdlib_text::spliced_code`]).
743fn spliced_module(idx: usize) -> String {
744    let source = PRELUDE_MODULES[idx];
745    let runs = PRELUDE_SPLICE[idx];
746    let mut code = String::with_capacity(runs.iter().map(|&(s, e)| (e - s) as usize).sum());
747    for &(s, e) in runs {
748        code.push_str(&source[s as usize..e as usize]);
749    }
750    code
751}
752
753/// One run of [`apply_prelude`]'s output tied back to where it came from:
754/// `user_start` is the byte offset of an untouched run of the caller's own
755/// text, `None` marks spliced stdlib text. Downstream span translation
756/// (deep check) inverts the prelude edit exactly through these runs.
757#[derive(Debug, Clone, Copy, PartialEq, Eq)]
758pub struct PreludeSegment {
759    pub out_start: usize,
760    pub len: usize,
761    pub user_start: Option<usize>,
762}
763
764/// Prepend the stdlib modules a program actually uses. Returns the source
765/// unchanged when the program references no stdlib vocabulary or opts out with
766/// `## NoPrelude` (in which case the opt-out marker is stripped so it never
767/// reaches the parser). This is the auto-import seam for both the interpreter and
768/// the compiler.
769pub fn apply_prelude(source: &str) -> std::borrow::Cow<'_, str> {
770    apply_prelude_mapped(source).0
771}
772
773/// [`apply_prelude`] plus the exact edit it performed, as ordered output runs.
774/// A consumer that parses the expanded text and reports spans against the
775/// USER's buffer must translate through these segments rather than assume the
776/// modules were prepended: they are spliced AFTER any leading title/comment
777/// prose, and `## NoPrelude` REMOVES its marker lines.
778pub fn apply_prelude_mapped(source: &str) -> (std::borrow::Cow<'_, str>, Vec<PreludeSegment>) {
779    if let Some((stripped, segments)) = strip_no_prelude(source) {
780        return (std::borrow::Cow::Owned(stripped), segments);
781    }
782    // "Declarer wins", PER NAME. A module is spliced when something needs one of its names that
783    // the program does not declare itself; the program's declaration of any OTHER name of that
784    // module never costs it the module. A name the program declares (a top-level `## To`/`## A`,
785    // or a local closure — a call reaches a function before a local) is its own at every call it
786    // writes, and the spliced library copy of that name is renamed out of the way
787    // ([`rename_for_hygiene`]), so library code keeps calling the library's version. A name the
788    // program binds as a plain VALUE coexists with the function and only stops counting as a use
789    // unless it is called. The rule stays idempotent: a source already carrying a module's
790    // definitions declares every name that module could be needed for, so it is left untouched
791    // and the AOT hot path stays byte-identical.
792    let locals = local_bindings(source);
793    let user_defined: std::collections::HashSet<String> = defined_names(source)
794        .into_iter()
795        .chain(locals.callables)
796        .collect();
797    let user_values = locals.values;
798    // Every scan below finds a name only as a whole word, so a name the program never writes as
799    // one is decided without reading the program again.
800    let words = whole_words(source);
801    let demanded_by_program = |n: &str| {
802        if !may_name(&words, n) {
803            false
804        } else if user_values.iter().any(|v| v == n) {
805            references_call_only(source, n) || references_as_filter(source, n)
806        } else {
807            references(source, n)
808        }
809    };
810    // TRANSITIVE references: a stdlib fn calling ANOTHER module's .lg fn (statistics.lg's
811    // `fsumReal` → math.lg's `absReal`, or `geometricMeanReal` → `ln`/`exp`). A single
812    // non-fixpoint pass over the PROGRAM's references alone splices statistics.lg but NOT math.lg,
813    // leaving the transitive dependency an `Unknown function` on every tier. The fixpoint keeps
814    // selecting a module whose name is referenced by the program OR by any already-selected module
815    // (`PRELUDE_PULLS`, which the build script reads off each module's spliced code), until nothing
816    // new is pulled — so a stdlib fn may freely call another module's fn. `builtin_backed` names
817    // (sqrt, pow, …) resolve without a module, which is why only the non-builtin `.lg` deps
818    // regressed.
819    // Statement desugars reference stdlib names that never appear TEXTUALLY: `Solve … for x.`
820    // lowers to `solveLinear`, `Minimize … over x.` to `minimizeQuadratic` (R4). The demand
821    // scan must see through the sugar or every tier reports an unknown function.
822    let mut virtual_refs: Vec<&'static str> = Vec::new();
823    if source.lines().any(|l| l.trim_start().starts_with("Solve ")) {
824        virtual_refs.push("solveLinear");
825    }
826    if source
827        .lines()
828        .any(|l| l.trim_start().starts_with("Minimize "))
829    {
830        virtual_refs.push("minimizeQuadratic");
831    }
832    // A `## Route GET /todos/:id` lowers to a dispatcher that matches the pattern and pulls the
833    // named segment out — `matchRoute`/`routeParam`, from web.lg. Neither name appears in the
834    // user's source: the header IS the reference. Without this the router is synthesized calling
835    // functions the program never loaded, and every routed page dies with "Unknown function:
836    // matchRoute" — a failure in generated code the author cannot see, naming a function they
837    // never wrote. Literal-path routes need neither, so the trigger is a `:` segment.
838    if source
839        .lines()
840        .any(|l| l.trim_start().starts_with("## Route ") && l.contains("/:"))
841    {
842        virtual_refs.push("matchRoute");
843        virtual_refs.push("routeParam");
844        virtual_refs.push("isIntText");
845    }
846    // ★ AND A `## Page /posts/:id` IS THE SAME SENTENCE ON THE OTHER TIER. Its `:name` segments
847    // lower to the identical `routeParam(pattern, name, routePath())` binding, written by the
848    // compiler from the header, so the demand scan cannot see it either. This is the third time
849    // this exact shape has been paid for (`htmlEscape`, then `## Route`, now `## Page`): a
850    // reference the COMPILER writes is invisible to a scan that reads the SOURCE.
851    if source
852        .lines()
853        .any(|l| l.trim_start().starts_with("## Page ") && l.contains("/:"))
854    {
855        virtual_refs.push("matchRoute");
856        virtual_refs.push("routeParam");
857    }
858    // ★ `Load "k" into f.` READS A TAG OFF THE STORED TEXT, through `cutAfter` — a call the
859    // COMPILER writes from the sentence, so the scan that reads the author's tokens cannot see it.
860    // Fifth instance of this exact shape (`htmlEscape`, `## Route`, `## Page`, the key modifiers,
861    // now this): a reference the compiler writes must be declared at every stage that reasons
862    // about reachability, or the program dies with `Unknown function` in generated code naming
863    // something the author never wrote.
864    // ★ `Add class …` / `Remove class …` DECIDE WHICH CLASS WORDS SURVIVE in compiled LOGOS, so
865    // the lowering names two web.lg functions the author never wrote. Seventh instance of this
866    // shape — a reference the compiler writes must be declared at every stage that reasons about
867    // reachability, or the page dies with `Unknown function` naming something nobody typed.
868    if source.lines().any(|l| {
869        let l = l.trim_start();
870        l.starts_with("Add class ") || l.starts_with("Remove class ")
871    }) {
872        virtual_refs.push("classListWith");
873        virtual_refs.push("classListWithout");
874    }
875    if source.lines().any(|l| l.trim_start().starts_with("Load ")) {
876        virtual_refs.push("cutAfter");
877        // A `Bool` field decodes through convert.lg. `parseInt`/`parseFloat` are builtins and need
878        // no declaring; this one is compiled LOGOS, so it does.
879        virtual_refs.push("parseBool");
880    }
881    // ★ A PAGE RENDERS THROUGH vdom.lg: every component lowers to tape calls, a commit and the
882    // sites it finds its nodes by — all written by the compiler, none in the author's source.
883    if renders_a_page(source) {
884        virtual_refs.push("vdCommit");
885    }
886    // A URL-valued attribute a paint computes goes through `safeUrl` — see [`computes_a_url`].
887    if renders_a_page(source) && computes_a_url(source) {
888        virtual_refs.push("safeUrl");
889    }
890    // A key modifier or a key trigger gates on which key was pressed, comparing case-insensitively
891    // through `lower` — see [`uses_a_key_gate`].
892    if uses_a_key_gate(source) {
893        virtual_refs.push("lower");
894    }
895    if declares_a_convergent_shared_field(source) {
896        virtual_refs.push("randomInt");
897    }
898    // A `## Session` synthesizes a global, a payload encoder and the two functions that move it
899    // to and from a signed cookie — none of whose names the author ever types. The header IS the
900    // reference, exactly as it is for `## Route`'s `matchRoute`.
901    if source.lines().any(|l| l.trim_start() == "## Session") {
902        for f in [
903            "sessionSecret",
904            "hexText",
905            "sessionField",
906            "sessionInt",
907            "sessionBool",
908            "signSession",
909            "verifySession",
910            "cookieOf",
911            "withCookie",
912            // The router checks CSRF itself for a state-changing request, and `csrf()` mints the
913            // token a form carries — none of these names is typed by the author either.
914            "csrfToken",
915            "csrfValid",
916            "randomSecret",
917            "bodyParam",
918            "headerOf",
919            "upper",
920        ] {
921            virtual_refs.push(f);
922        }
923    }
924    // EVERY dispatcher splits the URL it is handed into a path and a query before it matches
925    // anything, so these are needed by a literal-path route, a lone `## Redirect` and a file
926    // whose only server header is a middleware guard — all three synthesize the same walk.
927    if source.lines().any(|l| {
928        let l = l.trim_start();
929        l.starts_with("## Route ")
930            || l.starts_with("## Redirect ")
931            || l.starts_with("## Before each request")
932    }) {
933        virtual_refs.push("pathOf");
934        virtual_refs.push("queryString");
935        // The synthesized handler reads the matched answer's `Location` out of its headers to tell
936        // the router's own moved answer from a route that redirected itself, and `routeHeader`
937        // reads any header by name. Neither name appears in the author's source.
938        virtual_refs.push("headerIn");
939        virtual_refs.push("queryParam");
940        virtual_refs.push("urlDecode");
941        virtual_refs.push("hexDigitValue");
942        // The synthesized `Request -> Response` a bare `Serve on port N.` serves with: it rebuilds
943        // a moved answer through `redirectTo`, so the reply constructors come with the table.
944        virtual_refs.push("redirectTo");
945        virtual_refs.push("permanentRedirectTo");
946        virtual_refs.push("cutAfter");
947        virtual_refs.push("bodyParam");
948
949        virtual_refs.push("jsonIsNull");
950    }
951    // A derived `toJson_<T>` escapes its Text fields with `jsonQuote` (json.lg). The derive runs
952    // AFTER parsing, so the name never appears in the user's source — calling the encoder is the
953    // reference. Keyed on the CALL rather than on "this file declares a record", so a program
954    // that never serialises anything does not drag in the JSON module.
955    // A plain substring test, not `references`: that helper requires a WHOLE-WORD match, and
956    // `toJson_` is by construction a PREFIX of the real name (`toJson_Todo`), so it could never
957    // match one.
958    // …and a `## Route` that answers a RECORD is wrapped in that record's encoder by the router
959    // lowering, so `toJson_` never appears in the source either — the ROUTE is the reference. A
960    // routed program is a server; pulling in the JSON module for one is the right trade against
961    // a page that dies on its first typed response.
962    // A TYPED FETCH (`Get "/api/todo" as Todo, then loaded.`) decodes its answer through the
963    // derived decoder, so it needs the JSON module — and its `as` clause is the only reference,
964    // since the decoder's name is written by the compiler rather than by the author.
965    // ★ An `Upload` frames its body as `multipart/form-data` through these — names the compiler
966    // writes, never the author, so the demand keys on the SENTENCE.
967    let has_upload = source
968        .lines()
969        .any(|l| l.trim_start().starts_with("Upload "));
970    if has_upload {
971        virtual_refs.push("multipartBody");
972        virtual_refs.push("multipartContentType");
973        virtual_refs.push("multipartBoundary");
974    }
975    let has_typed_fetch = source.lines().any(|l| {
976        let t = l.trim_start();
977        ["Get ", "Post ", "Put ", "Patch ", "Delete ", "Upload "]
978            .iter()
979            .any(|v| t.starts_with(v))
980            && t.contains(" as ")
981            && t.contains("then")
982    });
983    // The DECODER pulls in more of json.lg than the encoder does — it parses the text and reads
984    // fields back off the tree — so it names those entry points as its own demand.
985    //
986    // `Save`/`Load` (any field) and a `## Store` (any mode) route a `Seq`/record field through the
987    // SAME derived codec (`parser/lgx_lower/{json,stores,elements}.rs`), and the encoder/decoder
988    // names it calls (`toJsonSeq_<T>`, `fromJson_<T>`, …) are exactly as compiler-written as a
989    // typed fetch's own — never present in the author's source for the JSON module to be pulled in
990    // by the checks above. Keyed on the SENTENCE/HEADER (a plain scalar `Save`/`Load`/store field
991    // never calls any of these, so this is conservative the same way `has_typed_fetch` already is)
992    // rather than on whether a field is ACTUALLY a `Seq`/record, since that answer needs the parse
993    // this prelude splice runs before.
994    let has_save_or_load = source.lines().any(|l| {
995        let t = l.trim_start();
996        t.starts_with("Save ") || t.starts_with("Load ")
997    });
998    let has_store = source
999        .lines()
1000        .any(|l| l.trim_start().starts_with("## Store"));
1001    if source.contains("toJson_")
1002        || source.contains("fromJson")
1003        || has_typed_fetch
1004        || has_save_or_load
1005        || has_store
1006        || source
1007            .lines()
1008            .any(|l| l.trim_start().starts_with("## Route "))
1009    {
1010        virtual_refs.push("jsonQuote");
1011    }
1012    if source.contains("fromJson") || has_typed_fetch || has_save_or_load || has_store {
1013        virtual_refs.push("jsonTryParse");
1014        virtual_refs.push("jsonSerialize");
1015        virtual_refs.push("jsonGet");
1016        virtual_refs.push("jsonInt");
1017        virtual_refs.push("jsonBool");
1018        virtual_refs.push("jsonString");
1019        // A `Seq` field's own encoder/decoder (`toJsonSeq_<T>`/`fromJsonSeq_<T>`) reads the
1020        // document as an ARRAY — the one json.lg entry point neither a bare typed fetch of a
1021        // record nor a route ever needed before a `Seq` payload existed on this path.
1022        virtual_refs.push("jsonArray");
1023    }
1024    let mut selected = vec![false; PRELUDE_MODULES.len()];
1025    loop {
1026        let mut added = false;
1027        // ★ `text_from_bytes` IS THE REFERENCE, and the author never types the name it needs.
1028        // The builtin must answer alike on every tier when the bytes are not valid UTF-8 — the
1029        // tree-walker and VM raise `text_from_bytes(): invalid UTF-8` and the AOT tier panics with
1030        // it — so the standalone wasm module has to trap too. It has no runtime to ask, so it CALLS
1031        // the rules, which are already written in LOGOS as `strings.lg`'s `validUtf8`. Fourth
1032        // instance of the compiler-written-reference shape after `htmlEscape`, `## Route` and
1033        // `## Page`; the first one keyed on a BUILTIN rather than on a header.
1034        //
1035        // Keyed on the selected modules too, not just the author's source: `encoding.lg`'s
1036        // `fromHex`, `json.lg`, `session.lg` and six others call `text_from_bytes` themselves, so a
1037        // program that only ever writes `fromHex(s)` reaches it without naming it once.
1038        if !virtual_refs.contains(&"validUtf8")
1039            && (source.contains("text_from_bytes")
1040                || (0..PRELUDE_MODULES.len())
1041                    .any(|j| selected[j] && PRELUDE_MENTIONS_TEXT_FROM_BYTES[j]))
1042        {
1043            virtual_refs.push("validUtf8");
1044            added = true;
1045        }
1046        for idx in 0..PRELUDE_MODULES.len() {
1047            if selected[idx] {
1048                continue;
1049            }
1050            let names = PRELUDE_NAMES[idx];
1051            // The two collisions hygiene cannot rename keep "declarer wins" at module grain: a
1052            // builtin-backed type (its declaration is stripped — the engine owns the name) and a
1053            // native (bound to its runtime implementation BY NAME on every tier).
1054            let natives = PRELUDE_NATIVES[idx];
1055            if names
1056                .iter()
1057                .any(|n| user_defined.contains(*n) && (builtin_backed(n) || natives.contains(n)))
1058            {
1059                continue;
1060            }
1061            let referenced = (0..PRELUDE_MODULES.len())
1062                .any(|j| selected[j] && PRELUDE_PULLS[j].contains(&(idx as u8)))
1063                || names.iter().any(|n| {
1064                    !builtin_backed(n)
1065                        && !user_defined.contains(*n)
1066                        && (demanded_by_program(n) || virtual_refs.contains(n))
1067                });
1068            if referenced {
1069                selected[idx] = true;
1070                added = true;
1071            }
1072        }
1073        if !added {
1074            break;
1075        }
1076    }
1077    let renames: std::collections::HashMap<String, String> = (0..PRELUDE_MODULES.len())
1078        .filter(|&idx| selected[idx])
1079        .flat_map(|idx| PRELUDE_NAMES[idx].iter())
1080        .filter(|n| user_defined.contains(**n))
1081        .map(|n| (n.to_string(), hygienic_name(n)))
1082        .collect();
1083    let needed: Vec<String> = (0..PRELUDE_MODULES.len())
1084        .filter(|&idx| selected[idx])
1085        .map(|idx| {
1086            let code = spliced_module(idx);
1087            if renames.is_empty() {
1088                code
1089            } else {
1090                rename_for_hygiene(&code, &renames)
1091            }
1092        })
1093        .collect();
1094    if needed.is_empty() {
1095        let segments = if source.is_empty() {
1096            Vec::new()
1097        } else {
1098            vec![PreludeSegment {
1099                out_start: 0,
1100                len: source.len(),
1101                user_start: Some(0),
1102            }]
1103        };
1104        (std::borrow::Cow::Borrowed(source), segments)
1105    } else {
1106        // Splice the modules in AFTER any leading title/comment prose (`# Title`,
1107        // `--` notes) and BEFORE the program's first `##` section. The lexer only
1108        // skips leading prose at the very start of a program, so prepending the
1109        // modules would push a user header into the middle of the assembled
1110        // source, where its `--` lines are a parse error.
1111        let insert_at = if source.starts_with("##") {
1112            0
1113        } else {
1114            source.find("\n##").map(|i| i + 1).unwrap_or(0)
1115        };
1116        let (head, tail) = source.split_at(insert_at);
1117        let mut out =
1118            String::with_capacity(source.len() + needed.iter().map(|m| m.len() + 2).sum::<usize>());
1119        out.push_str(head);
1120        for module in &needed {
1121            out.push_str(module);
1122            out.push_str("\n\n");
1123        }
1124        let spliced_len = out.len() - head.len();
1125        out.push_str(tail);
1126        let mut segments = Vec::with_capacity(3);
1127        if !head.is_empty() {
1128            segments.push(PreludeSegment {
1129                out_start: 0,
1130                len: head.len(),
1131                user_start: Some(0),
1132            });
1133        }
1134        segments.push(PreludeSegment {
1135            out_start: head.len(),
1136            len: spliced_len,
1137            user_start: None,
1138        });
1139        if !tail.is_empty() {
1140            segments.push(PreludeSegment {
1141                out_start: head.len() + spliced_len,
1142                len: tail.len(),
1143                user_start: Some(insert_at),
1144            });
1145        }
1146        (std::borrow::Cow::Owned(out), segments)
1147    }
1148}
1149
1150/// Like [`references`] but ONLY counts a genuine CALL (`name(`), never a bare mention in a use
1151/// position (`to words`, a type annotation, prose). Drives the C reachability tree-shake: a
1152/// program whose *variable* shares a stdlib function's name (`Let words be …`, `Push x to words`)
1153/// must NOT drag that function in — on the C backend it would be emitted, collide, and even absorb
1154/// the caller's body. A function genuinely passed as a value (rare, higher-order) that this misses
1155/// surfaces as a loud `undefined reference`, never a silent miscompile.
1156fn references_call_only(source: &str, name: &str) -> bool {
1157    if name.is_empty() {
1158        return false;
1159    }
1160    let sb = source.as_bytes();
1161    let mut from = 0;
1162    while let Some(off) = source[from..].find(name) {
1163        let start = from + off;
1164        let end = start + name.len();
1165        from = start + 1;
1166        if start > 0 && is_ident_byte(sb[start - 1]) {
1167            continue;
1168        }
1169        if end < sb.len() && is_ident_byte(sb[end]) {
1170            continue;
1171        }
1172        // Expression call `name(...)`.
1173        if end < sb.len() && sb[end] == b'(' {
1174            return true;
1175        }
1176        // Statement call `Call name with …` — `Call` is unambiguously an invocation (unlike
1177        // `to`/`of`/`the`/`a`, which also precede plain variables and caused the false trigger).
1178        if source[..start]
1179            .trim_end()
1180            .rsplit(char::is_whitespace)
1181            .next()
1182            == Some("Call")
1183        {
1184            return true;
1185        }
1186        // Concurrency spawn `Launch a task to name [with …]` — the function is named after `task to`,
1187        // so the two preceding words are unambiguously `task to`. Without this the C tree-shaker would
1188        // prune a spawned-only function (its body reached solely through `Launch`), leaving a dangling
1189        // `(void*)name` at the spawn site.
1190        let mut before = source[..start].trim_end().rsplit(char::is_whitespace);
1191        if before.next() == Some("to") && before.next() == Some("task") {
1192            return true;
1193        }
1194        // A function a real number is defined by, `the real number whose digits in base 10 are name` /
1195        // `the real number approximated by name`: the phrase reads the function whenever a refinement
1196        // of the number asks.
1197        if names_a_defining_function(source, start) {
1198            return true;
1199        }
1200        // A value handed to a function, `Show x to name.` / `Give x to name.`: the recipient closes a
1201        // sentence that opens with `Show` or `Give`. A bare `to` is not enough — `Set x to name.`
1202        // names a variable.
1203        let after = source[end..].trim_start_matches([' ', '\t']);
1204        if source[..start].trim_end().ends_with(" to")
1205            && (after.starts_with('.') || after.is_empty())
1206        {
1207            let line_start = source[..start].rfind('\n').map_or(0, |i| i + 1);
1208            let opener = source[line_start..start].split_whitespace().next();
1209            if matches!(opener, Some("Show" | "Give")) {
1210                return true;
1211            }
1212        }
1213    }
1214    false
1215}
1216
1217/// Whether the name at `start` closes a defined-real phrase outside a text literal: the words before it
1218/// end `the real number whose digits in base <k> are` or `the real number approximated by`.
1219fn names_a_defining_function(source: &str, start: usize) -> bool {
1220    let line_start = source[..start].rfind('\n').map_or(0, |i| i + 1);
1221    let quotes = source[line_start..start].bytes().filter(|&b| b == b'"').count();
1222    if quotes % 2 == 1 {
1223        return false;
1224    }
1225    let mut before: Vec<&str> = source[line_start..start].split_whitespace().rev().take(9).collect();
1226    before.reverse();
1227    let opens = |the: &str, real: &str, number: &str| {
1228        the.eq_ignore_ascii_case("the") && real == "real" && number == "number"
1229    };
1230    match before.as_slice() {
1231        [.., the, real, number, "whose", "digits", "in", "base", _, "are"] => opens(the, real, number),
1232        [.., the, real, number, "approximated", "by"] => opens(the, real, number),
1233        _ => false,
1234    }
1235}
1236
1237/// The functions of an assembled program that ARE the standard library's definitions: those whose
1238/// `## To` section is byte-identical to the section the library itself ships under that name.
1239///
1240/// This is provenance by content, and it is what licenses every name-keyed lowering of a library
1241/// function (the Rust tier's memchr `indexOf`, its AVX2 `trunc`, …): such a lowering encodes what
1242/// the LIBRARY's body computes, so it may replace a call only when the callee is that body. A
1243/// program's own function of the same name — the program's definition wins — never qualifies, and
1244/// neither does anything a program merely spells like the library. Sound by construction: a
1245/// program that copies a library section verbatim computes exactly what the lowering computes.
1246pub fn library_owned_functions(assembled: &str) -> std::collections::HashSet<String> {
1247    function_section_ranges(assembled)
1248        .into_iter()
1249        .filter(|(name, range)| library_section(name) == Some(&assembled[range.clone()]))
1250        .map(|(name, _)| name)
1251        .collect()
1252}
1253
1254/// The `## To name` section the library ships, trimmed, when it ships one.
1255fn library_section(name: &str) -> Option<&'static str> {
1256    let at = LIBRARY_SECTIONS
1257        .binary_search_by(|&(n, ..)| n.cmp(name))
1258        .ok()?;
1259    let (_, module, start, end) = LIBRARY_SECTIONS[at];
1260    Some(&PRELUDE_MODULES[module as usize][start as usize..end as usize])
1261}
1262
1263thread_local! {
1264    /// The functions of the program being compiled that ARE the standard library's own definitions
1265    /// ([`crate::loader::library_owned_functions`]). A lowering keyed on a library function's NAME
1266    /// (the Rust tier's memchr `indexOf`, native-width `rotateLeft`, AVX2 `trunc`; the interpreters' native `pbkdf2Sha256`) encodes what the library's body
1267    /// computes, so it may only replace a call whose callee is that body — never a program's own
1268    /// function spelled the same. Empty outside a [`LibraryProvenance`] scope: an entry that forgets
1269    /// to establish provenance loses the lowering, it can never hijack a program's function.
1270    static LIBRARY_FUNCTIONS: std::cell::RefCell<std::rc::Rc<std::collections::HashSet<String>>> =
1271        std::cell::RefCell::new(std::rc::Rc::new(std::collections::HashSet::new()));
1272}
1273
1274/// Establishes, for the compilation or execution that runs while it lives, which functions of the program are the
1275/// standard library's definitions. Restores the enclosing provenance on drop, so nested and
1276/// sequential compiles on one thread never see each other's program.
1277pub struct LibraryProvenance {
1278    previous: std::rc::Rc<std::collections::HashSet<String>>,
1279    owned: std::rc::Rc<std::collections::HashSet<String>>,
1280}
1281
1282impl LibraryProvenance {
1283    /// Enter the provenance of `assembled` — the exact text the codegen's AST was parsed from.
1284    pub fn of(assembled: &str) -> Self {
1285        let owned = std::rc::Rc::new(library_owned_functions(assembled));
1286        let previous =
1287            LIBRARY_FUNCTIONS.with(|c| std::mem::replace(&mut *c.borrow_mut(), owned.clone()));
1288        LibraryProvenance { previous, owned }
1289    }
1290
1291    /// The program's functions that are the standard library's own definitions.
1292    pub fn functions(&self) -> &std::collections::HashSet<String> {
1293        &self.owned
1294    }
1295}
1296
1297impl Drop for LibraryProvenance {
1298    fn drop(&mut self) {
1299        let previous = std::mem::take(&mut self.previous);
1300        LIBRARY_FUNCTIONS.with(|c| *c.borrow_mut() = previous);
1301    }
1302}
1303
1304/// Is `name` the standard library's own definition in the program being compiled?
1305pub fn is_library_function(name: &str) -> bool {
1306    LIBRARY_FUNCTIONS.with(|c| c.borrow().contains(name))
1307}
1308
1309/// Does `source` apply `name` as a template FILTER (`{price | money}`)? A filter is a call written
1310/// left to right, so it is a use of the function even where the same word is also a local value.
1311fn references_as_filter(source: &str, name: &str) -> bool {
1312    if name.is_empty() {
1313        return false;
1314    }
1315    let sb = source.as_bytes();
1316    let mut from = 0;
1317    while let Some(off) = source[from..].find(name) {
1318        let start = from + off;
1319        let end = start + name.len();
1320        from = start + 1;
1321        if (start > 0 && is_ident_byte(sb[start - 1])) || (end < sb.len() && is_ident_byte(sb[end]))
1322        {
1323            continue;
1324        }
1325        let prefix = source[..start].trim_end();
1326        if prefix.ends_with('|') && !source[prefix.len()..start].contains('\n') {
1327            return true;
1328        }
1329    }
1330    false
1331}
1332
1333/// Drop top-level `## To …` function definitions that are UNREACHABLE from the program's entry,
1334/// keeping every non-function section (`## A` structs, `## Main`, prose) and every function whose
1335/// name is transitively called. This is the C backends' tree-shake: a flat C namespace can't
1336/// tolerate emitting an *unused* stdlib function that either collides with a libc name or exercises
1337/// a C-codegen gap the function is never actually reached through (the Rust backend tolerates both,
1338/// so this is C-only).
1339///
1340/// Reachability is seeded from the entry sections of `spliced` (the prelude-spliced source) and from
1341/// every function a post-parse lowering calls — a `## Route` dispatcher's `pathOf`, a derived codec's
1342/// `jsonQuote` — which `synthesized_prelude_roots` reads off `user_source`, the author's own text.
1343/// Those calls are written by the compiler, so no scan of the source can see them; a pruner that
1344/// dropped them would leave the lowering calling a function that is gone, which the bytecode compiler
1345/// turns into an `Unknown function` failure at run time.
1346pub fn keep_reachable_functions(user_source: &str, spliced: &str) -> String {
1347    // 1. Split into `## `-delimited sections, preserving exact text + order.
1348    let mut sections: Vec<String> = Vec::new();
1349    for line in spliced.split_inclusive('\n') {
1350        if line.starts_with("## ") || sections.is_empty() {
1351            sections.push(String::new());
1352        }
1353        sections.last_mut().unwrap().push_str(line);
1354    }
1355    let names: Vec<Option<String>> = sections.iter().map(|s| fn_section_name(s)).collect();
1356    let fn_names: Vec<&str> = names.iter().filter_map(|n| n.as_deref()).collect();
1357    if fn_names.is_empty() {
1358        return spliced.to_string();
1359    }
1360    // 2. Seed reachable from every NON-function section (Main, structs, prose).
1361    let root: String = sections
1362        .iter()
1363        .zip(&names)
1364        .filter(|(_, n)| n.is_none())
1365        .map(|(s, _)| s.as_str())
1366        .collect();
1367    let synthesized = synthesized_prelude_roots(user_source);
1368    let mut reachable: std::collections::HashSet<&str> = std::collections::HashSet::new();
1369    for &name in &fn_names {
1370        if references_call_only(&root, name) || synthesized.iter().any(|s| s == name) {
1371            reachable.insert(name);
1372        }
1373    }
1374    // 3. Fixpoint: a reachable function pulls in every function its body references.
1375    loop {
1376        let mut added = false;
1377        for (s, n) in sections.iter().zip(&names) {
1378            let Some(nm) = n.as_deref() else { continue };
1379            if !reachable.contains(nm) {
1380                continue;
1381            }
1382            for &cand in &fn_names {
1383                if !reachable.contains(cand) && references_call_only(s, cand) {
1384                    reachable.insert(cand);
1385                    added = true;
1386                }
1387            }
1388        }
1389        if !added {
1390            break;
1391        }
1392    }
1393    // 4. Keep non-function sections + reachable function sections, in original order.
1394    let mut out = String::with_capacity(spliced.len());
1395    for (s, n) in sections.iter().zip(&names) {
1396        match n {
1397            Some(nm) if !reachable.contains(nm.as_str()) => {}
1398            _ => out.push_str(s),
1399        }
1400    }
1401    out
1402}
1403
1404/// Drop ONLY the auto-imported stdlib PRELUDE functions that are never reachable, keeping EVERY
1405/// user-defined function untouched. This is the chip-encoder analog of [`keep_reachable_functions`], but
1406/// safe for LOGOS's non-`name(` call forms: `apply_prelude` splices a WHOLE module when the program mentions
1407/// any of its names, so an UNCALLED prelude helper that reaches a host builtin (`parseFloat`, `format`, …)
1408/// would make the flat chip image reject even though it never runs. This prunes those dead prelude helpers
1409/// so the encoder lowers only what the program executes — with two safety differences from the C tree-shake:
1410///   • it NEVER drops a user function (the prune set is exactly the prelude vocabulary), so a user procedure
1411///     invoked by a LOGOS call form the call-only scan misses (`Launch a task to worker`, higher-order
1412///     `apply(f, …)`) is always kept;
1413///   • reachability uses the PERMISSIVE `references` (any use position — the same predicate `apply_prelude`
1414///     splices on), so a prelude function reached via `to <fn>` / `of <fn>` / a value position is retained.
1415/// The output is byte-identical to the input when nothing is pruned (no prelude, or all reachable), so the
1416/// AOT/other hot paths are untouched. Over-pruning can only ever surface as a LOUD undefined reference.
1417pub fn prune_unreachable_prelude(source: &str) -> String {
1418    prune_unreachable_prelude_mapped(source).0
1419}
1420
1421/// [`prune_unreachable_prelude`] told which names the USER's own (pre-prelude) source declares, so a
1422/// name the stdlib also has is recognized as the user's and kept. Callers that have the original
1423/// source should prefer this; the bare form behaves as before.
1424pub fn prune_unreachable_prelude_from(user_source: &str, spliced: &str) -> String {
1425    prune_unreachable_prelude_mapped_from(user_source, spliced).0
1426}
1427
1428/// [`prune_unreachable_prelude_from`] with the byte ranges of `spliced` it kept, as
1429/// [`prune_unreachable_prelude_mapped`] reports them — for a caller that maps offsets in the pruned
1430/// text back, and must still prune exactly as a build does.
1431pub fn prune_unreachable_prelude_mapped_from(
1432    user_source: &str,
1433    spliced: &str,
1434) -> (String, Vec<(usize, usize)>) {
1435    let mut declared = defined_names(user_source);
1436    // ★ ROOTS A POST-PARSE LOWERING WILL CALL, which the source text cannot show.
1437    //
1438    // `apply_prelude` already understands these — a page demands vdom.lg's calls, a `## Route`
1439    // demands the router's helpers — but this pruner runs on the SOURCE and keeps only what the
1440    // source NAMES. So it dropped the very function the demand had just pulled in, and the
1441    // lowering then emitted a call to a name that was gone. (`Unknown function: htmlEscape`,
1442    // from AOT-Rust; the tree-walker survived it because it resolves lazily, which is exactly
1443    // how a gap like this stays hidden on the reference tier.)
1444    //
1445    // Same shape as the demand itself, one stage later: a construct whose reference to a stdlib
1446    // function is written BY THE COMPILER has to declare that reference at every stage that
1447    // reasons about reachability.
1448    declared.extend(synthesized_prelude_roots(user_source));
1449    let refs: Vec<&str> = declared.iter().map(|s| s.as_str()).collect();
1450    prune_unreachable_prelude_mapped_with(spliced, &refs)
1451}
1452
1453/// Does a `## Store … shared on "…"` declare, in its own `State:`, a field that converges as a CRDT
1454/// (`Let likes: Tally be 0.`)? Such a store draws its page's replica id through `randomInt` — a call
1455/// the lowering writes (`lgx_lower::shared`), once per page and only for a converging store, so a
1456/// shared store of plain values, a store that is not shared, and a convergent field elsewhere demand
1457/// nothing. The names are the ones `shared_field_kind` converges.
1458fn declares_a_convergent_shared_field(source: &str) -> bool {
1459    const CONVERGENT: [&str; 9] = [
1460        "Tally",
1461        "PNCounter",
1462        "ConvergentCount",
1463        "GCounter",
1464        "SharedSet",
1465        "ORSet",
1466        "SharedSet_AddWins",
1467        "SharedSequence",
1468        "RGA",
1469    ];
1470    let mut in_shared_store = false;
1471    for line in source.lines() {
1472        let t = line.trim_start();
1473        if t.starts_with("## ") {
1474            in_shared_store = t.starts_with("## Store ") && t.contains(" shared on ");
1475            continue;
1476        }
1477        if !in_shared_store {
1478            continue;
1479        }
1480        let Some(binding) = t.strip_prefix("Let ") else {
1481            continue;
1482        };
1483        let binding = binding.strip_prefix("mutable ").unwrap_or(binding);
1484        let Some((_, annotation)) = binding.split_once(':') else {
1485            continue;
1486        };
1487        let head = annotation.split_whitespace().next().unwrap_or("");
1488        if CONVERGENT.contains(&head) {
1489            return true;
1490        }
1491    }
1492    false
1493}
1494
1495/// Prelude functions a LOWERING will call even though the source never names them.
1496///
1497/// Does this source carry a KEY MODIFIER (`on-keydown.enter={…}`) or a key TRIGGER
1498/// (`When the user presses Escape …:`)?
1499///
1500/// Both lower to a case-insensitive comparison against the key, which is `lower` from
1501/// `strings.lg` — a call the COMPILER writes from the modifier, so the demand scan that reads the
1502/// author's source cannot see it. Fourth time this exact shape has been paid for: `htmlEscape`,
1503/// then `## Route`'s `matchRoute`, then `## Page`'s `routeParam`, now this.
1504///
1505/// `.prevent`/`.stop`/`.once`/`.capture`/`.passive` are the BEHAVIOURAL modifiers and name no key,
1506/// so a page using only those needs nothing extra — keeping the pruned prelude of every existing
1507/// page exactly as it was.
1508/// Whether `source` declares something drawn through vdom.lg — a component, a page, an error page,
1509/// a `-> View` function or route — or asks for markup (`html of`).
1510fn renders_a_page(source: &str) -> bool {
1511    source.lines().any(|l| {
1512        let l = l.trim_start();
1513        l.starts_with("## Component ")
1514            || l.starts_with("## Page ")
1515            || l == "## Page"
1516            || l.starts_with("## Error page ")
1517            || ((l.starts_with("## To ") || l.starts_with("## Route ")) && l.contains("-> View"))
1518    }) || source
1519        .split_whitespace()
1520        .collect::<Vec<_>>()
1521        .windows(2)
1522        .any(|w| w[0].eq_ignore_ascii_case("html") && w[1] == "of")
1523}
1524
1525/// Whether a view writes a URL-valued attribute (`href`, `src`, … — `lgx::html::URL_ATTRIBUTES`)
1526/// whose value is computed: a hole (`href={link}`) or a quoted value holding one
1527/// (`href="/p/{id}"`). The paint checks such a value's scheme with `safeUrl` when it runs; a
1528/// written URL is checked when the view is compiled and needs nothing at run time.
1529fn computes_a_url(source: &str) -> bool {
1530    let lower = source.to_ascii_lowercase();
1531    logicaffeine_language::lgx::html::URL_ATTRIBUTES
1532        .iter()
1533        .any(|attr| {
1534            let needle = format!("{attr}=");
1535            lower.match_indices(&needle).any(|(at, _)| {
1536                let before = at.checked_sub(1).map(|i| lower.as_bytes()[i]);
1537                let written_alone = before.is_none_or(|b| !b.is_ascii_alphanumeric() && b != b'-');
1538                let value = &lower[at + needle.len()..];
1539                written_alone
1540                    && match value.as_bytes().first() {
1541                        Some(b'{') => true,
1542                        Some(b'"') => value[1..]
1543                            .split('"')
1544                            .next()
1545                            .is_some_and(|quoted| quoted.contains('{')),
1546                        _ => false,
1547                    }
1548            })
1549        })
1550}
1551
1552fn uses_a_key_gate(source: &str) -> bool {
1553    const BEHAVIOURAL: &[&str] = &["prevent", "stop", "once", "capture", "passive"];
1554    for line in source.lines() {
1555        if line.contains("presses ") {
1556            return true;
1557        }
1558        let mut rest = line;
1559        while let Some(i) = rest.find("on-") {
1560            rest = &rest[i + 3..];
1561            // The directive runs to `=` or to whitespace; a `.` inside it introduces a modifier.
1562            let end = rest.find(['=', ' ', '\t', '>']).unwrap_or(rest.len());
1563            let directive = &rest[..end];
1564            if let Some(dot) = directive.find('.') {
1565                let modifier = directive[dot + 1..].split('.').next().unwrap_or("");
1566                if !modifier.is_empty() && !BEHAVIOURAL.contains(&modifier) {
1567                    return true;
1568                }
1569            }
1570        }
1571    }
1572    false
1573}
1574
1575/// Kept beside the demand rules in `apply_prelude` deliberately: the two answer the same question
1576/// ("what does this program actually reach?") at different stages, and they drift apart the
1577/// moment they live apart.
1578fn synthesized_prelude_roots(source: &str) -> Vec<String> {
1579    let mut roots = Vec::new();
1580    if source
1581        .lines()
1582        .any(|l| l.trim_start().starts_with("Upload "))
1583    {
1584        roots.push("multipartBody".to_string());
1585        roots.push("multipartContentType".to_string());
1586        roots.push("multipartBoundary".to_string());
1587    }
1588    // ★ A DERIVED CODEC'S CALLS ARE WRITTEN BY THE COMPILER. `toJson_Todo` and `fromJson_Todo`
1589    // are emitted after parsing and reach into json.lg for the parser and the accessors — names
1590    // the author's source never contains, so the pruner (which keeps only what the SOURCE names)
1591    // threw them away and the program died with `Unknown function: jsonTryParse`.
1592    //
1593    // ★ AND IT ONLY BITES ON A BUILD. The tree-walker resolves lazily, so every single-file lock
1594    // passed while `largo build` and `largo check` refused the same program — the second time
1595    // this exact shape has cost real time (the first was `htmlEscape`), which is why the demand
1596    // rules and these roots live side by side: they answer one question at two stages.
1597    if source.contains("toJson") || source.contains("fromJson") {
1598        for name in [
1599            "jsonQuote",
1600            "jsonTryParse",
1601            "jsonGet",
1602            "jsonString",
1603            "jsonInt",
1604            "jsonBool",
1605            "jsonArray",
1606            "jsonSerialize",
1607            "jsonIsNull",
1608        ] {
1609            roots.push(name.to_string());
1610        }
1611    }
1612    // `html of <Component>` lowers to a server-render function whose every hole is escaped, and
1613    // whose URL-valued attributes additionally go through `safeUrl` — escaping neutralises markup,
1614    // and a `javascript:` URL contains none.
1615    // The other half of the `Load` demand above — the pruner keeps only what the SOURCE names,
1616    // and `cutAfter` is named by the lowering rather than by the author.
1617    // The pruner half of the class-list demand above.
1618    if source.lines().any(|l| {
1619        let l = l.trim_start();
1620        l.starts_with("Add class ") || l.starts_with("Remove class ")
1621    }) {
1622        roots.push("classListWith".to_string());
1623        roots.push("classListWithout".to_string());
1624    }
1625    if source.lines().any(|l| l.trim_start().starts_with("Load ")) {
1626        roots.push("cutAfter".to_string());
1627        roots.push("parseBool".to_string());
1628    }
1629    // A `## Route` is wrapped by the router walk, which matches paths, reads parameters and
1630    // quotes a JSON answer.
1631    if source
1632        .lines()
1633        .any(|l| l.trim_start().starts_with("## Route "))
1634    {
1635        roots.push("matchRoute".to_string());
1636        roots.push("routeParam".to_string());
1637        roots.push("isIntText".to_string());
1638        roots.push("jsonQuote".to_string());
1639    }
1640    // A `## Page /posts/:id` binds its parameters through the same two helpers — see the
1641    // matching `virtual_refs` block. The demand pulls them in; without this the pruner, which
1642    // keeps only what the SOURCE names, deletes them again one stage later.
1643    if source
1644        .lines()
1645        .any(|l| l.trim_start().starts_with("## Page ") && l.contains("/:"))
1646    {
1647        roots.push("matchRoute".to_string());
1648        roots.push("routeParam".to_string());
1649    }
1650    // The page's vdom.lg calls — see the matching `virtual_refs` block.
1651    if renders_a_page(source) {
1652        roots.extend(
1653            logicaffeine_language::parser::lgx_lower::VDOM_CALLS
1654                .iter()
1655                .map(|f| f.to_string()),
1656        );
1657    }
1658    // The pruner half of the `safeUrl` demand above.
1659    if renders_a_page(source) && computes_a_url(source) {
1660        roots.push("safeUrl".to_string());
1661    }
1662    // The key gate's `lower` — see the matching `virtual_refs` block.
1663    if uses_a_key_gate(source) {
1664        roots.push("lower".to_string());
1665    }
1666    if declares_a_convergent_shared_field(source) {
1667        roots.push("randomInt".to_string());
1668    }
1669    // The session's own machinery — see the matching `virtual_refs` block.
1670    if source.lines().any(|l| l.trim_start() == "## Session") {
1671        for f in [
1672            "sessionSecret",
1673            "randomSecret",
1674            "hexText",
1675            "unhexText",
1676            "sessionField",
1677            "sessionInt",
1678            "sessionBool",
1679            "signSession",
1680            "verifySession",
1681            "cookieOf",
1682            "withCookie",
1683            "cookie",
1684            "isCookieSafe",
1685            "macHex",
1686            "toHexInt",
1687            "bytesToHex",
1688            "bytesFromHex",
1689            "isIntText",
1690            "csrfToken",
1691            "csrfValid",
1692            "bodyParam",
1693            "headerOf",
1694            "upper",
1695            "randomInt",
1696            "split",
1697            "parseInt",
1698        ] {
1699            roots.push(f.to_string());
1700        }
1701    }
1702    // The URL split, and the query reader a parameter with no `:name` slot binds through.
1703    if source.lines().any(|l| {
1704        let l = l.trim_start();
1705        l.starts_with("## Route ")
1706            || l.starts_with("## Redirect ")
1707            || l.starts_with("## Before each request")
1708    }) {
1709        roots.push("pathOf".to_string());
1710        roots.push("queryString".to_string());
1711        roots.push("headerIn".to_string());
1712        roots.push("queryParam".to_string());
1713        roots.push("urlDecode".to_string());
1714        roots.push("hexDigitValue".to_string());
1715        roots.push("redirectTo".to_string());
1716        roots.push("permanentRedirectTo".to_string());
1717        roots.push("cutAfter".to_string());
1718        roots.push("bodyParam".to_string());
1719
1720        roots.push("jsonIsNull".to_string());
1721    }
1722    roots
1723}
1724
1725/// [`prune_unreachable_prelude`] plus the KEPT byte ranges of the INPUT (merged and
1726/// in order), so a consumer that parses the pruned text can remap an offset back to
1727/// the original source. Deep check uses this to drop EXACTLY what `largo build` drops
1728/// (it prunes the same way before it parses) while keeping every rustc finding mapped
1729/// to the user's own line. The ranges partition the kept output: concatenating
1730/// `source[s..e]` for each `(s, e)` reproduces the pruned string.
1731pub fn prune_unreachable_prelude_mapped(source: &str) -> (String, Vec<(usize, usize)>) {
1732    prune_unreachable_prelude_mapped_with(source, &[])
1733}
1734
1735/// [`prune_unreachable_prelude_mapped`] with the names the user's own source declares, which are
1736/// never eligible for pruning (see there).
1737pub fn prune_unreachable_prelude_mapped_with(
1738    source: &str,
1739    user_declared: &[&str],
1740) -> (String, Vec<(usize, usize)>) {
1741    // The prelude's function names — the ONLY sections eligible for pruning.
1742    let mut prelude_fns: std::collections::HashSet<String> =
1743        PRELUDE_FUNCTIONS.iter().map(|n| n.to_string()).collect();
1744    if prelude_fns.is_empty() {
1745        return (source.to_string(), vec![(0, source.len())]);
1746    }
1747    // A prelude NAME the USER also declares is the user's own function, not the stdlib's, and must
1748    // never be pruned: `apply_prelude` does not prepend a module whose names the source already
1749    // defines, so when the user writes `## To native args -> Seq of Text` the only section carrying
1750    // that name IS theirs. Pruning it as unreachable stdlib deleted a declaration the program needs —
1751    // a native nothing calls yet still has to reach codegen, because it is the program's own
1752    // declaration of its own native. `user_declared` is empty for callers that do not have the
1753    // pre-prelude source, which restores the previous behaviour exactly.
1754    for declared in user_declared {
1755        prelude_fns.remove(*declared);
1756    }
1757    if prelude_fns.is_empty() {
1758        return (source.to_string(), vec![(0, source.len())]);
1759    }
1760
1761    // Split into `## `-delimited sections (exact text + order), classify each by its function name.
1762    let mut sections: Vec<String> = Vec::new();
1763    for line in source.split_inclusive('\n') {
1764        if line.starts_with("## ") || sections.is_empty() {
1765            sections.push(String::new());
1766        }
1767        sections.last_mut().unwrap().push_str(line);
1768    }
1769    let names: Vec<Option<String>> = sections.iter().map(|s| fn_section_name(s)).collect();
1770
1771    // A section is a PRUNABLE prelude function iff its name is in the prelude vocabulary; every other section
1772    // (Main, structs, prose, and every USER function) is a permanent ROOT.
1773    let is_prelude_fn = |n: &Option<String>| {
1774        n.as_deref()
1775            .map(|nm| prelude_fns.contains(nm))
1776            .unwrap_or(false)
1777    };
1778
1779    // Seed reachability from the ROOTS (everything not a prunable prelude function), then fixpoint-expand over
1780    // the prelude functions, using the PERMISSIVE any-position `references` so a `to <fn>` call is seen.
1781    let root: String = sections
1782        .iter()
1783        .zip(&names)
1784        .filter(|(_, n)| !is_prelude_fn(n))
1785        .map(|(s, _)| s.as_str())
1786        .collect();
1787    let prelude_names: Vec<&str> = names
1788        .iter()
1789        .zip(&sections)
1790        .filter(|(n, _)| is_prelude_fn(n))
1791        .filter_map(|(n, _)| n.as_deref())
1792        .collect();
1793    let mut reachable: std::collections::HashSet<&str> = std::collections::HashSet::new();
1794    for &name in &prelude_names {
1795        if references(&root, name) {
1796            reachable.insert(name);
1797        }
1798    }
1799    loop {
1800        let mut added = false;
1801        // ★ THE ONE EDGE THE TEXT CANNOT SHOW: `text_from_bytes` reaches `validUtf8`. The wasm
1802        // backend lowers that builtin into a call to the stdlib validator so a browser traps on
1803        // invalid UTF-8 exactly as the reference tier does (`vm/wasm/module.rs`), and the CALLER
1804        // may be a spliced module rather than the author's own source — `encoding.lg`'s `fromHex`
1805        // reaches it without the program naming it once. Kept beside the demand rule in
1806        // `apply_prelude`, which answers the same question one stage earlier.
1807        if prelude_names.contains(&"validUtf8")
1808            && !reachable.contains("validUtf8")
1809            && (references(&root, "text_from_bytes")
1810                || sections.iter().zip(&names).any(|(s, n)| {
1811                    n.as_deref()
1812                        .map(|nm| reachable.contains(nm))
1813                        .unwrap_or(false)
1814                        && references(s, "text_from_bytes")
1815                }))
1816        {
1817            reachable.insert("validUtf8");
1818            added = true;
1819        }
1820        for (s, n) in sections.iter().zip(&names) {
1821            let Some(nm) = n.as_deref() else { continue };
1822            if !reachable.contains(nm) {
1823                continue;
1824            }
1825            for &cand in &prelude_names {
1826                if !reachable.contains(cand) && references(s, cand) {
1827                    reachable.insert(cand);
1828                    added = true;
1829                }
1830            }
1831        }
1832        if !added {
1833            break;
1834        }
1835    }
1836
1837    // Keep every non-prelude-function section + every REACHABLE prelude function, in
1838    // original order — recording each KEPT byte range in the INPUT (merging adjacent
1839    // ones) so a consumer can map an offset in the pruned text back to `source`.
1840    let mut out = String::with_capacity(source.len());
1841    let mut kept: Vec<(usize, usize)> = Vec::new();
1842    let mut pos = 0usize;
1843    for (s, n) in sections.iter().zip(&names) {
1844        let seg_len = s.len();
1845        let drop = is_prelude_fn(n) && !reachable.contains(n.as_deref().unwrap());
1846        if !drop {
1847            match kept.last_mut() {
1848                Some(last) if last.1 == pos => last.1 = pos + seg_len,
1849                _ => kept.push((pos, pos + seg_len)),
1850            }
1851            out.push_str(s);
1852        }
1853        pos += seg_len;
1854    }
1855    (out, kept)
1856}
1857
1858/// If `source` has a `## NoPrelude` opt-out line, return the source with that
1859/// line removed plus the surviving runs as [`PreludeSegment`]s; otherwise
1860/// `None`. Byte-preserving: every kept line comes through untouched (CRLF and
1861/// the trailing newline included), so the segments tie each output run to an
1862/// identical run of the user's own bytes.
1863fn strip_no_prelude(source: &str) -> Option<(String, Vec<PreludeSegment>)> {
1864    if !source.lines().any(|l| l.trim() == "## NoPrelude") {
1865        return None;
1866    }
1867    let mut out = String::with_capacity(source.len());
1868    let mut segments: Vec<PreludeSegment> = Vec::new();
1869    let mut user_pos = 0usize;
1870    for line in source.split_inclusive('\n') {
1871        if line.trim() == "## NoPrelude" {
1872            user_pos += line.len();
1873            continue;
1874        }
1875        match segments.last_mut() {
1876            Some(seg) if seg.user_start.map(|us| us + seg.len) == Some(user_pos) => {
1877                seg.len += line.len();
1878            }
1879            _ => segments.push(PreludeSegment {
1880                out_start: out.len(),
1881                len: line.len(),
1882                user_start: Some(user_pos),
1883            }),
1884        }
1885        out.push_str(line);
1886        user_pos += line.len();
1887    }
1888    Some((out, segments))
1889}
1890
1891#[cfg(test)]
1892#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/loader/tests.rs"]
1893mod tests;