Skip to main content

einvoice_validator/
validator.rs

1//! Loading a rule set once, then validating documents with it.
2
3use std::borrow::Cow;
4use std::path::{Path, PathBuf};
5
6use einvoice_xpath_eval::Clock;
7use einvoice_xslt::LoadErrorKind;
8use einvoice_xslt_exec::{Executable, TransformError, TransformOptions};
9use roxmltree::ParsingOptions;
10use sha2::{Digest, Sha256};
11
12use crate::manifest::{MANIFEST_FILE, RuleSet, SchemaId, StylesheetEntry};
13use crate::report::{Report, RuleSetVersion, StylesheetFailure, StylesheetReport};
14use crate::{Error, builtin};
15
16/// Options of one validation.
17#[derive(Debug, Clone, Copy, Default)]
18pub struct ValidateOptions<'a> {
19    document_uri: Option<&'a str>,
20    clock: Option<Clock>,
21}
22
23impl<'a> ValidateOptions<'a> {
24    /// The default options: the document has no URI, and the clock is the system clock
25    /// in UTC.
26    #[must_use]
27    pub const fn new() -> Self {
28        Self {
29            document_uri: None,
30            clock: None,
31        }
32    }
33
34    /// The clock of the stylesheets: the implicit timezone and the value of
35    /// `fn:current-dateTime()` (read once per validation, as the reference engine reads
36    /// it once per transformation). By default, the system clock in UTC; required on
37    /// targets without a system clock, such as `wasm32-unknown-unknown`, where
38    /// validating without it fails with [`Error::Unsupported`].
39    #[must_use]
40    pub const fn clock(mut self, clock: Clock) -> Self {
41        self.clock = Some(clock);
42        self
43    }
44
45    /// The URI of the document: what `document-uri(/)` returns in the stylesheets, and
46    /// what the SVRL report states in `svrl:active-pattern/@documents`. For a file,
47    /// [`file_uri`] gives the URI the reference engine uses.
48    #[must_use]
49    pub const fn document_uri(mut self, uri: &'a str) -> Self {
50        self.document_uri = Some(uri);
51        self
52    }
53}
54
55/// The `file:` URI that the reference engine (Saxon-HE) gives a document read from the
56/// file at `path` (absolute). `None` for a relative path or one that is not Unicode.
57#[must_use]
58pub fn file_uri(path: &Path) -> Option<String> {
59    einvoice_xpath_eval::file_uri(path)
60}
61
62/// A rule set ready to validate documents: its schema loaded and its stylesheets
63/// prepared, once. Validating a document only reads it, so one `Validator` serves any
64/// number of documents, from any number of threads at once (`Send + Sync`); nothing of
65/// the rule set is copied per document.
66#[derive(Debug)]
67pub struct Validator {
68    rule_set: RuleSet,
69    schema: Option<einvoice_xsd::Schema>,
70    /// The prepared stylesheets, in the order of `rule_set.stylesheets()`.
71    stylesheets: Vec<Executable>,
72}
73
74impl Validator {
75    /// The built-in rule set `name` (see [`BUILTIN_RULE_SETS`](crate::BUILTIN_RULE_SETS)).
76    ///
77    /// # Errors
78    ///
79    /// [`Error::Bundle`] for an unknown name; otherwise as [`Validator::from_bundle`],
80    /// which none of the built-in rule sets fails in practice (a test loads each).
81    pub fn builtin(name: &str) -> Result<Self, Error> {
82        let (manifest, files) = builtin::get(name)?;
83        Self::from_bundle(manifest, files)
84    }
85
86    /// The built-in rule set `cen-ubl`: the CEN EN 16931 validation artefacts for UBL,
87    /// release 1.3.17 (EUPL-1.2), embedded unmodified, with the UBL 2.1 schemas.
88    ///
89    /// # Errors
90    ///
91    /// None in practice (a test loads it); the error is returned rather than hidden.
92    #[cfg(feature = "cen-ubl")]
93    pub fn cen_ubl() -> Result<Self, Error> {
94        Self::builtin("cen-ubl")
95    }
96
97    /// Loads a bundle from memory: its manifest and its files, by their paths in the
98    /// manifest. Files not named by the manifest are ignored.
99    ///
100    /// # Errors
101    ///
102    /// [`Error::Bundle`] for an invalid manifest, a missing file or a stylesheet that is
103    /// not well-formed; [`Error::Checksum`] for a file whose SHA-256 differs from the
104    /// manifest's; [`Error::Unsupported`] for a stylesheet or schema outside the
105    /// supported subset.
106    pub fn from_bundle(manifest: &str, files: &[(&str, &[u8])]) -> Result<Self, Error> {
107        let rule_set = RuleSet::parse(manifest)?;
108        let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
109        for entry in rule_set.stylesheets() {
110            let Some((_, bytes)) = files.iter().find(|(path, _)| *path == entry.path()) else {
111                return Err(Error::bundle(format!(
112                    "stylesheet {}: file {} missing from the bundle",
113                    entry.name(),
114                    entry.path()
115                )));
116            };
117            stylesheets.push(prepare(entry, bytes, None)?);
118        }
119        Self::with(rule_set, stylesheets)
120    }
121
122    /// Loads the bundle in the directory `dir`: its manifest [`MANIFEST_FILE`] and the
123    /// files it names, relative to `dir`.
124    ///
125    /// # Errors
126    ///
127    /// [`Error::Io`] when a file cannot be read, otherwise as
128    /// [`Validator::from_bundle`].
129    pub fn from_bundle_dir(dir: impl AsRef<Path>) -> Result<Self, Error> {
130        let dir = dir.as_ref();
131        let manifest_path = dir.join(MANIFEST_FILE);
132        let manifest = read(&manifest_path)?;
133        let manifest = std::str::from_utf8(&manifest)
134            .map_err(|e| Error::bundle(format!("{}: not UTF-8: {e}", manifest_path.display())))?;
135        let rule_set = RuleSet::parse(manifest)?;
136        let mut stylesheets = Vec::with_capacity(rule_set.stylesheets().len());
137        for entry in rule_set.stylesheets() {
138            let mut path = dir.to_path_buf();
139            path.extend(entry.path().split('/'));
140            let bytes = read(&path)?;
141            let base_uri = std::path::absolute(&path).ok().and_then(|p| file_uri(&p));
142            stylesheets.push(prepare(entry, &bytes, base_uri)?);
143        }
144        Self::with(rule_set, stylesheets)
145    }
146
147    fn with(rule_set: RuleSet, stylesheets: Vec<Executable>) -> Result<Self, Error> {
148        let schema = match rule_set.schema() {
149            None => None,
150            Some(SchemaId::Ubl21) => Some(einvoice_xsd::Schema::ubl_2_1().map_err(|e| {
151                if e.kind == einvoice_xsd::LoadErrorKind::Unsupported {
152                    Error::unsupported(format!("schema ubl-2.1: {e}"))
153                } else {
154                    Error::internal(format!("the embedded schema ubl-2.1 does not load: {e}"))
155                }
156            })?),
157        };
158        Ok(Self {
159            rule_set,
160            schema,
161            stylesheets,
162        })
163    }
164
165    /// The rule set: name, version, schema, stylesheets and their checksums.
166    #[must_use]
167    pub const fn rule_set(&self) -> &RuleSet {
168        &self.rule_set
169    }
170
171    /// Validates a document with the default options (no document URI).
172    ///
173    /// # Errors
174    ///
175    /// As [`Validator::validate_with`].
176    pub fn validate(&self, document: &[u8]) -> Result<Report, Error> {
177        self.validate_with(document, &ValidateOptions::new())
178    }
179
180    /// Validates a document given as a buffer, with the default options (no document
181    /// URI).
182    ///
183    /// # Errors
184    ///
185    /// As [`Validator::validate_with`].
186    pub fn validate_owned(&self, document: Vec<u8>) -> Result<Report, Error> {
187        self.validate_owned_with(document, &ValidateOptions::new())
188    }
189
190    /// [`Validator::validate_with`] on a document given as a buffer, which the
191    /// validation keeps instead of copying: the buffer becomes the text without a copy,
192    /// and the tree of the last stylesheet refers to it, so that while that stylesheet
193    /// runs the document is in memory once rather than twice. Same report as
194    /// [`Validator::validate_with`]; for a caller that has no further use for the bytes
195    /// (a file just read).
196    ///
197    /// # Errors
198    ///
199    /// As [`Validator::validate_with`].
200    pub fn validate_owned_with(
201        &self,
202        document: Vec<u8>,
203        options: &ValidateOptions<'_>,
204    ) -> Result<Report, Error> {
205        self.validate_text(Cow::Owned(decode_owned(document)?), options)
206    }
207
208    /// Validates a document: checks that it is well-formed XML, validates it against
209    /// the rule set's schema, then runs every stylesheet of the rule set on it. The
210    /// stylesheets run even when the schema reports errors, so that the report is
211    /// complete. When a stylesheet raises a dynamic error on a document that has schema
212    /// errors (a non-numeric amount the rules compute with, ...), the report is returned
213    /// all the same, invalid, with the error in [`StylesheetReport::failure`]; without
214    /// schema errors, the error is returned.
215    ///
216    /// The document must be UTF-8 (a byte order mark is allowed) and have no document
217    /// type declaration.
218    ///
219    /// # Errors
220    ///
221    /// [`Error::NotXml`] when the document is not well-formed XML (or not UTF-8);
222    /// [`Error::Unsupported`] for another encoding, a document type declaration, or a
223    /// construct the engine refuses; [`Error::Transform`] when a stylesheet raises a
224    /// dynamic error on the document; [`Error::Bundle`] when a stylesheet's result is
225    /// not an SVRL report; [`Error::Internal`] for a bug.
226    pub fn validate_with(
227        &self,
228        document: &[u8],
229        options: &ValidateOptions<'_>,
230    ) -> Result<Report, Error> {
231        self.validate_text(Cow::Borrowed(decode(document)?), options)
232    }
233
234    /// The validation of a decoded document: borrowed by the schema and every stylesheet
235    /// but the last, which is given it when it is owned.
236    fn validate_text(
237        &self,
238        text: Cow<'_, str>,
239        options: &ValidateOptions<'_>,
240    ) -> Result<Report, Error> {
241        check_well_formed(&text)?;
242        let schema_errors = match &self.schema {
243            None => Vec::new(),
244            Some(schema) => {
245                schema
246                    .validate(&text)
247                    .map_err(|e| match e {
248                        einvoice_xsd::DocumentError::Malformed {
249                            line,
250                            column,
251                            message,
252                        } => Error::NotXml {
253                            line,
254                            column,
255                            message,
256                        },
257                        einvoice_xsd::DocumentError::Unsupported {
258                            line,
259                            column,
260                            message,
261                        } => Error::unsupported(format!(
262                            "document, line {line}, column {column}: {message}"
263                        )),
264                    })?
265                    .errors
266            }
267        };
268        let transform_options = TransformOptions {
269            implicit_timezone: options.clock.map(|c| c.implicit_timezone()),
270            current_date_time: options.clock.map(|c| c.current_date_time()),
271            ..TransformOptions::default()
272        };
273        let mut stylesheets = Vec::with_capacity(self.stylesheets.len());
274        let count = self.stylesheets.len();
275        // The text, until the last stylesheet is given it.
276        let mut text = Some(text);
277        for (index, (entry, executable)) in self
278            .rule_set
279            .stylesheets()
280            .iter()
281            .zip(&self.stylesheets)
282            .enumerate()
283        {
284            let source = if index + 1 == count {
285                text.take()
286            } else {
287                text.as_deref().map(Cow::Borrowed)
288            }
289            .ok_or_else(|| Error::internal("the document text was given away early"))?;
290            let result =
291                executable.transform_with(source, options.document_uri, &transform_options);
292            let report = match result {
293                Ok(result) => StylesheetReport::new(
294                    entry,
295                    result.output,
296                    result.warnings,
297                    options.document_uri,
298                )?,
299                Err(e) => match transform_error(entry, &e) {
300                    // The schema errors already make the document invalid: the verdict
301                    // stands, the report says which stylesheet could not finish.
302                    Error::Transform {
303                        code,
304                        line,
305                        message,
306                        ..
307                    } if !schema_errors.is_empty() => StylesheetReport::failed(
308                        entry,
309                        StylesheetFailure {
310                            code,
311                            line,
312                            message,
313                        },
314                        options.document_uri,
315                    ),
316                    other => return Err(other),
317                },
318            };
319            stylesheets.push(report);
320        }
321        Ok(Report {
322            rule_set: RuleSetVersion {
323                name: self.rule_set.name().to_owned(),
324                title: self.rule_set.title().to_owned(),
325                version: self.rule_set.version().to_owned(),
326                schema: self.rule_set.schema(),
327            },
328            document_uri: options.document_uri.map(str::to_owned),
329            schema_errors,
330            stylesheets,
331        })
332    }
333}
334
335fn read(path: &Path) -> Result<Vec<u8>, Error> {
336    std::fs::read(path).map_err(|source| Error::Io {
337        path: PathBuf::from(path),
338        source,
339    })
340}
341
342/// Lower-case hexadecimal SHA-256.
343pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
344    const HEX: &[u8; 16] = b"0123456789abcdef";
345    let digest = Sha256::digest(bytes);
346    let mut hex = String::with_capacity(64);
347    for byte in digest {
348        hex.push(char::from(HEX[usize::from(byte >> 4)]));
349        hex.push(char::from(HEX[usize::from(byte & 0x0f)]));
350    }
351    hex
352}
353
354/// Checks the checksum of a stylesheet, loads and prepares it.
355fn prepare(
356    entry: &StylesheetEntry,
357    bytes: &[u8],
358    base_uri: Option<String>,
359) -> Result<Executable, Error> {
360    let actual = sha256_hex(bytes);
361    if actual != entry.sha256() {
362        return Err(Error::Checksum {
363            path: entry.path().to_owned(),
364            expected: entry.sha256().to_owned(),
365            actual,
366        });
367    }
368    let what = format!("stylesheet {} ({})", entry.name(), entry.path());
369    let text = decode(bytes).map_err(|e| Error::bundle(format!("{what}: {e}")))?;
370    let sheet = einvoice_xslt::load(text).map_err(|errors| {
371        let unsupported = errors.0.iter().any(|e| {
372            matches!(
373                e.kind,
374                LoadErrorKind::UnsupportedElement { .. }
375                    | LoadErrorKind::UnsupportedAttribute { .. }
376                    | LoadErrorKind::UnsupportedValue { .. }
377                    | LoadErrorKind::XPath { .. }
378            )
379        });
380        let message = format!("{what}: {}", first_lines(&errors.to_string()));
381        if unsupported {
382            Error::unsupported(message)
383        } else {
384            Error::bundle(message)
385        }
386    })?;
387    let executable = Executable::new(&sheet).map_err(|errors| {
388        Error::unsupported(format!("{what}: {}", first_lines(&errors.to_string())))
389    })?;
390    Ok(match base_uri {
391        Some(uri) => executable.with_base_uri(uri),
392        None => executable,
393    })
394}
395
396/// At most the first ten lines of a list of errors, with the number left out.
397fn first_lines(text: &str) -> String {
398    const MAX: usize = 10;
399    let lines: Vec<&str> = text.lines().collect();
400    if lines.len() <= MAX {
401        return lines.join("; ");
402    }
403    format!(
404        "{}; and {} more",
405        lines[..MAX].join("; "),
406        lines.len() - MAX
407    )
408}
409
410fn transform_error(entry: &StylesheetEntry, e: &TransformError) -> Error {
411    let at = e.line().map_or_else(String::new, |l| format!(", line {l}"));
412    match e.code() {
413        "UNSUPPORTED" => {
414            Error::unsupported(format!("stylesheet {}{at}: {}", entry.name(), e.message()))
415        }
416        // The document was checked before: a parse error here means two parsers
417        // disagree, which is a bug.
418        "INTERNAL" | "SXXP0003" => Error::internal(format!(
419            "stylesheet {}{at}: {}: {}",
420            entry.name(),
421            e.code(),
422            e.message()
423        )),
424        code => Error::Transform {
425            stylesheet: entry.name().to_owned(),
426            code: code.to_owned(),
427            line: e.line(),
428            message: e.message().to_owned(),
429        },
430    }
431}
432
433/// The UTF-8 byte order mark.
434const BOM: &[u8] = &[0xEF, 0xBB, 0xBF];
435
436/// The text of a document given as bytes: UTF-8, with or without a byte order mark,
437/// and an XML declaration, if any, naming UTF-8 or US-ASCII.
438fn decode(bytes: &[u8]) -> Result<&str, Error> {
439    refuse_utf16(bytes)?;
440    let bytes = bytes.strip_prefix(BOM).unwrap_or(bytes);
441    check_encoding(bytes)?;
442    std::str::from_utf8(bytes).map_err(|e| not_utf8(bytes, &e))
443}
444
445/// [`decode`] on a buffer, which becomes the text without being copied (the byte order
446/// mark, if any, is removed in place).
447fn decode_owned(mut bytes: Vec<u8>) -> Result<String, Error> {
448    refuse_utf16(&bytes)?;
449    if bytes.starts_with(BOM) {
450        bytes.drain(..BOM.len());
451    }
452    check_encoding(&bytes)?;
453    String::from_utf8(bytes).map_err(|e| not_utf8(e.as_bytes(), &e.utf8_error()))
454}
455
456/// The error for bytes (after the byte order mark) that are not UTF-8.
457fn not_utf8(bytes: &[u8], e: &std::str::Utf8Error) -> Error {
458    bad_at(bytes, e.valid_up_to(), format!("not UTF-8: {e}"))
459}
460
461/// A [`Error::NotXml`] at the byte `valid_up_to` of `bytes` (after the byte order mark).
462fn bad_at(bytes: &[u8], valid_up_to: usize, message: String) -> Error {
463    let before = &bytes[..valid_up_to];
464    let line_start = before
465        .iter()
466        .rposition(|&b| b == b'\n')
467        .map_or(0, |i| i + 1);
468    let line = before.split(|&b| b == b'\n').count();
469    let column = String::from_utf8_lossy(&before[line_start..])
470        .chars()
471        .count()
472        + 1;
473    Error::NotXml {
474        line: u32::try_from(line).unwrap_or(u32::MAX),
475        column: u32::try_from(column).unwrap_or(u32::MAX),
476        message,
477    }
478}
479
480/// Refuses a document that starts with a UTF-16 byte order mark.
481fn refuse_utf16(bytes: &[u8]) -> Result<(), Error> {
482    if bytes.starts_with(&[0xFE, 0xFF]) || bytes.starts_with(&[0xFF, 0xFE]) {
483        return Err(Error::unsupported(
484            "a UTF-16 document: only UTF-8 is supported",
485        ));
486    }
487    Ok(())
488}
489
490/// Checks the XML declaration of a document given as bytes (after the byte order mark,
491/// if any): its encoding, if any, must be UTF-8 or US-ASCII, and with US-ASCII every
492/// byte must be ASCII. Whether the bytes are UTF-8 is checked by the caller.
493fn check_encoding(bytes: &[u8]) -> Result<(), Error> {
494    let ascii = match declared_encoding(bytes) {
495        None => false,
496        Some(e) if e.eq_ignore_ascii_case("utf-8") || e.eq_ignore_ascii_case("utf8") => false,
497        Some(e) if e.eq_ignore_ascii_case("us-ascii") || e.eq_ignore_ascii_case("ascii") => true,
498        Some(e) => {
499            return Err(Error::unsupported(format!(
500                "the {e} encoding: only UTF-8 is supported"
501            )));
502        }
503    };
504    if ascii && let Some(i) = bytes.iter().position(|b| !b.is_ascii()) {
505        return Err(bad_at(
506            bytes,
507            i,
508            "a byte outside US-ASCII, the encoding the XML declaration names".to_owned(),
509        ));
510    }
511    Ok(())
512}
513
514/// The `encoding` pseudo-attribute of the XML declaration, if any.
515fn declared_encoding(bytes: &[u8]) -> Option<&str> {
516    let declaration = bytes.strip_prefix(b"<?xml")?;
517    if !declaration.first().is_some_and(u8::is_ascii_whitespace) {
518        return None;
519    }
520    let end = declaration.windows(2).position(|w| w == b"?>")?;
521    let declaration = std::str::from_utf8(&declaration[..end]).ok()?;
522    let rest = &declaration[declaration.find("encoding")? + "encoding".len()..];
523    let rest = rest.trim_start().strip_prefix('=')?.trim_start();
524    let quote = rest.chars().next().filter(|c| *c == '"' || *c == '\'')?;
525    let value = &rest[1..];
526    value.find(quote).map(|end| &value[..end])
527}
528
529/// Checks that the text is namespace-well-formed XML without a document type
530/// declaration, as the stylesheets' parser requires.
531fn check_well_formed(text: &str) -> Result<(), Error> {
532    let options = ParsingOptions {
533        allow_dtd: false,
534        nodes_limit: u32::MAX,
535        ..ParsingOptions::default()
536    };
537    match roxmltree::Document::parse_with_options(text, options) {
538        Ok(_) => Ok(()),
539        Err(roxmltree::Error::DtdDetected) => Err(Error::unsupported(
540            "a document type declaration (DTD): its entities and default attributes could change the document, so it is refused",
541        )),
542        Err(e) => Err(Error::NotXml {
543            line: e.pos().row,
544            column: e.pos().col,
545            message: e.to_string(),
546        }),
547    }
548}
549
550#[cfg(test)]
551mod tests {
552    use super::*;
553
554    #[test]
555    fn decoding_a_buffer_gives_the_same_result() {
556        for bytes in [
557            &b"<a/>"[..],
558            b"\xEF\xBB\xBF<a>\xC3\xA9</a>",
559            b"<?xml version='1.0' encoding='UTF-8'?><a/>",
560            b"\xFF\xFE<\0a\0/\0>\0",
561            b"\xFE\xFF\0<\0a\0/\0>",
562            b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>",
563            b"<a>\n  \xC3\xA9\xFF</a>",
564            b"\xEF\xBB\xBF<a>\n\xFF</a>",
565            b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>",
566            b"\xEF\xBB\xBF",
567            b"",
568        ] {
569            let borrowed = decode(bytes).map(str::to_owned).map_err(|e| e.to_string());
570            let owned = decode_owned(bytes.to_vec()).map_err(|e| e.to_string());
571            assert_eq!(owned, borrowed, "{bytes:?}");
572        }
573    }
574
575    #[test]
576    fn decoding() {
577        assert_eq!(decode(b"\xEF\xBB\xBF<a/>").unwrap(), "<a/>");
578        assert_eq!(
579            decode(b"<?xml version='1.0' encoding='UTF-8'?><a/>").unwrap(),
580            "<?xml version='1.0' encoding='UTF-8'?><a/>"
581        );
582        assert!(matches!(
583            decode(b"\xFF\xFE<\0a\0/\0>\0"),
584            Err(Error::Unsupported { .. })
585        ));
586        assert!(matches!(
587            decode(b"<?xml version='1.0' encoding='ISO-8859-1'?><a/>"),
588            Err(Error::Unsupported { .. })
589        ));
590        match decode(b"<a>\n  \xC3\xA9\xFF</a>") {
591            Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
592            other => panic!("{other:?}"),
593        }
594        match decode(b"<?xml version=\"1.0\" encoding=\"US-ASCII\"?>\n<a>\xC3\xA9</a>") {
595            Err(Error::NotXml { line, column, .. }) => assert_eq!((line, column), (2, 4)),
596            other => panic!("{other:?}"),
597        }
598        assert_eq!(
599            declared_encoding(b"<?xml-stylesheet encoding='x'?><a/>"),
600            None
601        );
602    }
603
604    #[test]
605    fn well_formedness() {
606        assert!(check_well_formed("<a/>").is_ok());
607        match check_well_formed("<a>\n<b></a>") {
608            Err(Error::NotXml { line, .. }) => assert_eq!(line, 2),
609            other => panic!("{other:?}"),
610        }
611        assert!(matches!(
612            check_well_formed("<!DOCTYPE a [<!ENTITY e 'x'>]><a>&e;</a>"),
613            Err(Error::Unsupported { .. })
614        ));
615        assert!(matches!(
616            check_well_formed("<p:a/>"),
617            Err(Error::NotXml { .. })
618        ));
619    }
620
621    #[test]
622    fn checksums() {
623        assert_eq!(
624            sha256_hex(b"abc"),
625            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
626        );
627    }
628
629    #[test]
630    fn errors_are_summarised() {
631        let many: Vec<String> = (1..=12).map(|i| format!("line {i}: x")).collect();
632        let text = first_lines(&many.join("\n"));
633        assert!(text.ends_with("line 10: x; and 2 more"), "{text}");
634    }
635}