Skip to main content

xsd_schema/codegen/
mod.rs

1//! The generator of validation modules, for a build script (feature
2//! `codegen`).
3//!
4//! A usual business application works with a fixed set of schemas that is
5//! known when the project is created: the invoices, orders, tax messages or
6//! bank files it accepts are defined by schemas that are part of the project,
7//! and they change with a release of the application, not while it runs. So
8//! the project can compile them when it is built. Its `build.rs` names them:
9//!
10//! ```no_run
11//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
12//! xsd_schema::codegen::Configuration::new()
13//!     .schema("schema/maindoc/UBL-Invoice-2.1.xsd")
14//!     .module("invoice")
15//!     .process()?;
16//! # Ok(())
17//! # }
18//! ```
19//!
20//! and its source declares the module with
21//! `xsd_schema::include_validator!(pub invoice);` (feature `plan` of the
22//! dependency). The generator compiles the schema, builds its validation
23//! tables and writes them to `$OUT_DIR/<module>.rs`, with every schema
24//! document it read embedded. The schema is checked when the project is
25//! built, the tables ship inside the binary, and there is no schema file to
26//! deploy and no schema to compile at start-up; what the module's functions
27//! answer is in the [`plan`] module's documentation. A program
28//! that receives its schemas while it runs does not use this: it compiles
29//! them with [`SchemaSetBuilder`].
30//!
31//! The build dependency and the dependency must be the same version of this
32//! crate: a module written by another version does not compile, and says so.
33//! The generator reads a schema as the `xsd11` build of this crate does (the
34//! feature implies `xsd11`), so a schema error fails the build script, a
35//! `pattern` that is not an XSD regular expression included. The dependency
36//! needs `plan`, and `xsd11` only for an XSD 1.1 module: the tables of an XSD
37//! 1.0 schema are read by a dependency with or without `xsd11`.
38//!
39//! A build script does not fetch schemas: documents are read from the file
40//! system only, and a remote location (an `http:` import, say) fails the
41//! build with its name unless [`Configuration::map_location`] maps it to a
42//! file of the crate. Cargo is told to run the build script again when
43//! `build.rs` or any document it read changes. Before it writes the module,
44//! the generator compiles the embedded documents once more, from memory and
45//! by their keys, as the module's fallback will: a module whose documents do
46//! not compile that way is not written.
47//!
48//! The guide *Generated Validation* (`doc/GENERATED_VALIDATION.md` in the
49//! repository) has the costs, measured on three real schemas, and examples.
50
51use std::collections::{BTreeMap, BTreeSet};
52use std::error::Error;
53use std::fmt::Write as _;
54use std::path::{Component, Path, PathBuf};
55use std::sync::{Arc, Mutex};
56
57use crate::builder::SchemaSetBuilder;
58use crate::error::{SchemaError, SchemaResult};
59use crate::parser::resolver::{
60    decode_xml_bytes, EmbeddedLoader, LocationRequest, SchemaLoader, SchemaResolver,
61};
62use crate::plan::emit::{byte_string, emit_tables, str_literal};
63use crate::plan::{self, BuildReport, PlanData};
64use crate::schema::model::XsdVersion;
65use crate::schema::SchemaSet;
66
67/// For this crate's tests: what a module generated from `schemas`
68/// (relative to the crate root `manifest`) embeds for its fallback, and its
69/// tables, as [`Configuration::process`] would write them.
70#[doc(hidden)]
71pub fn harness_embedding(
72    manifest: &Path,
73    schemas: &[PathBuf],
74    xsd11: bool,
75) -> Result<(crate::plan::fallback::Documents, PlanData), String> {
76    let mut c = Configuration::new();
77    for s in schemas {
78        c.schema(s);
79    }
80    c.module("harness");
81    if xsd11 {
82        c.xsd_version(XsdVersion::V1_1);
83    }
84    let g = c.generate(manifest)?;
85    Ok((g.fallback, g.plan))
86}
87
88/// The settings of one generated module.
89///
90/// Every setter returns the configuration, so that a build script can chain
91/// them and end with [`process`](Self::process).
92#[derive(Clone, Debug)]
93pub struct Configuration {
94    schemas: Vec<PathBuf>,
95    module: Option<String>,
96    roots: Vec<(String, String)>,
97    version: XsdVersion,
98    maps: Vec<(String, PathBuf)>,
99    emit_report: bool,
100}
101
102impl Default for Configuration {
103    fn default() -> Self {
104        Self::new()
105    }
106}
107
108/// What one run of the generator produced.
109pub(crate) struct Generated {
110    /// The module's source.
111    pub(crate) source: String,
112    /// The report (`emit_report`).
113    pub(crate) report: String,
114    /// The files the build depends on: every schema document read, and the
115    /// directories of local documents that could not be read.
116    pub(crate) watch: Vec<PathBuf>,
117    /// Warnings for the build's output.
118    pub(crate) warnings: Vec<String>,
119    /// The number of uncovered types, declarations and checks.
120    pub(crate) uncovered: usize,
121    /// What the module's fallback compiles: its documents, entries,
122    /// absolute locations and version, as the module writes them.
123    pub(crate) fallback: crate::plan::fallback::Documents,
124    /// The tables.
125    pub(crate) plan: PlanData,
126}
127
128impl Configuration {
129    /// A configuration with no schema yet, for XSD 1.0, covering every
130    /// global element.
131    pub fn new() -> Self {
132        Configuration {
133            schemas: Vec::new(),
134            module: None,
135            roots: Vec::new(),
136            version: XsdVersion::V1_0,
137            maps: Vec::new(),
138            emit_report: false,
139        }
140    }
141
142    /// A schema document to compile, relative to the crate root (the
143    /// directory of `Cargo.toml`). Several documents are compiled into one
144    /// schema set; the documents they include and import are read too. Each
145    /// document is embedded under this path, or under the location the
146    /// documents name it by, resolved from here: its key.
147    ///
148    /// A key is relative to the crate root, with `/` between its parts,
149    /// however the files are linked or placed; at run time the module's
150    /// fallback finds the documents by their keys alone. A document outside
151    /// the crate root is keyed with `..` from the crate root
152    /// (`../shared/common.xsd`), so its key spells the directories on the way
153    /// up, as far as the directory the crate root and the document share: a
154    /// crate outside the home directory whose schemas are inside it writes the
155    /// user's name into the module and the binary. Keep the schemas inside the
156    /// crate, or link them in, to avoid that.
157    pub fn schema(&mut self, path: impl AsRef<Path>) -> &mut Self {
158        self.schemas.push(path.as_ref().to_path_buf());
159        self
160    }
161
162    /// The module's name: the generator writes `$OUT_DIR/<name>.rs`, and
163    /// `include_validator!(<name>)` declares it. Lower-case ASCII letters,
164    /// digits and `_`, starting with a letter or `_`, not a Rust keyword and
165    /// not a name Windows reserves for a device (`con`, `nul`, `com1` …): a
166    /// file system that ignores case must not see two modules as one file.
167    pub fn module(&mut self, name: impl Into<String>) -> &mut Self {
168        self.module = Some(name.into());
169        self
170    }
171
172    /// Limit the tables to documents whose root is this global element
173    /// (`namespace` is `""` for no namespace); may be given several times.
174    /// Without it, every global element is a possible root. A document with
175    /// another root is left to the dynamic validator.
176    pub fn root(&mut self, namespace: &str, local: &str) -> &mut Self {
177        self.roots.push((namespace.to_string(), local.to_string()));
178        self
179    }
180
181    /// The XSD version the schema is compiled as (default 1.0). An XSD 1.1
182    /// module needs the `xsd11` feature on the dependency that includes it;
183    /// an XSD 1.0 module compiles with or without it.
184    pub fn xsd_version(&mut self, version: XsdVersion) -> &mut Self {
185        self.version = version;
186        self
187    }
188
189    /// Read the document at `from` (an absolute URI as a schema document
190    /// writes it, such as an `http:` URL) from the file `to`, relative to the
191    /// crate root, which must exist. The document is embedded under `from`,
192    /// and a relative location it names is read relative to `to` and
193    /// embedded relative to `from`.
194    pub fn map_location(&mut self, from: &str, to: impl AsRef<Path>) -> &mut Self {
195        self.maps
196            .push((from.to_string(), to.as_ref().to_path_buf()));
197        self
198    }
199
200    /// Also write `$OUT_DIR/<module>.report`: the types, declarations and
201    /// value checks the tables do not cover, and why (a document that needs
202    /// one of them is left to the dynamic validator), and the pattern facets
203    /// without a table. The build prints a warning naming the file.
204    pub fn emit_report(&mut self, on: bool) -> &mut Self {
205        self.emit_report = on;
206        self
207    }
208
209    /// Compile the schema and write the module, from a build script (it
210    /// reads `CARGO_MANIFEST_DIR` and `OUT_DIR`). A schema that does not
211    /// compile, a remote location that is not mapped, or a root that is no
212    /// global element fails with a message that says which.
213    pub fn process(&self) -> Result<(), Box<dyn Error>> {
214        let manifest = std::env::var_os("CARGO_MANIFEST_DIR")
215            .map(PathBuf::from)
216            .ok_or("xsd-schema codegen: CARGO_MANIFEST_DIR is not set (run from a build script)")?;
217        let out_dir = std::env::var_os("OUT_DIR")
218            .map(PathBuf::from)
219            .ok_or("xsd-schema codegen: OUT_DIR is not set (run from a build script)")?;
220        let module = self.module_name()?;
221        claim_module(module)?;
222        let generated = self.generate(&manifest)?;
223
224        if manifest.join("build.rs").is_file() {
225            println!("cargo:rerun-if-changed=build.rs");
226        }
227        // A directive is one line: a path with a line break in it (from a
228        // schema location) is not watched, but named in a warning. Nor is a
229        // directory that holds the build's output: it changes with every
230        // build.
231        let mut warnings = generated.warnings.clone();
232        let out_canonical = std::fs::canonicalize(&out_dir).unwrap_or_else(|_| out_dir.clone());
233        for path in &generated.watch {
234            let text = path.display().to_string();
235            if path.is_dir() && out_canonical.starts_with(path) {
236                warnings.push(format!(
237                    "not watched for changes (it holds the build's output): {}",
238                    one_line(&text)
239                ));
240            } else if text.chars().any(char::is_control) {
241                warnings.push(format!("not watched for changes: {}", one_line(&text)));
242            } else {
243                println!("cargo:rerun-if-changed={text}");
244            }
245        }
246        for warning in &warnings {
247            println!(
248                "cargo:warning=xsd-schema codegen ({module}): {}",
249                one_line(warning)
250            );
251        }
252
253        let target = out_dir.join(format!("{module}.rs"));
254        // Written only when it changes, so its time stays that of the
255        // tables it holds.
256        if std::fs::read(&target).ok().as_deref() != Some(generated.source.as_bytes()) {
257            std::fs::write(&target, &generated.source)
258                .map_err(|e| format!("xsd-schema codegen: writing {}: {e}", target.display()))?;
259        }
260        if self.emit_report {
261            let report = out_dir.join(format!("{module}.report"));
262            std::fs::write(&report, &generated.report)
263                .map_err(|e| format!("xsd-schema codegen: writing {}: {e}", report.display()))?;
264            println!(
265                "cargo:warning=xsd-schema codegen ({module}): {} uncovered; report in {}",
266                generated.uncovered,
267                one_line(&report.display().to_string())
268            );
269        }
270        Ok(())
271    }
272
273    /// The module name, checked.
274    fn module_name(&self) -> Result<&str, String> {
275        let Some(name) = self.module.as_deref() else {
276            return Err("xsd-schema codegen: no module name (`Configuration::module`)".into());
277        };
278        let ident = name
279            .bytes()
280            .enumerate()
281            .all(|(i, b)| b == b'_' || b.is_ascii_lowercase() || (i > 0 && b.is_ascii_digit()));
282        if name.is_empty() || name == "_" || !ident || KEYWORDS.contains(&name) {
283            return Err(format!(
284                "xsd-schema codegen: the module name {name:?} is not a lower-case Rust \
285                 identifier (ASCII lower-case letters, digits and `_`, not a keyword)"
286            ));
287        }
288        if is_device_name(name) {
289            return Err(format!(
290                "xsd-schema codegen: the module name {name:?} names a device on Windows: \
291                 choose another"
292            ));
293        }
294        Ok(name)
295    }
296
297    /// Compile, build and write the module's source, with the crate root at
298    /// `manifest`.
299    pub(crate) fn generate(&self, manifest: &Path) -> Result<Generated, String> {
300        let module = self.module_name()?;
301        if self.schemas.is_empty() {
302            return Err("xsd-schema codegen: no schema (`Configuration::schema`)".into());
303        }
304        let root = std::fs::canonicalize(manifest).map_err(|e| {
305            format!(
306                "xsd-schema codegen: the crate root {}: {e}",
307                manifest.display()
308            )
309        })?;
310
311        for (from, _) in &self.maps {
312            if crate::parser::uri::scheme(from).is_none() {
313                return Err(format!(
314                    "xsd-schema codegen: map_location({from:?}): a location to map is an \
315                     absolute URI (`https:` …); a relative location names a file of the crate \
316                     already"
317                ));
318            }
319        }
320        let compiled = self.compile(&root)?;
321        let (set, read, maps_used) = (&compiled.set, &compiled.read, &compiled.maps_used);
322        let mut warnings = Vec::new();
323        for (from, to) in &self.maps {
324            if !maps_used.contains(from) {
325                warnings.push(format!("map_location({from:?}): no document names it"));
326            } else if !root.join(to).is_file() {
327                return Err(format!(
328                    "xsd-schema codegen: map_location({from:?}, {:?}): no such file",
329                    to.display()
330                ));
331            }
332        }
333
334        // Every directive that read nothing: a remote location the schema
335        // names is an error (a build script does not fetch), a local one a
336        // warning; so is a remote location the crate's own catalog supplied
337        // for an import that names none (the schema-instance namespace's),
338        // which the dynamic validator does not read either.
339        let mut remote = BTreeSet::new();
340        let mut watch_dirs = BTreeSet::new();
341        for f in set.directive_failures() {
342            let location = f
343                .resolved_location()
344                .or(f.schema_location())
345                .unwrap_or_default()
346                .to_string();
347            // A remote location the schema does not write is the catalog's:
348            // for an import that names none, or after the one it names could
349            // not be read.
350            let written_remote = f.schema_location().is_some_and(is_remote);
351            if is_remote(&location) && !written_remote {
352                let written = match f.schema_location() {
353                    Some(w) if !w.is_empty() => format!("could not read {w}, and "),
354                    _ => format!(
355                        "the import of {} names no schemaLocation, and ",
356                        f.namespace().unwrap_or("no namespace")
357                    ),
358                };
359                warnings.push(format!(
360                    "{written}the catalog's location for it, {location}, is remote: not read \
361                     (`Configuration::map_location` from that location reads it from a file)"
362                ));
363            } else if is_remote(&location) {
364                remote.insert(location);
365            } else {
366                // Watched by the nearest directory that exists, so that the
367                // file appearing runs the build again (a missing file would
368                // run it every time), but only one strictly inside the crate
369                // root: the root itself holds `target`, which changes with
370                // every build, and a directory above it may be the whole disk.
371                let mut dir = Path::new(&location).parent();
372                while let Some(d) = dir.filter(|d| !d.is_dir()) {
373                    dir = d.parent();
374                }
375                let watched = dir
376                    .map(|d| PathBuf::from(canonical_or_joined(d)))
377                    .filter(|d| d.starts_with(&root) && d.as_path() != root.as_path());
378                let note = if watched.is_some() {
379                    ""
380                } else {
381                    " (not watched: change build.rs to run the build again once it is there)"
382                };
383                warnings.push(format!("could not read {location}: {}{note}", f.error()));
384                watch_dirs.extend(watched);
385            }
386        }
387        if !remote.is_empty() {
388            let list: Vec<&str> = remote.iter().map(String::as_str).collect();
389            return Err(format!(
390                "xsd-schema codegen: a build script does not fetch schemas; map these locations \
391                 to files of the crate with `Configuration::map_location`: {}",
392                list.join(", ")
393            ));
394        }
395
396        let (data, report) = plan::build_roots(set, &self.roots)
397            .map_err(|e| format!("xsd-schema codegen: `Configuration::root`: {e}"))?;
398
399        // The documents, keyed as the module embeds them: by the locations
400        // the schema documents name them by (`document_keys`).
401        let mapped: BTreeMap<String, String> = self.mapped_targets(&root, maps_used);
402        let keys = self.document_keys(set, manifest, &root, &mapped);
403        let mut documents: Vec<(String, Vec<u8>)> = Vec::new();
404        let mut watch: BTreeSet<PathBuf> = watch_dirs;
405        let mut identities = BTreeSet::new();
406        for (location, bytes) in &read.documents {
407            identities.insert(crate::parser::resolver::canonicalize_file_location(
408                location.clone(),
409            ));
410            let key = if location.starts_with("embedded://") {
411                location.clone()
412            } else {
413                let path = crate::parser::uri::file_uri_to_path(location)
414                    .unwrap_or_else(|| PathBuf::from(location));
415                let canonical = canonical_or_joined(&path);
416                watch.insert(PathBuf::from(&canonical));
417                match keys.get(location).or_else(|| keys.get(&canonical)) {
418                    Some(key) => key.clone(),
419                    None => relative_key(Path::new(&canonical), &root),
420                }
421            };
422            documents.push((key, bytes.clone()));
423        }
424        documents.sort();
425        // One document read under two locations (a path and a `file:` URI of
426        // it, say) is one document.
427        documents.dedup();
428        // One key, one document.
429        for pair in documents.windows(2) {
430            if pair[0].0 == pair[1].0 {
431                return Err(format!(
432                    "xsd-schema codegen: two different schema documents are named {}: a link to a \
433                     directory on the way, and `..` after it, lead the locations the documents \
434                     write to two files; give them locations of their own",
435                    pair[0].0
436                ));
437            }
438        }
439        // Every document of the set is one that was read (and so embedded).
440        for location in set.loaded_schema_locations() {
441            if !identities.contains(location) {
442                return Err(format!(
443                    "xsd-schema codegen: internal: {location} is in the set but was not read"
444                ));
445            }
446        }
447
448        // Every document's key, by its base URI in this set.
449        let mut key_of_base = BTreeMap::new();
450        for d in &set.documents {
451            let key = if d.base_uri.starts_with("embedded://") {
452                d.base_uri.clone()
453            } else {
454                match keys.get(&d.base_uri) {
455                    Some(key) => key.clone(),
456                    None => {
457                        let path = crate::parser::uri::file_uri_to_path(&d.base_uri)
458                            .unwrap_or_else(|| PathBuf::from(&d.base_uri));
459                        let canonical = canonical_or_joined(&path);
460                        keys.get(&canonical)
461                            .cloned()
462                            .unwrap_or_else(|| relative_key(Path::new(&canonical), &root))
463                    }
464                }
465            };
466            key_of_base.insert(d.base_uri.clone(), key);
467        }
468        let entries = self.entries(&root, &keys)?;
469        let links = self.links(&root, &compiled, &key_of_base)?;
470        let source = self.module_source(&data, &documents, &entries, &links);
471        let report_text = report_text(module, &report, &documents);
472        let fallback = crate::plan::fallback::Documents {
473            schemas: documents
474                .iter()
475                .map(|(k, b)| (k.clone(), std::borrow::Cow::Owned(b.clone())))
476                .collect(),
477            entries,
478            links,
479            xsd11: self.version == XsdVersion::V1_1,
480        };
481        // The module's fallback compiles these documents from memory, by
482        // their keys and the links: here first, in the build that compiled
483        // the schema, and it must give this set (the same documents in the
484        // same namespaces, composed by the same directives), or no module is
485        // written. (A build of the program with `xsd11` compiles them with
486        // this same code.)
487        let (other, other_key) =
488            crate::plan::fallback::compile_set_keyed(&fallback).map_err(|e| {
489                let why = e
490                    .schema_error()
491                    .map_or_else(|| e.to_string(), |s| s.to_string());
492                format!(
493                    "xsd-schema codegen: the schema documents, read from memory by their keys, do \
494                     not give this schema: {why}"
495                )
496            })?;
497        let ours = shape(set, |b| key_of_base.get(b).cloned().unwrap_or_default());
498        let theirs = shape(&other, |b| other_key.get(b).cloned().unwrap_or_default());
499        if ours != theirs {
500            return Err(format!(
501                "xsd-schema codegen: the schema documents, read from memory by their keys, give \
502                 another set than the files: {}",
503                first_difference_of_shapes(&ours, &theirs)
504            ));
505        }
506        Ok(Generated {
507            source,
508            report: report_text,
509            watch: watch.into_iter().collect(),
510            warnings,
511            uncovered: report.uncovered.len(),
512            fallback,
513            plan: data,
514        })
515    }
516
517    /// The key of every document of `set`, by its location (`base_uri`):
518    /// the location it is named by, resolved against the key of the document
519    /// that names it, from the documents given to [`schema`](Self::schema)
520    /// (keyed by their paths relative to the crate root) along the
521    /// directives, breadth first. So a document is keyed by the path the
522    /// documents spell, not by where a link on the way leads, and the keys
523    /// resolve against each other as the locations do. A mapped document is
524    /// keyed by its `from` (and a relative location in it resolves against
525    /// that), a document embedded in this crate by its `embedded:` location.
526    fn document_keys(
527        &self,
528        set: &SchemaSet,
529        manifest: &Path,
530        root: &Path,
531        mapped: &BTreeMap<String, String>,
532    ) -> BTreeMap<String, String> {
533        let docs = &set.documents;
534        let mut key_of: Vec<Option<String>> = vec![None; docs.len()];
535        let mut queue = std::collections::VecDeque::new();
536        for schema in &self.schemas {
537            let canonical = canonical_or_joined(&root.join(schema));
538            let key = if schema.is_absolute() {
539                lexical_key(schema, manifest, root)
540            } else {
541                normalize_key(&schema.to_string_lossy().replace('\\', "/"))
542            };
543            for d in docs.iter().filter(|d| d.base_uri == canonical) {
544                let slot = &mut key_of[d.id as usize];
545                if slot.is_none() {
546                    *slot = Some(key.clone());
547                    queue.push_back(d.id as usize);
548                }
549            }
550        }
551        while let Some(d) = queue.pop_front() {
552            let base = key_of[d].clone().unwrap_or_default();
553            for e in &set.composition_edges {
554                let Some(t) = e.target_doc.map(|t| t as usize) else {
555                    continue;
556                };
557                if e.source_doc as usize != d || t >= docs.len() || key_of[t].is_some() {
558                    continue;
559                }
560                key_of[t] = Some(edge_key(
561                    &docs[t].base_uri,
562                    &e.schema_location,
563                    &base,
564                    manifest,
565                    root,
566                    mapped,
567                ));
568                queue.push_back(t);
569            }
570        }
571        let mut out = BTreeMap::new();
572        for d in docs {
573            if let Some(key) = &key_of[d.id as usize] {
574                out.entry(d.base_uri.clone()).or_insert_with(|| key.clone());
575            }
576        }
577        out
578    }
579
580    /// The keys of the documents given to [`schema`](Self::schema), in
581    /// order: the ones the module's fallback compiles.
582    fn entries(&self, root: &Path, keys: &BTreeMap<String, String>) -> Result<Vec<String>, String> {
583        let mut entries = Vec::new();
584        for schema in &self.schemas {
585            let canonical = canonical_or_joined(&root.join(schema));
586            let key = keys.get(&canonical).ok_or_else(|| {
587                format!(
588                    "xsd-schema codegen: internal: {} has no key",
589                    schema.display()
590                )
591            })?;
592            entries.push(key.clone());
593        }
594        Ok(entries)
595    }
596
597    /// The absolute target of each used mapping, to the first `from` (in
598    /// order) that names it.
599    fn mapped_targets(&self, root: &Path, used: &BTreeSet<String>) -> BTreeMap<String, String> {
600        let mut out = BTreeMap::new();
601        let mut froms: Vec<&(String, PathBuf)> =
602            self.maps.iter().filter(|(f, _)| used.contains(f)).collect();
603        froms.sort();
604        for (from, to) in froms {
605            let target = canonical_or_joined(&root.join(to));
606            out.entry(target)
607                .or_insert_with(|| crate::parser::uri::normalize(without_fragment(from)));
608        }
609        out
610    }
611
612    /// The rewriter of `map_location`: a mapped location to its file.
613    fn map_rewriter(&self, root: &Path) -> MapRewriter {
614        MapRewriter {
615            maps: self
616                .maps
617                .iter()
618                .map(|(from, to)| {
619                    (
620                        from.clone(),
621                        crate::parser::uri::normalize(without_fragment(from)),
622                        canonical_or_joined(&root.join(to)),
623                    )
624                })
625                .collect(),
626            used: Mutex::new(BTreeSet::new()),
627        }
628    }
629
630    /// Compile the schema set, reading through the recording loader, and
631    /// recording every directive's request (its location as written and the
632    /// base URI of the document that writes it).
633    fn compile(&self, root: &Path) -> Result<Compiled, String> {
634        let recorded = Arc::new(Mutex::new(Recorded::default()));
635        let loader = RecordingLoader {
636            recorded: Arc::clone(&recorded),
637        };
638        let mut resolver = SchemaResolver::with_loader(Box::new(loader));
639        resolver.catalog_mut().add_xml_catalog();
640        let maps = Arc::new(self.map_rewriter(root));
641        let maps_in = Arc::clone(&maps);
642        let requests = Arc::new(Mutex::new(std::collections::HashSet::new()));
643        let requests_in = Arc::clone(&requests);
644        resolver.set_location_rewriter(
645            move |request: &LocationRequest<'_>, _: &SchemaResolver| -> Option<String> {
646                if let Some(kind) = request.kind {
647                    lock(&requests_in).insert(Request {
648                        location: request.location.to_string(),
649                        base_uri: request.base_uri.to_string(),
650                        kind,
651                        namespace: request.namespace.map(str::to_string),
652                    });
653                }
654                maps_in.rewrite(request)
655            },
656        );
657        let mut builder = SchemaSetBuilder::with_resolver(resolver, self.version);
658        for schema in &self.schemas {
659            let path = canonical_or_joined(&root.join(schema));
660            builder
661                .try_add(&path)
662                .map_err(|e| format!("xsd-schema codegen: {}: {e}", schema.display()))?;
663        }
664        let compiled = builder
665            .compile()
666            .map_err(|e| format!("xsd-schema codegen: the schema does not compile: {e}"))?;
667        let set = compiled.into_schema_set();
668        let read = std::mem::take(&mut *lock(&recorded));
669        let used = std::mem::take(&mut *lock(&maps.used));
670        let requests = std::mem::take(&mut *lock(&requests));
671        Ok(Compiled {
672            set,
673            read,
674            maps_used: used,
675            requests,
676        })
677    }
678
679    /// Where each directive led this compile: (the key of the document that
680    /// writes it, its location as written, the key of the document it read,
681    /// or `""` when it read none). A module's fallback follows these, not its
682    /// own resolution of the location: the generator reads files, the
683    /// fallback reads keys, and the two resolve some spellings differently
684    /// (`//`, `\` on Windows, case and links on a file system that folds
685    /// them, `%XX`, a `#` in a file name, a file that is missing here).
686    fn links(
687        &self,
688        root: &Path,
689        compiled: &Compiled,
690        key_of_base: &BTreeMap<String, String>,
691    ) -> Result<Vec<(String, String, String)>, String> {
692        // The generator's resolver, asked again: the same rewriter, the same
693        // resolution, so each request resolves to what it resolved to.
694        let mut resolver = SchemaResolver::with_loader(Box::new(EmbeddedLoader::new()));
695        let maps = self.map_rewriter(root);
696        resolver.set_location_rewriter(
697            move |request: &LocationRequest<'_>, _: &SchemaResolver| -> Option<String> {
698                maps.rewrite(request)
699            },
700        );
701        // A document's identity (its canonical location), to its key.
702        let mut key_of_identity = BTreeMap::new();
703        for d in &compiled.set.documents {
704            if let Some(key) = key_of_base.get(&d.base_uri) {
705                key_of_identity.insert(
706                    crate::parser::resolver::document_identity(&d.base_uri),
707                    key.clone(),
708                );
709            }
710        }
711        let mut links = BTreeSet::new();
712        for r in &compiled.requests {
713            let Some(source) = key_of_base.get(&r.base_uri) else {
714                return Err(format!(
715                    "xsd-schema codegen: internal: no key for {}, which names {}",
716                    r.base_uri, r.location
717                ));
718            };
719            let target = resolver
720                .directive_target(
721                    &r.location,
722                    &r.base_uri,
723                    Some(r.kind),
724                    r.namespace.as_deref(),
725                )
726                .ok()
727                .map(|t| crate::parser::resolver::document_identity(&t))
728                .and_then(|identity| key_of_identity.get(&identity).cloned())
729                .unwrap_or_default();
730            links.insert((source.clone(), r.location.clone(), target));
731        }
732        // One location in one document leads to one document.
733        let all: Vec<(String, String, String)> = links.into_iter().collect();
734        for pair in all.windows(2) {
735            if pair[0].0 == pair[1].0 && pair[0].1 == pair[1].1 {
736                return Err(format!(
737                    "xsd-schema codegen: {} names {} twice, and it led to two documents ({} and {})",
738                    pair[0].0, pair[0].1, pair[0].2, pair[1].2
739                ));
740            }
741        }
742        Ok(all)
743    }
744
745    /// The generated module's text.
746    fn module_source(
747        &self,
748        data: &PlanData,
749        documents: &[(String, Vec<u8>)],
750        entries: &[String],
751        links: &[(String, String, String)],
752    ) -> String {
753        let mut h = Fnv::new();
754        for (key, bytes) in documents {
755            h.eat(key.as_bytes());
756            h.eat(&[0]);
757            h.eat(&(bytes.len() as u64).to_le_bytes());
758            h.eat(bytes);
759        }
760        let version = match self.version {
761            XsdVersion::V1_0 => crate::plan::abi::XSD10,
762            XsdVersion::V1_1 => crate::plan::abi::XSD11,
763        };
764        let mut out = String::new();
765        let _ = writeln!(
766            out,
767            "// auto-generated: \"xsd-schema {}\" (validation tables; do not edit)",
768            env!("CARGO_PKG_VERSION")
769        );
770        let _ = writeln!(out, "// schemas: {:016x}", h.finish());
771        let _ = writeln!(
772            out,
773            "const _: () = __xsd_plan::abi_check({});",
774            str_literal(&format!("{}{version}", crate::plan::abi::ABI))
775        );
776        emit_tables(data, "__xsd_plan", &mut out);
777        out.push_str(
778            "#[doc(hidden)]\n#[allow(dead_code, unreachable_pub)]\npub static SCHEMAS: &[(&str, &[u8])] = &[\n",
779        );
780        for (key, bytes) in documents {
781            let _ = writeln!(out, "    ({}, {}),", str_literal(key), byte_string(bytes));
782        }
783        out.push_str("];\n");
784        let entries: Vec<String> = entries.iter().map(|e| str_literal(e)).collect();
785        let links: Vec<String> = links
786            .iter()
787            .map(|(source, location, target)| {
788                format!(
789                    "({}, {}, {})",
790                    str_literal(source),
791                    str_literal(location),
792                    str_literal(target)
793                )
794            })
795            .collect();
796        let _ = write!(
797            out,
798            "{}",
799            MODULE_ITEMS
800                .replace("@ENTRIES@", &entries.join(", "))
801                .replace("@LINKS@", &links.join(", "))
802                .replace(
803                    "@XSD11@",
804                    if self.version == XsdVersion::V1_1 {
805                        "true"
806                    } else {
807                        "false"
808                    }
809                )
810        );
811        out
812    }
813}
814
815/// The module's functions and what they read, after the tables and the
816/// documents. Thin wrappers: everything they do is the crate's code, so that
817/// a fix there reaches a module without generating it again. Every path
818/// starts at `::std` (the edition 2015 reads `::std` at the crate root, where
819/// the prelude puts it) or at the module's `__xsd_plan`, so that a crate
820/// without the implicit prelude can include a module too.
821const MODULE_ITEMS: &str = r#"// Every thread reads the tables at once.
822const _: () = __xsd_plan::assert_sync(&PLAN);
823#[doc(hidden)]
824#[allow(dead_code, unreachable_pub)]
825pub static MODULE: __xsd_plan::Module =
826    __xsd_plan::Module::new(&PLAN, SCHEMAS, &[@ENTRIES@], &[@LINKS@], @XSD11@);
827::std::thread_local! {
828    static FALLBACK: __xsd_plan::Fallback = const { __xsd_plan::Fallback::new() };
829}
830/// Checks `input` against this module's tables alone.
831///
832/// `Verdict::Valid` only for a document the dynamic validator accepts,
833/// `Verdict::Unknown` for every other: it means "ask the dynamic validator",
834/// not "invalid". Touches no `SchemaSet`. `scratch` holds buffers for the
835/// next call: keep one per thread or task (any module's will do).
836#[allow(dead_code, unreachable_pub)]
837#[inline]
838pub fn check(input: &[u8], scratch: &mut __xsd_plan::Scratch) -> __xsd_plan::Verdict {
839    __xsd_plan::check(PLAN, input, scratch)
840}
841/// Validates `input`: `Ok` exactly when the dynamic validator accepts it.
842///
843/// Runs `check`, and for a document it does not answer `Valid`, the dynamic
844/// validator over this thread's `SchemaSet`, compiled from the embedded
845/// schema documents on its first use in the thread. The verdict is validity
846/// as the module's XSD version defines it: the validator's default flags,
847/// and for XSD 1.1 also the evaluation of assertions. For other flags, build
848/// a validator over `with_schema_set`.
849///
850/// # Errors
851///
852/// `ValidateError::Invalid` with the dynamic validator's errors for a
853/// document it refuses, `ValidateError::Drive` for one it could not read to
854/// the end (not well-formed XML), `ValidateError::Schema` when this build
855/// cannot compile the module's schema.
856#[allow(dead_code, unreachable_pub)]
857pub fn validate(input: &[u8]) -> ::std::result::Result<(), __xsd_plan::ValidateError> {
858    __xsd_plan::validate(&FALLBACK, &MODULE, input)
859}
860/// Calls `f` with this thread's `SchemaSet`, the one `validate` falls back to.
861///
862/// The set is compiled from the embedded schema documents on its first use
863/// in the thread, for a caller that wants more than a verdict (typed values,
864/// other flags or limits).
865///
866/// # Errors
867///
868/// `SchemaUnavailable` when this build cannot compile the module's schema.
869#[allow(dead_code, unreachable_pub)]
870pub fn with_schema_set<R>(
871    f: impl ::std::ops::FnOnce(&__xsd_plan::SchemaSet) -> R,
872) -> ::std::result::Result<R, __xsd_plan::SchemaUnavailable> {
873    __xsd_plan::with_schema_set(&FALLBACK, &MODULE, f)
874}
875"#;
876
877/// The documents of a set, as (key, target namespace) with how many times
878/// each is in it (a chameleon include adds one per namespace), and its
879/// directives, as (key of the source, key of the target, kind) with their
880/// counts: what two sets must share to be the same set as a module's fallback
881/// sees it.
882type Shape = (
883    BTreeMap<(String, String), usize>,
884    BTreeMap<(String, String, String), usize>,
885);
886
887fn shape(set: &SchemaSet, key: impl Fn(&str) -> String) -> Shape {
888    let mut documents = BTreeMap::new();
889    for d in &set.documents {
890        let ns = d
891            .target_namespace
892            .map(|n| set.name_table.resolve(n))
893            .unwrap_or_default();
894        *documents.entry((key(&d.base_uri), ns)).or_default() += 1;
895    }
896    let mut edges = BTreeMap::new();
897    for e in &set.composition_edges {
898        let of = |id: Option<u32>| {
899            id.and_then(|i| set.documents.get(i as usize))
900                .map(|d| key(&d.base_uri))
901                .unwrap_or_default()
902        };
903        *edges
904            .entry((
905                of(Some(e.source_doc)),
906                of(e.target_doc),
907                format!("{:?}", e.kind),
908            ))
909            .or_default() += 1;
910    }
911    (documents, edges)
912}
913
914/// What differs first between two shapes, in words.
915fn first_difference_of_shapes(ours: &Shape, theirs: &Shape) -> String {
916    for ((key, ns), n) in &ours.0 {
917        let m = theirs
918            .0
919            .get(&(key.clone(), ns.clone()))
920            .copied()
921            .unwrap_or(0);
922        if m != *n {
923            return format!("{key} (namespace {ns:?}) is in it {m} times, not {n}");
924        }
925    }
926    for ((key, ns), m) in &theirs.0 {
927        if !ours.0.contains_key(&(key.clone(), ns.clone())) {
928            return format!("{key} (namespace {ns:?}) is in it {m} times, not 0");
929        }
930    }
931    for ((from, to, kind), n) in &ours.1 {
932        let m = theirs
933            .1
934            .get(&(from.clone(), to.clone(), kind.clone()))
935            .copied()
936            .unwrap_or(0);
937        if m != *n {
938            return format!("the {kind} of {to} in {from} is in it {m} times, not {n}");
939        }
940    }
941    for ((from, to, kind), m) in &theirs.1 {
942        if !ours
943            .1
944            .contains_key(&(from.clone(), to.clone(), kind.clone()))
945        {
946            return format!("the {kind} of {to} in {from} is in it {m} times, not 0");
947        }
948    }
949    "the directives differ".to_string()
950}
951
952/// Rust's keywords, strict and reserved: no module name.
953const KEYWORDS: [&str; 52] = [
954    "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for",
955    "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
956    "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where",
957    "while", "async", "await", "dyn", "abstract", "become", "box", "do", "final", "macro",
958    "override", "priv", "typeof", "unsized", "virtual", "yield", "try", "gen",
959];
960
961/// The report text.
962fn report_text(module: &str, report: &BuildReport, documents: &[(String, Vec<u8>)]) -> String {
963    let mut out = String::new();
964    let _ = writeln!(out, "xsd-schema codegen report: module {module}");
965    let _ = writeln!(out, "\nschema documents ({}):", documents.len());
966    for (key, bytes) in documents {
967        let _ = writeln!(out, "  {key} ({} bytes)", bytes.len());
968    }
969    let _ = writeln!(
970        out,
971        "\nnot covered ({}): a document that needs one of these is left to the dynamic validator",
972        report.uncovered.len()
973    );
974    for line in &report.uncovered {
975        let _ = writeln!(out, "  {line}");
976    }
977    let _ = writeln!(
978        out,
979        "\npattern facets: {} with a table, {} without:",
980        report.patterns_built,
981        report.patterns_refused.len()
982    );
983    for line in &report.patterns_refused {
984        let _ = writeln!(out, "  {line}");
985    }
986    out
987}
988
989/// A 64-bit FNV-1a hash: stable, not for security.
990pub(crate) struct Fnv(u64);
991
992impl Fnv {
993    pub(crate) fn new() -> Self {
994        Fnv(0xcbf2_9ce4_8422_2325)
995    }
996
997    pub(crate) fn eat(&mut self, bytes: &[u8]) {
998        for &b in bytes {
999            self.0 = (self.0 ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
1000        }
1001    }
1002
1003    pub(crate) fn finish(&self) -> u64 {
1004        self.0
1005    }
1006}
1007
1008/// Whether a location names a remote document (a scheme other than `file:`
1009/// and `embedded:`).
1010fn is_remote(location: &str) -> bool {
1011    match crate::parser::uri::scheme(location) {
1012        None => false,
1013        Some(s) => {
1014            !(s.eq_ignore_ascii_case("file") || s.eq_ignore_ascii_case("embedded"))
1015                // A drive letter is no scheme.
1016                && s.len() > 1
1017        }
1018    }
1019}
1020
1021/// A path in its canonical form when it exists, else as given.
1022fn canonical_or_joined(path: &Path) -> String {
1023    std::fs::canonicalize(path)
1024        .unwrap_or_else(|_| path.to_path_buf())
1025        .to_string_lossy()
1026        .into_owned()
1027}
1028
1029/// The key of a local document: its path relative to the crate root, with
1030/// `/` between the parts (`..` for a document outside the root).
1031fn relative_key(path: &Path, root: &Path) -> String {
1032    let parts = |p: &Path| -> Vec<String> {
1033        p.components()
1034            .filter(|c| !matches!(c, Component::CurDir))
1035            .map(|c| c.as_os_str().to_string_lossy().into_owned())
1036            .collect()
1037    };
1038    let (p, r) = (parts(path), parts(root));
1039    let common = p.iter().zip(&r).take_while(|(a, b)| a == b).count();
1040    let mut out: Vec<String> = std::iter::repeat_n("..".to_string(), r.len() - common).collect();
1041    out.extend(p[common..].iter().cloned());
1042    out.join("/")
1043}
1044
1045/// The key of a document at `target` (its location in the set), named by
1046/// `written` (a directive's `schemaLocation` as written; empty for an import
1047/// the catalog supplied the location of) in the document keyed `base`.
1048fn edge_key(
1049    target: &str,
1050    written: &str,
1051    base: &str,
1052    manifest: &Path,
1053    root: &Path,
1054    mapped: &BTreeMap<String, String>,
1055) -> String {
1056    use crate::parser::uri;
1057    if target.starts_with("embedded://") {
1058        return target.to_string();
1059    }
1060    let target_path = uri::file_uri_to_path(target).unwrap_or_else(|| PathBuf::from(target));
1061    let canonical = canonical_or_joined(&target_path);
1062    if let Some(from) = mapped.get(&canonical) {
1063        return from.clone();
1064    }
1065    let written = written
1066        .split('#')
1067        .next()
1068        .unwrap_or_default()
1069        .replace('\\', "/");
1070    if written.is_empty() {
1071        return relative_key(Path::new(&canonical), root);
1072    }
1073    if uri::scheme(&written).is_some() {
1074        return match uri::file_uri_to_path(&written) {
1075            Some(path) => lexical_key(&path, manifest, root),
1076            None => uri::normalize(&written),
1077        };
1078    }
1079    if Path::new(&written).is_absolute() {
1080        return lexical_key(Path::new(&written), manifest, root);
1081    }
1082    if uri::scheme(base).is_some() {
1083        return uri::normalize(&uri::resolve(base, &written));
1084    }
1085    match base.rsplit_once('/') {
1086        Some((dir, _)) => normalize_key(&format!("{dir}/{written}")),
1087        None => normalize_key(&written),
1088    }
1089}
1090
1091/// A relative key with `.` dropped and each `..` cancelling the part before
1092/// it; a leading `..` stays.
1093fn normalize_key(key: &str) -> String {
1094    let mut parts: Vec<&str> = Vec::new();
1095    for part in key.split('/') {
1096        match part {
1097            "" | "." => {}
1098            ".." if parts.last().is_some_and(|p| *p != "..") => {
1099                parts.pop();
1100            }
1101            _ => parts.push(part),
1102        }
1103    }
1104    parts.join("/")
1105}
1106
1107/// The key of an absolute path: relative to the crate root as given, or as
1108/// its canonical form, whichever holds it; else relative to the root with
1109/// `..`.
1110fn lexical_key(path: &Path, manifest: &Path, root: &Path) -> String {
1111    let path = crate::parser::resolver::normalize_path(path);
1112    for base in [
1113        crate::parser::resolver::normalize_path(manifest),
1114        root.to_path_buf(),
1115    ] {
1116        if let Ok(rest) = path.strip_prefix(&base) {
1117            return relative_key(rest, Path::new(""));
1118        }
1119    }
1120    relative_key(&path, manifest)
1121}
1122
1123/// `location` without its `#fragment`.
1124fn without_fragment(location: &str) -> &str {
1125    location.split('#').next().unwrap_or(location)
1126}
1127
1128/// The modules this process (a build script) generated.
1129static WRITTEN: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new());
1130
1131/// One module per name and build script: a second would overwrite the first.
1132/// Names are lower case, so equal names are the only ones a file system that
1133/// ignores case takes for one file.
1134fn claim_module(module: &str) -> Result<(), String> {
1135    if lock(&WRITTEN).insert(module.to_ascii_lowercase()) {
1136        Ok(())
1137    } else {
1138        Err(format!(
1139            "xsd-schema codegen: the module {module} is generated twice by this build script"
1140        ))
1141    }
1142}
1143
1144/// Whether `name` is a device name of Windows (`con`, `prn`, `aux`, `nul`,
1145/// `com0`–`com9`, `lpt0`–`lpt9`), which no file there may be called.
1146fn is_device_name(name: &str) -> bool {
1147    matches!(name, "con" | "prn" | "aux" | "nul")
1148        || (name.len() == 4
1149            && (name.starts_with("com") || name.starts_with("lpt"))
1150            && name.as_bytes()[3].is_ascii_digit())
1151}
1152
1153/// `text` on one line: every control character (a line break would end a
1154/// Cargo directive and start another) as a space.
1155fn one_line(text: &str) -> String {
1156    text.chars()
1157        .map(|c| if c.is_control() { ' ' } else { c })
1158        .collect()
1159}
1160
1161fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
1162    m.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
1163}
1164
1165/// The locations `map_location` maps, each `(from, from normalized, the
1166/// file)`, and the `from`s a compile used.
1167struct MapRewriter {
1168    maps: Vec<(String, String, String)>,
1169    used: Mutex<BTreeSet<String>>,
1170}
1171
1172impl MapRewriter {
1173    /// The file a mapped location is read from. A fragment names a part of
1174    /// a document, not another one: it takes no part in the comparison (nor
1175    /// in the key the document is embedded under).
1176    fn rewrite(&self, request: &LocationRequest<'_>) -> Option<String> {
1177        let location = without_fragment(request.location);
1178        let normalized =
1179            crate::parser::uri::scheme(location).map(|_| crate::parser::uri::normalize(location));
1180        let (from, _, to) = self.maps.iter().find(|(from, norm, _)| {
1181            location == without_fragment(from) || normalized.as_deref() == Some(norm.as_str())
1182        })?;
1183        lock(&self.used).insert(from.clone());
1184        Some(to.clone())
1185    }
1186}
1187
1188/// One compile of the generator: the set, the documents read, the mapped
1189/// locations used, the directives' requests.
1190struct Compiled {
1191    set: SchemaSet,
1192    read: Recorded,
1193    maps_used: BTreeSet<String>,
1194    requests: std::collections::HashSet<Request>,
1195}
1196
1197/// A directive's request to the location rewriter.
1198#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1199struct Request {
1200    location: String,
1201    base_uri: String,
1202    kind: crate::schema::composition::CompositionEdgeKind,
1203    namespace: Option<String>,
1204}
1205
1206/// What the loader read.
1207#[derive(Debug, Default)]
1208struct Recorded {
1209    /// Each document read, by the location it was read from: its bytes as
1210    /// they are in the file.
1211    documents: BTreeMap<String, Vec<u8>>,
1212}
1213
1214/// The generator's loader: local files and the crate's embedded documents
1215/// only, each recorded with its bytes.
1216#[derive(Debug)]
1217struct RecordingLoader {
1218    recorded: Arc<Mutex<Recorded>>,
1219}
1220
1221impl SchemaLoader for RecordingLoader {
1222    fn load(&self, location: &str) -> SchemaResult<String> {
1223        if location.starts_with("embedded://") {
1224            let text = EmbeddedLoader::new().load(location)?;
1225            lock(&self.recorded)
1226                .documents
1227                .insert(location.to_string(), text.clone().into_bytes());
1228            return Ok(text);
1229        }
1230        if is_remote(location) && crate::parser::uri::file_uri_to_path(location).is_none() {
1231            return Err(SchemaError::resolution(format!(
1232                "a build script does not fetch {location}: map it to a file with \
1233                 `Configuration::map_location`"
1234            )));
1235        }
1236        let path = crate::parser::uri::file_uri_to_path(location)
1237            .unwrap_or_else(|| PathBuf::from(location));
1238        let bytes = std::fs::read(&path).map_err(|e| {
1239            SchemaError::resolution(format!("Failed to read file '{location}': {e}"))
1240        })?;
1241        let text = decode_xml_bytes(bytes.clone())?;
1242        lock(&self.recorded)
1243            .documents
1244            .insert(location.to_string(), bytes);
1245        Ok(text)
1246    }
1247
1248    fn can_load(&self, _location: &str) -> bool {
1249        true
1250    }
1251}
1252
1253#[cfg(test)]
1254mod tests;