1use 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#[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#[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
108pub(crate) struct Generated {
110 pub(crate) source: String,
112 pub(crate) report: String,
114 pub(crate) watch: Vec<PathBuf>,
117 pub(crate) warnings: Vec<String>,
119 pub(crate) uncovered: usize,
121 pub(crate) fallback: crate::plan::fallback::Documents,
124 pub(crate) plan: PlanData,
126}
127
128impl Configuration {
129 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 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 pub fn module(&mut self, name: impl Into<String>) -> &mut Self {
168 self.module = Some(name.into());
169 self
170 }
171
172 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 pub fn xsd_version(&mut self, version: XsdVersion) -> &mut Self {
185 self.version = version;
186 self
187 }
188
189 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 pub fn emit_report(&mut self, on: bool) -> &mut Self {
205 self.emit_report = on;
206 self
207 }
208
209 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 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 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 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 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 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 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 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 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 documents.dedup();
428 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 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 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 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 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 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 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 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 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 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 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 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 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 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
815const 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
877type 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
914fn 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
952const 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
961fn 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
989pub(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
1008fn 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 && s.len() > 1
1017 }
1018 }
1019}
1020
1021fn 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
1029fn 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
1045fn 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
1091fn 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
1107fn 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
1123fn without_fragment(location: &str) -> &str {
1125 location.split('#').next().unwrap_or(location)
1126}
1127
1128static WRITTEN: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new());
1130
1131fn 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
1144fn 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
1153fn 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
1165struct MapRewriter {
1168 maps: Vec<(String, String, String)>,
1169 used: Mutex<BTreeSet<String>>,
1170}
1171
1172impl MapRewriter {
1173 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
1188struct Compiled {
1191 set: SchemaSet,
1192 read: Recorded,
1193 maps_used: BTreeSet<String>,
1194 requests: std::collections::HashSet<Request>,
1195}
1196
1197#[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#[derive(Debug, Default)]
1208struct Recorded {
1209 documents: BTreeMap<String, Vec<u8>>,
1212}
1213
1214#[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;