teixml 0.1.0

Validate TEI XML documents against RELAX NG schemas, in pure Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
#![forbid(unsafe_code)]
#![warn(missing_docs)]
//! Validate TEI XML documents against RELAX NG schemas, in pure Rust.
//!
//! With the `schematron` feature (on by default), the ISO Schematron rules
//! a schema embeds, as TEI ODD-generated schemas do, are checked too; see
//! [`Schema::set_schematron`] and the `schematron` module.
//!
//! ```no_run
//! let schema = teixml::Schema::from_file("tei_all.rng")?;
//! let xml = std::fs::read_to_string("edition.xml")?;
//! for diagnostic in schema.validate_str(&xml)? {
//!     println!("{}: {diagnostic}", diagnostic.severity());
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

mod document;
mod limits;
pub mod relaxng;
#[cfg(feature = "schematron")]
pub mod schematron;
pub mod store;
#[cfg(feature = "sync")]
pub mod sync;
#[cfg(feature = "schematron")]
mod xpath;

use std::fmt;
use std::path::{Path, PathBuf};

use crate::relaxng::{
    DatatypeRegistry, ResolveError, SchemaResolver, SchemaSource, SchemaSyntax, ValidationErrorKind,
};

pub use document::Position;
pub use limits::MAX_DOCUMENT_DEPTH;
pub use relaxng::ElementPath;
pub use store::SchemaStore;

/// Runs `work` on its own thread with a large stack. Compiling schemas and
/// validating recurse once per level of nesting; this makes input at the
/// nesting limits fit whatever stack the caller has (debug builds especially
/// use large frames). The stack is reserved, not committed, so this costs
/// little; if the thread can't be created, `work` runs on the caller's.
fn on_large_stack<T: Send>(work: impl FnOnce() -> T + Send) -> T {
    const STACK: usize = 256 * 1024 * 1024;
    let work = std::sync::Mutex::new(Some(work));
    let run = || {
        (work
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .take()
            .expect("runs once"))()
    };
    std::thread::scope(|scope| {
        match std::thread::Builder::new()
            .name("teixml".into())
            .stack_size(STACK)
            .spawn_scoped(scope, run)
        {
            Ok(thread) => thread
                .join()
                .unwrap_or_else(|panic| std::panic::resume_unwind(panic)),
            Err(_) => run(),
        }
    })
}

/// A compiled RELAX NG schema, ready to validate documents.
///
/// With the `schematron` feature, validation also checks the Schematron
/// rules the schema embeds, unless turned off with `set_schematron(false)`.
/// The rules are compiled on first use, once per schema.
pub struct Schema {
    inner: crate::relaxng::Schema,
    registry: DatatypeRegistry,
    #[cfg(feature = "schematron")]
    schematron: EmbeddedSchematron,
}

/// The schema's own text, from which its Schematron rules are compiled when
/// they are first needed (so RELAX NG-only validation never pays for them).
#[cfg(feature = "schematron")]
struct EmbeddedSchematron {
    enabled: bool,
    /// Text and URI of a schema in the XML syntax; `None` for the compact
    /// syntax, whose annotations this crate doesn't read.
    source: Option<(String, String)>,
    /// The text of a schema in the compact syntax, only to report the
    /// Schematron rules it embeds as unchecked.
    compact: String,
    compiled: std::sync::OnceLock<Result<schematron::Schematron, String>>,
}

impl Schema {
    /// Reads and compiles a schema file. The syntax is chosen from the
    /// extension: `.rnc` is the compact syntax, anything else the XML syntax.
    /// `include`/`externalRef` are resolved relative to the including file.
    pub fn from_file(path: impl AsRef<Path>) -> Result<Self, Error> {
        let path = path.as_ref();
        let text = std::fs::read_to_string(path).map_err(|source| Error::Io {
            path: path.to_owned(),
            source,
        })?;
        Self::from_text(&text, &path.to_string_lossy(), syntax_for(path))
    }

    /// Compiles a schema from text. `base_uri` is the path that relative
    /// `include`/`externalRef` hrefs are resolved against.
    pub fn from_text(text: &str, base_uri: &str, syntax: SchemaSyntax) -> Result<Self, Error> {
        let source = SchemaSource::new(text, base_uri, syntax);
        let inner = on_large_stack(|| crate::relaxng::Schema::compile(&source, &FileResolver))
            .map_err(|error| Error::Schema(error.to_string()))?;
        Ok(Self {
            inner,
            registry: DatatypeRegistry::new(),
            #[cfg(feature = "schematron")]
            schematron: EmbeddedSchematron {
                enabled: true,
                source: (syntax == SchemaSyntax::Xml)
                    .then(|| (text.to_owned(), base_uri.to_owned())),
                compact: if syntax == SchemaSyntax::Compact {
                    text.to_owned()
                } else {
                    String::new()
                },
                compiled: std::sync::OnceLock::new(),
            },
        })
    }

    /// Turns checking of the schema's embedded Schematron rules on (the
    /// default) or off. Off, validation is RELAX NG only.
    #[cfg(feature = "schematron")]
    pub fn set_schematron(&mut self, enabled: bool) {
        self.schematron.enabled = enabled;
    }

    /// Whether validation checks the embedded Schematron rules.
    #[cfg(feature = "schematron")]
    pub fn schematron_enabled(&self) -> bool {
        self.schematron.enabled
    }

    /// The schema's embedded Schematron rules, compiled on the first call.
    /// Use it to see how many tests there are and which ones are
    /// [unsupported](schematron::Schematron::unsupported) and skipped.
    /// Fails if the schema, or a file it includes, can't be read again.
    #[cfg(feature = "schematron")]
    pub fn schematron(&self) -> Result<&schematron::Schematron, Error> {
        let compiled = self.schematron.compiled.get_or_init(|| {
            on_large_stack(|| {
                let (text, uri) = match &self.schematron.source {
                    Some((text, uri)) => (text.as_str(), uri.as_str()),
                    None => {
                        return Ok(schematron::Schematron::from_compact(
                            &self.schematron.compact,
                        ));
                    }
                };
                schematron::Schematron::from_relaxng(text, uri, &|href, base| {
                    FileResolver
                        .resolve(href, base)
                        .map(|source| (source.text().to_owned(), source.base_uri().to_owned()))
                        .map_err(|error| error.to_string())
                })
            })
        });
        compiled
            .as_ref()
            .map_err(|error| Error::Schema(format!("Schematron rules: {error}")))
    }

    /// Validates an XML document given as text. Returns every problem found,
    /// RELAX NG errors first, then Schematron messages; the document is
    /// valid when none of them [is an error](Diagnostic::is_error).
    pub fn validate_str(&self, xml: &str) -> Result<Vec<Diagnostic>, Error> {
        self.validate(xml, None)
    }

    /// Like [`validate_str`](Self::validate_str), for a document that was
    /// read from `path`. The file isn't read again: Schematron rules see the
    /// path as the document's `document-uri()`.
    pub fn validate_str_from(
        &self,
        xml: &str,
        path: impl AsRef<Path>,
    ) -> Result<Vec<Diagnostic>, Error> {
        self.validate(xml, Some(path.as_ref()))
    }

    /// Reads and validates an XML file.
    pub fn validate_file(&self, path: impl AsRef<Path>) -> Result<Vec<Diagnostic>, Error> {
        let path = path.as_ref();
        let xml = std::fs::read_to_string(path).map_err(|source| Error::Io {
            path: path.to_owned(),
            source,
        })?;
        self.validate(&xml, Some(path))
    }

    fn validate(&self, xml: &str, path: Option<&Path>) -> Result<Vec<Diagnostic>, Error> {
        on_large_stack(|| self.validate_here(xml, path))
    }

    fn validate_here(&self, xml: &str, path: Option<&Path>) -> Result<Vec<Diagnostic>, Error> {
        let options = roxmltree::ParsingOptions {
            allow_dtd: true,
            ..Default::default()
        };
        if limits::xml_nesting_exceeds(xml, MAX_DOCUMENT_DEPTH) {
            return Err(Error::Xml(format!(
                "elements nested more than {MAX_DOCUMENT_DEPTH} levels deep"
            )));
        }
        let doc = roxmltree::Document::parse_with_options(xml, options)
            .map_err(|error| Error::Xml(error.to_string()))?;
        let root = document::Node::root(&doc);
        let errors = self
            .inner
            .validate(&self.registry, &root)
            .map_err(|error| Error::Schema(error.to_string()))?;
        let mut found: Vec<(Option<usize>, ValidationErrorKind, ElementPath)> = errors
            .into_iter()
            .map(|error| {
                (
                    error.location().copied(),
                    error.kind().clone(),
                    error.path().clone(),
                )
            })
            .collect();
        let ids = self.inner.id_types();
        if !ids.is_empty() {
            // Duplicate IDs go in document order among the other errors,
            // after any at the same position; unresolved references last.
            let (duplicates, unresolved) = document::id_errors(&doc, ids);
            let mut merged = Vec::with_capacity(found.len() + duplicates.len() + unresolved.len());
            let mut found_iter = found.into_iter().peekable();
            let mut duplicates = duplicates.into_iter().peekable();
            while let Some((offset, ..)) = duplicates.peek() {
                let offset = *offset;
                while found_iter
                    .peek()
                    .is_some_and(|(at, ..)| at.is_none_or(|at| at <= offset))
                {
                    merged.extend(found_iter.next());
                }
                // A duplicate and its first occurrence stay together.
                merged.extend(
                    duplicates
                        .next()
                        .map(|(at, kind, path)| (Some(at), kind, path)),
                );
                merged.extend(
                    duplicates
                        .next()
                        .map(|(at, kind, path)| (Some(at), kind, path)),
                );
            }
            merged.extend(found_iter);
            merged.extend(
                unresolved
                    .into_iter()
                    .map(|(at, kind, path)| (Some(at), kind, path)),
            );
            found = merged;
        }
        // Positions are looked up in a line index, built only if needed.
        let lines = std::cell::OnceCell::new();
        let diagnostics: Vec<Diagnostic> = found
            .into_iter()
            .map(|(offset, kind, path)| Diagnostic {
                position: offset.map(|offset| {
                    lines
                        .get_or_init(|| document::LineIndex::new(xml))
                        .position(offset)
                }),
                kind: DiagnosticKind::RelaxNg(kind),
                path,
            })
            .collect();
        #[cfg(feature = "schematron")]
        let diagnostics = self.check_schematron(&doc, xml, &lines, path, diagnostics)?;
        #[cfg(not(feature = "schematron"))]
        let _ = path;
        Ok(diagnostics)
    }

    #[cfg(feature = "schematron")]
    fn check_schematron<'x>(
        &self,
        doc: &roxmltree::Document<'_>,
        xml: &'x str,
        lines: &std::cell::OnceCell<document::LineIndex<'x>>,
        path: Option<&Path>,
        mut diagnostics: Vec<Diagnostic>,
    ) -> Result<Vec<Diagnostic>, Error> {
        if !self.schematron.enabled {
            return Ok(diagnostics);
        }
        let rules = self.schematron()?;
        if rules.is_empty() {
            return Ok(diagnostics);
        }
        let uri = path.map(|path| {
            let path = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
            format!("file:{}", path.to_string_lossy().replace('\\', "/"))
        });
        for (node, message) in rules.check(doc, uri) {
            let lines = lines.get_or_init(|| document::LineIndex::new(xml));
            diagnostics.push(Diagnostic::schematron(lines, node, message));
        }
        Ok(diagnostics)
    }
}

/// One validation problem in a document.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Diagnostic {
    /// Where in the document the problem was found.
    pub position: Option<Position>,
    /// What went wrong.
    pub kind: DiagnosticKind,
    /// The elements from the root down to the one the problem was reported
    /// on; displays as `/TEI/text/body`.
    pub path: ElementPath,
}

/// What a diagnostic is about, and where it comes from.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum DiagnosticKind {
    /// The document doesn't match the RELAX NG schema.
    RelaxNg(ValidationErrorKind),
    /// A Schematron `assert` failed or a `report` fired, or a rule could
    /// not be evaluated.
    #[cfg(feature = "schematron")]
    Schematron(schematron::Message),
}

impl fmt::Display for DiagnosticKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RelaxNg(kind) => write!(f, "{kind}"),
            #[cfg(feature = "schematron")]
            Self::Schematron(message) => write!(f, "{message}"),
        }
    }
}

/// How serious a diagnostic is. RELAX NG errors are always errors;
/// Schematron messages take theirs from the test's `role`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Severity {
    /// The document is invalid.
    Error,
    /// Worth a look; the document is still valid.
    Warning,
    /// For information; the document is still valid.
    Info,
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Error => "error",
            Self::Warning => "warning",
            Self::Info => "info",
        })
    }
}

impl Diagnostic {
    /// How serious this diagnostic is.
    pub fn severity(&self) -> Severity {
        match &self.kind {
            DiagnosticKind::RelaxNg(_) => Severity::Error,
            #[cfg(feature = "schematron")]
            DiagnosticKind::Schematron(message) => message.severity,
        }
    }

    /// Whether this diagnostic makes the document invalid.
    pub fn is_error(&self) -> bool {
        self.severity() == Severity::Error
    }

    #[cfg(feature = "schematron")]
    fn schematron(
        lines: &document::LineIndex<'_>,
        node: xpath::XNode<'_>,
        message: schematron::Message,
    ) -> Self {
        let path = node.element().map(document::path).unwrap_or_default();
        Self {
            position: Some(lines.position(node.source_offset())),
            kind: DiagnosticKind::Schematron(message),
            path,
        }
    }
}

impl Diagnostic {
    /// What went wrong, as a sentence: the kind, plus a hint where it helps.
    pub fn message(&self) -> impl fmt::Display + '_ {
        Message(self)
    }
}

/// [`Diagnostic::message`].
struct Message<'d>(&'d Diagnostic);

impl fmt::Display for Message<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let diagnostic = self.0;
        write!(f, "{}", diagnostic.kind)?;
        // A root element in no namespace is usually a missing `xmlns`.
        if let DiagnosticKind::RelaxNg(ValidationErrorKind::UnexpectedElement(name)) =
            &diagnostic.kind
            && diagnostic.path.is_empty()
            && name.namespace.as_deref().unwrap_or_default().is_empty()
        {
            f.write_str(" (in no namespace)")?;
        }
        Ok(())
    }
}

impl fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(position) = self.position {
            write!(f, "{position}: ")?;
        }
        write!(f, "{}", self.message())?;
        if !self.path.is_empty() {
            write!(f, " (in {})", self.path)?;
        }
        Ok(())
    }
}

/// Why a schema or document couldn't be processed at all.
#[derive(Debug)]
pub enum Error {
    /// A file couldn't be read.
    Io {
        /// The file.
        path: PathBuf,
        /// The underlying error.
        source: std::io::Error,
    },
    /// The schema is not a usable RELAX NG schema.
    Schema(String),
    /// The document is not well-formed XML.
    Xml(String),
    /// The schema store is unusable, or lacks a schema a document needs.
    Store(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
            Self::Schema(message) => write!(f, "schema error: {message}"),
            Self::Xml(message) => write!(f, "XML error: {message}"),
            Self::Store(message) => write!(f, "{message}"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}

fn syntax_for(path: &Path) -> SchemaSyntax {
    match path.extension().and_then(|ext| ext.to_str()) {
        Some("rnc") => SchemaSyntax::Compact,
        _ => SchemaSyntax::Xml,
    }
}

/// Resolves `include`/`externalRef` hrefs as file paths relative to the
/// including schema. URLs are refused: validation never touches the network.
struct FileResolver;

impl SchemaResolver for FileResolver {
    fn resolve(&self, href: &str, base_uri: &str) -> Result<SchemaSource, ResolveError> {
        if href.contains("://") {
            return Err(ResolveError::new(format!(
                "refusing to fetch `{href}`: only local files are supported"
            )));
        }
        let path = Path::new(base_uri)
            .parent()
            .unwrap_or_else(|| Path::new(""))
            .join(href);
        let text = std::fs::read_to_string(&path)
            .map_err(|error| ResolveError::new(format!("{}: {error}", path.display())))?;
        Ok(SchemaSource::new(
            text,
            path.to_string_lossy(),
            syntax_for(&path),
        ))
    }
}

/// Compiles and runs the examples in README.md as doctests.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;