weft-xml 0.2.1

XPath 3.1, XQuery 3.1 and XSLT 3.0 in Rust: a command and the libraries under it, tested on the W3C suites
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
//! The port's command (cl plan-0655; decisions 1105 and 1109): an XPath 3.1
//! expression, an XQuery 3.1 main module or an XSLT 3.0 stylesheet run over
//! XML files with the port's libraries, the result serialized to standard
//! output.
//!
//!     weft xpath EXPRESSION [FILE.xml]
//!     weft xquery QUERY.xq [FILE.xml]        (or -e 'QUERY TEXT')
//!     weft xslt [-o DIRECTORY [--allow-outside]] STYLESHEET.xsl [SOURCE.xml]
//!
//! FILE.xml (or SOURCE.xml) is the context item / the source document; `-'
//! reads it from standard input. fn:doc and friends read files relative to
//! the query's, the stylesheet's or the current directory. A static or
//! dynamic error is written to standard error as its W3C code and message,
//! and the command exits 1; a usage error exits 2.
//!
//! What xsl:result-document makes is written under -o's DIRECTORY (cl
//! plan-0715; until then it was dropped without a word); with no -o a
//! stylesheet that makes one is an error, so nothing is lost unsaid and
//! nothing is written where the user did not say.
//!
//! Nothing here is new evaluation: XPath is xpath-parse's reader planned and
//! evaluated by xpath-ir (as crates/xpath-ffi compiles an expression),
//! XQuery is xpath-ir's [`xpath_ir::xquery::run_main_module`], and XSLT is
//! xpath-ir's run-time XSLT compiler (its `xslt' feature, route A).

use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};
use std::process::ExitCode;
use xdm::arena::TreeArena;
use xdm::rt::Item;
use xdm::{Document, XdmError};
use xpath_ir::ctx::{DocSource, Dyn};
use xpath_ir::xslt::Resources;

/// The usage text, under the binary's name.
fn usage() -> String {
    let b = env!("CARGO_BIN_NAME");
    format!("usage:\n  {b} xpath EXPRESSION [FILE.xml]\n  {b} xquery QUERY.xq [FILE.xml]      {b} xquery -e 'QUERY TEXT' [FILE.xml]\n  {b} xslt [-o DIRECTORY [--allow-outside]] STYLESHEET.xsl [SOURCE.xml]\nFILE.xml or SOURCE.xml `-' reads standard input. XPath and XQuery results are\nserialized with the XML method, no XML declaration (XQuery 3.1 Appendix C.1),\nan XSLT result by its xsl:output. -o: where xsl:result-document's documents go,\neach at its href under DIRECTORY; one that would be outside it is refused unless\n--allow-outside. Errors: the W3C code and message on stderr,\nexit 1; a usage error exits 2.")
}

/// The files a query or stylesheet reads, from the file system: a `file:'
/// URI or a path.
struct Files;

/// The files read in this run, as the file system names them: none may be
/// written in it (XTDE1500).
static READ: std::sync::Mutex<Vec<PathBuf>> = std::sync::Mutex::new(Vec::new());

/// PATH's bytes, the file entered in [`READ`].
fn read_file(path: &str) -> std::io::Result<Vec<u8>> {
    let bytes = std::fs::read(path)?;
    if let (Ok(p), Ok(mut read)) = (std::fs::canonicalize(path), READ.lock()) {
        read.push(p);
    }
    Ok(bytes)
}

/// PATH opened to be read as a stream, the file entered in [`READ`].
fn open_file(path: &str) -> std::io::Result<std::fs::File> {
    let f = std::fs::File::open(path)?;
    if let (Ok(p), Ok(mut read)) = (std::fs::canonicalize(path), READ.lock()) {
        read.push(p);
    }
    Ok(f)
}

fn path_of_uri(uri: &str) -> String {
    let p = uri.strip_prefix("file://").unwrap_or(uri);
    let b = p.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' && i + 2 < b.len() {
            if let Ok(v) = u8::from_str_radix(&p[i + 1..i + 3], 16) {
                out.push(v);
                i += 3;
                continue;
            }
        }
        out.push(b[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

impl Resources for Files {
    fn read(&self, uri: &str) -> Option<Vec<u8>> {
        read_file(&path_of_uri(uri)).ok()
    }
}

impl DocSource for Files {
    fn path_of(&self, uri: &str) -> Option<String> {
        let p = path_of_uri(uri);
        std::path::Path::new(&p).is_file().then_some(p)
    }
    fn bytes(&self, path: &str) -> Option<&[u8]> {
        // read once per run (Dyn::loaded keeps the document), kept for the
        // process's life
        read_file(path).ok().map(|v| &*Box::leak(v.into_boxed_slice()))
    }
    fn open(&self, path: &str) -> Option<Box<dyn Read>> {
        open_file(path).ok().map(|f| Box::new(f) as Box<dyn Read>)
    }
    fn uri_of(&self, path: &str) -> String {
        format!("file://{path}")
    }
}

static FILES: Files = Files;

/// The absolute `file:' URI of PATH (the current directory's when `-').
fn file_uri(path: &str) -> String {
    let p = if path == "-" { std::path::PathBuf::from("stdin.xml") } else { std::path::PathBuf::from(path) };
    let abs = std::fs::canonicalize(&p).unwrap_or_else(|_| std::env::current_dir().map(|d| d.join(&p)).unwrap_or(p));
    format!("file://{}", abs.display())
}

/// PATH's text (standard input for `-'), UTF-8 or UTF-16 with its mark.
fn read_text(path: &str) -> Result<String, XdmError> {
    let bytes = if path == "-" {
        let mut v = Vec::new();
        std::io::stdin().read_to_end(&mut v).map_err(|e| XdmError::new("FODC0002", format!("standard input: {e}")))?;
        v
    } else {
        read_file(path).map_err(|e| XdmError::new("FODC0002", format!("{path}: {e}")))?
    };
    xpath_ir::ctx::decode_text(&bytes).ok_or_else(|| XdmError::new("FODC0002", format!("{path}: not UTF-8 or UTF-16 text")))
}

/// RUN on the parser's deep stack (xpath-ir's own: its reader and evaluator
/// recurse), its error carried back as its code and message (an XdmError
/// holds an Rc and is not Send); a panic answered FOER0000.
fn on_stack<T: Send>(run: impl FnOnce() -> Result<T, XdmError> + Send) -> Result<T, XdmError> {
    let r = xpath_ir::parse::on_stack(xpath_ir::parse::STACK, move || run().map_err(|e| (e.code.to_string(), e.message.to_string())));
    match r {
        Ok(Ok(made)) => Ok(made),
        Ok(Err((code, message))) => Err(XdmError::new(&code, message)),
        Err(_) => Err(XdmError::new("FOER0000", "the evaluator panicked")),
    }
}

/// EXPRESSION read as XPath 3.1, planned, and evaluated with FILE's
/// document node as the context item (none: the focus absent).
fn xpath(expression: &str, file: Option<&str>) -> Result<String, XdmError> {
    let source = match file {
        Some(f) => Some((read_text(f)?, file_uri(f))),
        None => None,
    };
    let expression = expression.to_string();
    let run = move || -> Result<String, XdmError> {
        let ir = xpath_parse::parse_in(&expression, xpath_parse::Generation::Xpath31).map_err(|e| XdmError::new(&e.code, e.message))?;
        let json = xpath_parse::statics(&[], "").ir(&ir).map_err(|u| XdmError::new("XPST0003", format!("an expression this reader does not carry: {}", u.0)))?;
        let ir = xpath_ir::ir::Ir::decode(&json).map_err(|e| XdmError::new("XPST0003", format!("{e:?}")))?;
        let plan = xpath_ir::plan::compile(&ir, &xpath_ir::plan::StaticContext::default()).map_err(|e| match e {
            xpath_ir::plan::CompileError::Static(e) => e,
            xpath_ir::plan::CompileError::NotYet { bucket, key } => XdmError::new("XPST0017", format!("not implemented here: {bucket}: {key}")),
        })?;
        let arena = TreeArena::new();
        let mut d = Dyn::empty();
        d.arena = Some(&arena);
        d.docs = Some(&FILES);
        let item = match &source {
            Some((text, uri)) => Some(Item::Node(arena.alloc(Document::parse_at(text, uri)?).root_ref())),
            None => None,
        };
        xdm::rt::current_datetime_reset();
        let value = plan.evaluate_in(item, &d)?;
        xpath_ir::serfn::serialize_declared(&value, &[("omit-xml-declaration".to_string(), "yes".to_string())])
    };
    on_stack(run)
}

/// QUERY's text run as a main module, FILE's document node its context item.
fn xquery(query: &str, base: &str, file: Option<&str>) -> Result<String, XdmError> {
    let source = match file {
        Some(f) => Some((read_text(f)?, file_uri(f))),
        None => None,
    };
    xpath_ir::xquery::run_main_module(query, base, source.as_ref().map(|(t, u)| (t.as_str(), u.as_str())), &FILES).map_err(|e| {
        let (code, message) = e.split_once(' ').unwrap_or((e.as_str(), ""));
        XdmError::new(code, message.to_string())
    })
}

/// The stylesheet at STYLESHEET compiled by the run-time compiler and run
/// over SOURCE (none: its initial template, xsl:initial-template), its
/// principal result serialized by its output definition (empty when the
/// stylesheet wrote secondary results alone, as fn:transform leaves it out),
/// and each secondary result written by its own under OUT, once all of them
/// are made and may be. A stylesheet that declares something streamable is
/// run as it says (cl plan-0699): a source its initial mode streams is read as
/// a stream, and the principal result is written as it is made, so that an
/// error can follow some of it.
fn xslt(stylesheet: &str, source: Option<&str>, out: Option<&Out>) -> Result<Vec<u8>, XdmError> {
    let text = read_text(stylesheet)?;
    let base = file_uri(stylesheet);
    let source = source.map(str::to_string);
    let run = move || -> Result<(Vec<u8>, Vec<(String, Vec<u8>)>), XdmError> {
        use xpath_ir::xslt::transform::{run, run_in_parts, streams_source, strip, Invocation, Stream};
        let sheet = xpath_ir::xslt::compile_text(&text, &base, &FILES)?;
        let arena = TreeArena::new();
        let mut d = Dyn::empty();
        d.arena = Some(&arena);
        d.docs = Some(&FILES);
        let mut stream = None;
        let source_item = match &source {
            Some(f) if streams_source(&sheet, &d, None).is_ok() => {
                let input: Box<dyn Read> = if f == "-" { Box::new(std::io::stdin()) } else { Box::new(open_file(f).map_err(|e| XdmError::new("FODC0002", format!("{f}: {e}")))?) };
                stream = Some(Stream { input, uri: file_uri(f) });
                None
            }
            Some(f) => {
                let doc: &Document = arena.alloc(Document::parse_at(&read_text(f)?, &file_uri(f))?);
                Some(Item::Node(strip(&sheet, doc, &d).root_ref()))
            }
            None => None,
        };
        let template = source.is_none().then(|| format!("Q{{{}}}initial-template", xpath_ir::xslt::XSL_NS));
        let inv = Invocation { source: source_item, template, stream, ..Invocation::default() };
        xdm::rt::current_datetime_reset();
        let utf8 = sheet.output.encoding.as_deref().is_none_or(|e| e.trim().eq_ignore_ascii_case("utf-8"));
        if sheet.streams && utf8 {
            let ended = std::rc::Rc::new(std::cell::Cell::new(None));
            let last = std::rc::Rc::clone(&ended);
            let out = run_in_parts(&sheet, &d, inv, false, move |t| {
                last.set(t.chars().last());
                std::io::stdout().write_all(t.as_bytes()).map_err(|e| XdmError::new("SERE0000", format!("standard output: {e}")))
            })?;
            let mut secondary = Vec::new();
            for (href, tree, params) in &out.secondary {
                secondary.push((href.clone(), octets(&xpath_ir::serfn::serialize_document_checked(tree, params)?, params)));
            }
            // the line's end the whole text is given
            let end = if ended.get() == Some('\n') || ended.get().is_none() && !secondary.is_empty() { Vec::new() } else { b"\n".to_vec() };
            return Ok((end, secondary));
        }
        let mut out = run(&sheet, &d, inv)?;
        if out.output_method_by_default {
            out.params.method = sheet.output.method.clone();
        }
        let tree = out.tree.ok_or_else(|| XdmError::new("XTDE0040", "the stylesheet made no principal result"))?;
        let mut secondary = Vec::new();
        for (href, tree, params) in &out.secondary {
            secondary.push((href.clone(), octets(&xpath_ir::serfn::serialize_document_checked(tree, params)?, params)));
        }
        if !secondary.is_empty() && !out.principal_written && tree.root_ref().children().next().is_none() {
            return Ok((Vec::new(), secondary));
        }
        let mut text = xpath_ir::serfn::serialize_document_checked(&tree, &out.params)?;
        if !text.ends_with('\n') {
            text.push('\n');
        }
        Ok((octets(&text, &out.params), secondary))
    };
    let (principal, secondary) = on_stack(run)?;
    if !secondary.is_empty() {
        write_secondary(&secondary, out)?;
    }
    Ok(principal)
}

/// TEXT in the encoding P names, of those that are not UTF-8 the two the
/// serializer writes for: UTF-16, with its byte order mark, and ISO-8859-1.
fn octets(text: &str, p: &xpath_ir::serfn::Params) -> Vec<u8> {
    let marked = || if text.starts_with('\u{feff}') { text.to_string() } else { format!("\u{feff}{text}") };
    match p.encoding.as_deref().map(|e| e.trim().to_ascii_lowercase()).as_deref() {
        Some("utf-16" | "utf-16be") => marked().encode_utf16().flat_map(u16::to_be_bytes).collect(),
        Some("utf-16le") => marked().encode_utf16().flat_map(u16::to_le_bytes).collect(),
        Some("iso-8859-1" | "latin1") if text.trim_start_matches('\u{feff}').chars().all(|c| (c as u32) < 0x100) => text.trim_start_matches('\u{feff}').chars().map(|c| c as u8).collect(),
        _ => text.as_bytes().to_vec(),
    }
}

/// Where a stylesheet's secondary results go.
struct Out {
    directory: String,
    /// May one be written outside it?
    outside: bool,
}

/// A refusal no W3C code names, at fn:error's own (F&O 3.1 §3.1.1, an
/// unidentified error).
fn refused(what: String) -> XdmError {
    XdmError::new("FOER0000", what)
}

/// The secondary results written, or none of them: each href's file is found
/// and may be written before the first is.
fn write_secondary(made: &[(String, Vec<u8>)], out: Option<&Out>) -> Result<(), XdmError> {
    let Some(out) = out else {
        let hrefs: Vec<&str> = made.iter().map(|(h, _)| h.as_str()).collect();
        return Err(refused(format!("xsl:result-document made {} with nowhere to put {}: name a directory with -o", hrefs.join(", "), if made.len() == 1 { "it" } else { "them" })));
    };
    let directory = std::fs::create_dir_all(&out.directory).and_then(|_| std::fs::canonicalize(&out.directory)).map_err(|e| refused(format!("-o {}: {e}", out.directory)))?;
    let mut files: Vec<PathBuf> = Vec::new();
    for (href, _) in made {
        let file = file_of(href, &directory)?;
        if !out.outside && !file.starts_with(&directory) {
            return Err(refused(format!("xsl:result-document: {href} is {}, outside {} (--allow-outside writes it)", file.display(), directory.display())));
        }
        if files.contains(&file) {
            return Err(XdmError::new("XTDE1490", format!("two results at {}", file.display())));
        }
        if let Some(f) = files.iter().find(|f| f.starts_with(&file) || file.starts_with(f)) {
            return Err(refused(format!("xsl:result-document: {} and {} cannot both be files", f.display(), file.display())));
        }
        if READ.lock().is_ok_and(|read| read.contains(&file)) {
            return Err(XdmError::new("XTDE1500", format!("{} was read in this transformation and may not be written", file.display())));
        }
        files.push(file);
    }
    for (file, (_, bytes)) in files.iter().zip(made) {
        file.parent().map_or(Ok(()), std::fs::create_dir_all).and_then(|_| std::fs::write(file, bytes)).map_err(|e| refused(format!("{}: {e}", file.display())))?;
    }
    Ok(())
}

/// The file HREF names, resolved against DIRECTORY (XSLT 3.0 §25.1: `If it is
/// relative, then it is resolved against the base output URI'), as the file
/// system will have it: percent-escapes read, then `.' and `..' taken away,
/// then the links of what is there already followed, so no spelling of a
/// place outside DIRECTORY looks like one inside it.
fn file_of(href: &str, directory: &Path) -> Result<PathBuf, XdmError> {
    let mut base = String::from("file://");
    for b in directory.to_string_lossy().bytes() {
        if b.is_ascii_alphanumeric() || b"/-._~".contains(&b) {
            base.push(b as char);
        } else {
            base.push_str(&format!("%{b:02X}"));
        }
    }
    base.push('/');
    let uri = xdm::rt::resolve_reference(href, &base);
    let local = uri.strip_prefix("file:").map(|p| p.strip_prefix("//localhost/").map_or(p.to_string(), |p| format!("///{p}")));
    let path = match local.as_deref() {
        Some(p) if p.starts_with("///") || (p.starts_with('/') && !p.starts_with("//")) => path_of_uri(p.strip_prefix("//").unwrap_or(p)),
        _ => return Err(refused(format!("xsl:result-document: {href} is {uri}, which is not a file here"))),
    };
    let mut plain = PathBuf::new();
    for c in Path::new(&path).components() {
        if c == Component::ParentDir {
            plain.pop();
        } else if c != Component::CurDir {
            plain.push(c);
        }
    }
    // the part that exists, its links followed; what is below it is to be made
    let there = plain.ancestors().find(|a| std::fs::symlink_metadata(a).is_ok()).unwrap_or(Path::new("/"));
    let real = std::fs::canonicalize(there).map_err(|e| refused(format!("xsl:result-document: {href}: {}: {e}", there.display())))?;
    let rest = plain.strip_prefix(there).unwrap_or(Path::new(""));
    let file = if rest.as_os_str().is_empty() { real } else { real.join(rest) };
    if path.ends_with('/') || path.contains('\0') || file.is_dir() {
        return Err(refused(format!("xsl:result-document: {href} does not name a file")));
    }
    Ok(file)
}

/// `weft xslt's arguments: its options, wherever they stand, and the one or
/// two files.
fn xslt_arguments<'a>(args: &[&'a str]) -> Option<(Vec<&'a str>, Option<Out>)> {
    let (mut files, mut directory, mut outside) = (Vec::new(), None, false);
    let mut rest = args.iter();
    while let Some(a) = rest.next() {
        match *a {
            "-o" if directory.is_none() => directory = Some(rest.next().filter(|d| !d.is_empty())?.to_string()),
            "--allow-outside" => outside = true,
            f if f != "-" && f.starts_with('-') => return None,
            f => files.push(f),
        }
    }
    if !(1..=2).contains(&files.len()) || (outside && directory.is_none()) {
        return None;
    }
    Some((files, directory.map(|directory| Out { directory, outside })))
}

fn misused() -> ExitCode {
    eprintln!("{}", usage());
    ExitCode::from(2)
}

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let a: Vec<&str> = args.iter().map(String::as_str).collect();
    let line = |text: String| if text.ends_with('\n') { text.into_bytes() } else { (text + "\n").into_bytes() };
    let result = match a.as_slice() {
        ["--version"] | ["-V"] => {
            println!("{} {} ({})", env!("CARGO_BIN_NAME"), env!("CARGO_PKG_VERSION"), env!("CARGO_PKG_NAME"));
            return ExitCode::SUCCESS;
        }
        ["--help"] | ["-h"] => {
            println!("{}", usage());
            return ExitCode::SUCCESS;
        }
        ["xpath", expression] => xpath(expression, None).map(line),
        ["xpath", expression, file] => xpath(expression, Some(file)).map(line),
        ["xquery", "-e", text, rest @ ..] if rest.len() <= 1 => xquery(text, &file_uri("query.xq"), rest.first().copied()).map(line),
        ["xquery", query, rest @ ..] if rest.len() <= 1 => match read_text(query) {
            Ok(text) => xquery(&text, &file_uri(query), rest.first().copied()).map(line),
            Err(e) => Err(e),
        },
        ["xslt", rest @ ..] => match xslt_arguments(rest) {
            Some((files, out)) => xslt(files[0], files.get(1).copied(), out.as_ref()),
            None => return misused(),
        },
        _ => return misused(),
    };
    match result {
        Ok(bytes) => {
            let _ = std::io::stdout().lock().write_all(&bytes);
            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("{} {}", e.code, e.message);
            ExitCode::from(1)
        }
    }
}