Skip to main content

quarb_compose/
lib.rs

1//! Adapter composition: descend *through* a leaf into its content.
2//!
3//! A filesystem's `.json` file, an archive's `config.xml` entry, a
4//! message's HTML part — trees of files are full of leaves whose
5//! *content* is itself a tree in another notation. Composition
6//! grafts that inner tree onto the outer one: wrap any adapter in
7//! a [`ComposeAdapter`] and a leaf whose name or content says
8//! "parse me" gains the parsed arbor as its children:
9//!
10//! ```text
11//! /data/store.json/books/*[/price:: < 12]/title::
12//!       └ outer (fs) ┘└──── inner (json) ────┘
13//! ```
14//!
15//! The graft happens on first touch, lazily: a leaf is only read
16//! and parsed when navigation actually enters it. Detection is by
17//! extension (`.json`, `.xml`, `.html`/`.htm`/`.xhtml`/`.svg`,
18//! `.csv`/`.tsv`), else by sniffing the content's first
19//! character; a parse failure simply leaves the leaf a leaf.
20//! Archive leaves (`.zip`, `.tar`, `.tar.gz`) are binary, so they
21//! graft by *path* rather than content — available when the outer
22//! substrate has real paths (see
23//! [`ComposeAdapter::with_source_paths`]) — and the grafted
24//! archive composes in turn, so one path runs filesystem → tar →
25//! JSON without a seam. The
26//! inner root is *identified with* the outer leaf node — the leaf
27//! itself answers the inner root's children — so there is no
28//! phantom node between the file and its content.
29//!
30//! Locators show the boundary with a bang, jar-URL style:
31//! `store.json!/books/1`.
32
33use quarb::source::SourceDecoding;
34use quarb::{AstAdapter, NodeId, Value};
35use std::cell::RefCell;
36use std::collections::HashMap;
37use std::path::PathBuf;
38
39/// A parsed inner arbor.
40enum Inner {
41    Json(quarb_json::JsonAdapter),
42    Xml(quarb_xml::XmlAdapter),
43    Html(quarb_html::HtmlAdapter),
44    Text(quarb_text::TextModel),
45    Csv(quarb_csv::CsvAdapter),
46    #[cfg(feature = "source")]
47    Syntax(quarb_tree_sitter::TreeSitterAdapter),
48    #[cfg(feature = "source")]
49    Code(quarb_code::CodeModel),
50    /// A grafted archive, itself composed so its own parseable
51    /// entries graft in turn.
52    Archive(Box<ComposeAdapter<quarb_archive::ArchiveAdapter>>),
53}
54
55impl Inner {
56    fn adapter(&self) -> &dyn AstAdapter {
57        match self {
58            Inner::Json(a) => a,
59            Inner::Xml(a) => a,
60            Inner::Html(a) => a,
61            Inner::Text(a) => a,
62            Inner::Csv(a) => a,
63            #[cfg(feature = "source")]
64            Inner::Syntax(a) => a,
65            #[cfg(feature = "source")]
66            Inner::Code(a) => a,
67            Inner::Archive(a) => &**a,
68        }
69    }
70
71    fn locator(&self, node: NodeId) -> String {
72        match self {
73            Inner::Json(a) => a.pointer(node),
74            Inner::Xml(a) => a.locator(node),
75            Inner::Html(a) => a.locator(node),
76            Inner::Text(a) => a.locator(node),
77            Inner::Csv(a) => a.locator(node),
78            #[cfg(feature = "source")]
79            Inner::Syntax(a) => a.locator(node),
80            #[cfg(feature = "source")]
81            Inner::Code(a) => a.locator(node),
82            Inner::Archive(a) => a.locator(node, |o| a.outer().locator(o)),
83        }
84    }
85}
86
87/// The level source-file leaves graft at: the syntax level (the
88/// literal parse — the default) or the code level (identifiers
89/// as names). Chosen per mount by the `code:` target prefix, and
90/// inherited by nested composes (an archive inside a `code:`
91/// mount grafts its source entries at the code level too) — the
92/// filesystem-into-declarations namespace has no seam.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
94pub enum SourceGraft {
95    #[default]
96    Syntax,
97    Code,
98}
99
100/// The level marked-up documents (`.html`, `.htm`, `.md`) graft
101/// at: their DOM by default, or the text level — sections,
102/// paragraphs, lists, and what the page declares about itself
103/// in its head — when the mount asks for the reader's model
104/// (`text:` on an archive or directory).
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
106pub enum DocumentGraft {
107    #[default]
108    Dom,
109    Text,
110}
111
112/// The declaration reporter a host hands the source boundary: by
113/// the source's name, the XML prologue for XML-family names, the
114/// HTML prescan for HTML names, both tried (prologue first) for a
115/// name that says nothing — a plain text file declares nothing
116/// either way.
117pub fn declared_encoding(name: &str, bytes: &[u8]) -> Option<String> {
118    let ext = name.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
119    match ext.as_str() {
120        "xml" | "svg" | "xhtml" | "fb2" | "tei" | "rss" | "atom" | "opml" | "xsd" | "xsl" => {
121            quarb_xml::declared_encoding(bytes)
122        }
123        "html" | "htm" => quarb_html::declared_encoding(bytes),
124        // RTF's header names its code page (`\ansicpg1251`).
125        "rtf" => quarb_text_rtf::declared_encoding(bytes),
126        _ => quarb_xml::declared_encoding(bytes).or_else(|| quarb_html::declared_encoding(bytes)),
127    }
128}
129
130/// The rule a host mount carries: `?encoding=` validated at open,
131/// the reporter above.
132pub fn source_decoding(
133    explicit: Option<&str>,
134) -> Result<SourceDecoding, quarb::source::SourceError> {
135    SourceDecoding::default()
136        .with_declared(declared_encoding)
137        .with_option(explicit)
138}
139
140/// Read one file at the source boundary under the host rule:
141/// `?encoding=`, then a byte-order mark, then what the file
142/// declares, then strict UTF-8.
143pub fn read_source(
144    path: &std::path::Path,
145    explicit: Option<&str>,
146) -> std::io::Result<Result<quarb::source::Decoded, quarb::source::SourceError>> {
147    let bytes = std::fs::read(path)?;
148    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
149    Ok(source_decoding(explicit).and_then(|d| d.decode(name, &bytes)))
150}
151
152/// The bytes of an archive's member: the hook an archive mount and
153/// every archive grafted inside another hand to
154/// [`ComposeAdapter::with_source_bytes`].
155pub fn archive_member_bytes(a: &quarb_archive::ArchiveAdapter, node: NodeId) -> Option<Vec<u8>> {
156    a.member_bytes(node)
157}
158
159/// Whether a leaf's name says archive: the one list quarb-archive
160/// keeps.
161fn archive_name(name: &str) -> bool {
162    quarb_archive::archive_extension(name.rsplit('.').next().unwrap_or(""))
163}
164
165/// The notations a leaf can be declared to carry (spec: Grafting):
166/// the one vocabulary `?format=NOTATION` on a mount and `<NOTATION>`
167/// on a step share, the Quarb Readings' names of the formats. Source
168/// languages come besides, by their grammar names.
169pub const NOTATIONS: &[&str] = &[
170    "json", "jsonl", "yaml", "toml", "xml", "html", "markdown", "text", "csv", "tsv", "fb2",
171];
172
173/// The canonical notation a name declares by its extension (`.json`,
174/// `.yml`, `.htm`, `.ndjson`), a source language by its grammar's
175/// extension; None for no extension or one no reader takes.
176pub fn notation_of_name(name: &str) -> Option<String> {
177    let (_, ext) = name.rsplit_once('.')?;
178    let ext = ext.to_ascii_lowercase();
179    let n = match ext.as_str() {
180        "json" => "json",
181        "jsonl" | "ndjson" => "jsonl",
182        "xml" | "svg" | "xhtml" => "xml",
183        "fb2" => "fb2",
184        "html" | "htm" => "html",
185        "yaml" | "yml" => "yaml",
186        "toml" => "toml",
187        "md" | "markdown" => "markdown",
188        "txt" => "text",
189        "csv" => "csv",
190        "tsv" => "tsv",
191        _ => {
192            #[cfg(feature = "source")]
193            if quarb_tree_sitter::supported(&ext) {
194                return Some(ext);
195            }
196            return None;
197        }
198    };
199    Some(n.to_string())
200}
201
202/// Whether a word names a notation (`?format=`, `<NOTATION>`).
203pub fn is_notation(name: &str) -> bool {
204    let n = canonical_notation(name);
205    if NOTATIONS.contains(&n.as_str()) {
206        return true;
207    }
208    #[cfg(feature = "source")]
209    if quarb_tree_sitter::supported(&n) {
210        return true;
211    }
212    false
213}
214
215/// A notation's canonical spelling: the extension synonyms read as
216/// their notation (`yml` yaml, `md` markdown, `ndjson` jsonl, `txt`
217/// text).
218pub fn canonical_notation(name: &str) -> String {
219    let n = name.trim().to_ascii_lowercase();
220    match n.as_str() {
221        "yml" => "yaml".into(),
222        "md" => "markdown".into(),
223        "ndjson" => "jsonl".into(),
224        "txt" | "plain" => "text".into(),
225        "htm" => "html".into(),
226        _ => n,
227    }
228}
229
230/// The notation a text declares about itself in its first bytes
231/// (the Quarb Readings' declared identity): an XML declaration or a
232/// DOCTYPE. Nothing else counts; a brace or a bracket is a guess,
233/// not a declaration.
234pub fn self_declared(content: &str) -> Option<&'static str> {
235    let t = content.trim_start_matches('\u{feff}').trim_start();
236    if t.starts_with("<?xml") {
237        return Some("xml");
238    }
239    // by `get`: the ninth byte of a text that opens with a curly
240    // quote is no character boundary, and a cut there panics
241    if t.get(..9)
242        .is_some_and(|w| w.eq_ignore_ascii_case("<!doctype"))
243    {
244        let rest = t[9..].trim_start();
245        return Some(
246            if rest.len() >= 4 && rest[..4].eq_ignore_ascii_case("html") {
247                "html"
248            } else {
249                "xml"
250            },
251        );
252    }
253    None
254}
255
256/// Parse `content` as `notation` (canonical): the reader that
257/// notation names, at the mount's graft levels. None when the text
258/// does not parse as it, or no reader here takes the notation.
259fn parse_as(
260    notation: &str,
261    content: &str,
262    graft: SourceGraft,
263    doc: DocumentGraft,
264    csv: quarb_csv::CsvOptions,
265) -> Option<Inner> {
266    #[cfg(not(feature = "source"))]
267    let _ = graft;
268    let ext = canonical_notation(notation);
269    match ext.as_str() {
270        "json" => {
271            return quarb_json::JsonAdapter::parse(content)
272                .ok()
273                .map(Inner::Json);
274        }
275        "jsonl" => {
276            return quarb_json::JsonAdapter::parse_lines(content)
277                .ok()
278                .map(Inner::Json);
279        }
280        "xml" => {
281            // A FictionBook declared by its namespace grafts at the
282            // text level through the koine route when the level
283            // asks for it; the DOM otherwise, like any XML.
284            #[cfg(feature = "koine")]
285            if doc == DocumentGraft::Text
286                && quarb_text_koine::detect_xml_kind(content) == Some("fb2")
287                && let Ok(m) = quarb_text_koine::parse_xml_as(content, "fb2")
288            {
289                return Some(Inner::Text(m));
290            }
291            return quarb_xml::XmlAdapter::parse(content).ok().map(Inner::Xml);
292        }
293        "fb2" => {
294            #[cfg(feature = "koine")]
295            if doc == DocumentGraft::Text
296                && let Ok(m) = quarb_text_koine::parse_xml_as(content, "fb2")
297            {
298                return Some(Inner::Text(m));
299            }
300            return quarb_xml::XmlAdapter::parse(content).ok().map(Inner::Xml);
301        }
302        "html" => {
303            return Some(match doc {
304                DocumentGraft::Dom => Inner::Html(quarb_html::HtmlAdapter::parse(content)),
305                DocumentGraft::Text => Inner::Text(quarb_text_html::parse(content)),
306            });
307        }
308        "yaml" => return quarb_yaml::parse(content).ok().map(Inner::Json),
309        "toml" => return quarb_toml::parse(content).ok().map(Inner::Json),
310        "markdown" => {
311            return Some(match doc {
312                DocumentGraft::Dom => Inner::Html(quarb_markdown::parse(content)),
313                DocumentGraft::Text => Inner::Text(quarb_text_markdown::parse(content)),
314            });
315        }
316        // Plain text grafts at the text level (blank-line
317        // paragraphs); html/md keep their DOM-level graft.
318        "text" => return Some(Inner::Text(quarb_text::TextModel::parse_plain(content))),
319        "csv" => {
320            return quarb_csv::CsvAdapter::parse_declared(content, b',', csv)
321                .ok()
322                .map(Inner::Csv);
323        }
324        "tsv" => {
325            return quarb_csv::CsvAdapter::parse_declared(content, b'\t', csv)
326                .ok()
327                .map(Inner::Csv);
328        }
329        #[cfg(feature = "source")]
330        ext if quarb_tree_sitter::supported(ext) => {
331            return match graft {
332                SourceGraft::Syntax => quarb_tree_sitter::TreeSitterAdapter::parse(content, ext)
333                    .ok()
334                    .map(Inner::Syntax),
335                SourceGraft::Code => quarb_code::CodeModel::parse(content, ext)
336                    .ok()
337                    .map(Inner::Code),
338            };
339        }
340        _ => {}
341    }
342    None
343}
344
345/// The text reading of a string in the notations this crate
346/// parses at the text level: plain text, Markdown, HTML, RTF,
347/// CoNLL-U, and the XML vocabularies the koine route knows.
348fn text_reading_native(notation: &str, text: &str) -> Option<Inner> {
349    let model = match notation {
350        "text" | "plain" => quarb_text::TextModel::parse_plain(text),
351        "markdown" | "md" => quarb_text_markdown::parse(text),
352        "html" | "htm" => quarb_text_html::parse(text),
353        "rtf" => quarb_text_rtf::parse(text.as_bytes()).ok()?,
354        "conllu" => quarb_text::TextModel::parse_conllu_text(text).ok()?,
355        #[cfg(feature = "koine")]
356        "fb2" | "usfm" | "sfm" | "tei" | "docbook" | "jats" | "usx" | "osis" | "rnc"
357        | "opencorpora" | "proiel" => {
358            let kind = match notation {
359                "sfm" => "usfm",
360                k => k,
361            };
362            quarb_text_koine::parse_xml_as(text, kind).ok()?
363        }
364        #[cfg(feature = "koine")]
365        "xml" => {
366            let kind = quarb_text_koine::detect_xml_kind(text)?;
367            quarb_text_koine::parse_xml_as(text, kind).ok()?
368        }
369        _ => return None,
370    };
371    Some(Inner::Text(model))
372}
373
374/// Whether a reading operand named no notation and the string
375/// declared none (`graft(code)` over plain text).
376fn named_is_text(label: &str) -> bool {
377    label.ends_with(":text")
378}
379
380/// The code reading of a string: the language by its extension or
381/// its name (`rs`/`rust`, `py`/`python`, `js`/`javascript`, `c`).
382#[cfg(feature = "source")]
383fn code_graft(text: &str, language: &str) -> Option<Inner> {
384    let ext = match language {
385        "rust" => "rs",
386        "python" => "py",
387        "javascript" => "js",
388        other => other,
389    };
390    if !quarb_tree_sitter::supported(ext) {
391        return None;
392    }
393    quarb_code::CodeModel::parse(text, ext)
394        .ok()
395        .map(Inner::Code)
396}
397
398#[cfg(not(feature = "source"))]
399fn code_graft(_text: &str, _language: &str) -> Option<Inner> {
400    None
401}
402
403/// One graft: an inner arbor mounted at an outer leaf.
404struct Graft {
405    outer: NodeId,
406    inner: Inner,
407    /// The notation the leaf was read as.
408    notation: String,
409}
410
411/// Grafted node ids carry this tag bit; the rest indexes the intern
412/// table. The bit sits at the top of the 56-bit id window that
413/// `MountAdapter` leaves an inner adapter — it reserves the high byte
414/// (bits 56–63) for the mount index — so a grafted id survives being
415/// packed into a mount and still round-trips. It must stay below bit
416/// 56 for that reason; the top bit (1 << 63) collided with the mount
417/// byte. Outer adapters use small sequential indices, far below this
418/// bit, so a set bit 55 unambiguously marks a graft.
419const GRAFT_BIT: u64 = 1 << 55;
420
421/// Any adapter, with parseable leaf content grafted as subtrees.
422/// A host's reader for a document leaf: the path in, its text-level
423/// model out, or `None` to leave the leaf to the default grafting.
424pub type DocumentReader = std::rc::Rc<dyn Fn(&std::path::Path) -> Option<quarb_text::TextModel>>;
425
426/// A host's reader for a document leaf that has no path: the outer
427/// adapter and the leaf in, its text-level model out (a row's body
428/// under `?doc=`, a model file's `document` member), or `None` to
429/// leave the leaf to the default grafting (spec: The Corpus Reading).
430pub type DocumentNodes<A> = std::rc::Rc<dyn Fn(&A, NodeId) -> Option<quarb_text::TextModel>>;
431
432/// A host's reading of a lone string (spec: Grafting,
433/// `graft(READING:NOTATION)`): the reading's name (`text`, `corpus`,
434/// `lit`, `koine`), the notation the string is to be read as, and
435/// the string in; its text-level model out, `Some(Err)` the
436/// reading's own refusal, `None` where the host has no such reading.
437pub type StringReader =
438    std::rc::Rc<dyn Fn(&str, &str, &str) -> Option<Result<quarb_text::TextModel, String>>>;
439
440/// The readings a graft operand may name as a prefix
441/// (`graft(text:markdown)`), as the mount prefixes spell them.
442pub const READINGS: &[&str] = &["text", "corpus", "lit", "koine", "code", "web"];
443
444pub struct ComposeAdapter<A: AstAdapter> {
445    outer: A,
446    grafts: RefCell<Vec<Graft>>,
447    /// Outer leaf → its graft index (`None`: probed, not
448    /// parseable).
449    probed: RefCell<HashMap<NodeId, Option<usize>>>,
450    /// (graft, inner id) → interned composite id, and the reverse.
451    interned: RefCell<HashMap<(usize, NodeId), NodeId>>,
452    reverse: RefCell<Vec<(usize, NodeId)>>,
453    /// Maps an outer leaf to a filesystem path, when the outer
454    /// substrate has one. Enables archive grafts, which are
455    /// binary and open by path rather than parsing from text.
456    source_path: Option<fn(&A, NodeId) -> Option<PathBuf>>,
457    /// Maps an outer leaf to its bytes, when the outer substrate
458    /// holds them and has no path to give (a member of an archive).
459    /// Enables the graft of an archive inside an archive.
460    source_bytes: Option<fn(&A, NodeId) -> Option<Vec<u8>>>,
461    /// The level source-file leaves graft at.
462    source_graft: SourceGraft,
463    /// The level marked-up documents graft at.
464    document_graft: DocumentGraft,
465    /// Maps an outer leaf to the URL its document is served
466    /// from, so a text-level graft joins relative references
467    /// against it and `-->` can land on a sibling document.
468    document_url: Option<fn(&A, NodeId) -> Option<String>>,
469    /// URL → outer leaf, built on first `document_by_ref`.
470    urls: RefCell<Option<HashMap<String, NodeId>>>,
471    /// The host's own reading of a document leaf, by path: when it
472    /// answers, its model is the graft (a corpus reading with its
473    /// tokens, a format this crate does not parse); when it
474    /// declines, the leaf grafts as it otherwise would.
475    document_reader: Option<DocumentReader>,
476    /// The mount's rule at the source boundary (`?encoding=` and
477    /// the declaration reporter): every leaf this layer reads by
478    /// path decodes under it, and the layer answers `:::encoding`
479    /// / `:::replaced` on the leaf it grafted. A leaf with no path
480    /// grafts from the outer adapter's text as before.
481    decoding: SourceDecoding,
482    /// Per graft: the record of its decoding, when this layer did
483    /// it.
484    decoded: RefCell<HashMap<usize, (String, usize)>>,
485    /// The mount's `?delimiter=` / `?decimal=`, for the delimited
486    /// leaves it grafts.
487    csv: quarb_csv::CsvOptions,
488    /// The mount's `?format=NOTATION`: every leaf beneath reads as
489    /// it (spec: Grafting).
490    default_notation: Option<String>,
491    /// The host's reading of document leaves that have no path.
492    document_nodes: Option<DocumentNodes<A>>,
493    /// The grafts made on demand from a text (`graft(NOTATION)`):
494    /// each a free root, its `outer` the composite id of its own
495    /// inner root rather than an outer leaf, so nothing of the
496    /// outer substrate is asked about it.
497    free: RefCell<std::collections::HashSet<usize>>,
498    /// The host's readings of a lone string, for
499    /// `graft(READING:NOTATION)`.
500    string_reader: Option<StringReader>,
501    /// Graft on demand only: no leaf is probed for a declared
502    /// notation (the layer a host puts over a plain source so that
503    /// `graft(NOTATION)` and a `<NOTATION>` trait at a step have a
504    /// composing layer to answer from, the leaves otherwise as they
505    /// were).
506    on_demand_only: bool,
507}
508
509impl<A: AstAdapter> ComposeAdapter<A> {
510    pub fn new(outer: A) -> Self {
511        ComposeAdapter {
512            outer,
513            grafts: RefCell::new(Vec::new()),
514            probed: RefCell::new(HashMap::new()),
515            interned: RefCell::new(HashMap::new()),
516            reverse: RefCell::new(Vec::new()),
517            source_path: None,
518            source_bytes: None,
519            source_graft: SourceGraft::default(),
520            document_graft: DocumentGraft::default(),
521            document_url: None,
522            urls: RefCell::new(None),
523            document_reader: None,
524            decoding: SourceDecoding::default(),
525            decoded: RefCell::new(HashMap::new()),
526            csv: quarb_csv::CsvOptions::default(),
527            default_notation: None,
528            document_nodes: None,
529            free: RefCell::new(std::collections::HashSet::new()),
530            string_reader: None,
531            on_demand_only: false,
532        }
533    }
534
535    /// Graft on demand only (`graft(NOTATION)`, a `<NOTATION>` trait
536    /// at a step): no leaf is read for a declared notation of its
537    /// own, so a plain source keeps its leaves as they were.
538    pub fn on_demand_only(mut self) -> Self {
539        self.on_demand_only = true;
540        self
541    }
542
543    /// The host's readings of a lone string (`graft(corpus:latex)`):
544    /// without one, a reading prefix other than `code` refuses.
545    pub fn with_string_reader(mut self, reader: StringReader) -> Self {
546        self.string_reader = Some(reader);
547        self
548    }
549
550    /// The delimited-text options for this mount (builder-style).
551    /// The host's reading of document leaves by node: a leaf the
552    /// reader answers grafts as that text-level model (the leaves
553    /// `?doc=` names, a model file's `document` members).
554    pub fn with_document_nodes(mut self, reader: DocumentNodes<A>) -> Self {
555        self.document_nodes = Some(reader);
556        self
557    }
558
559    /// Every leaf beneath the mount reads as `notation`, the mount's
560    /// `?format=NOTATION` (spec: Grafting); a leaf whose text does not
561    /// parse as it stays a leaf.
562    pub fn with_default_notation(mut self, notation: Option<String>) -> Self {
563        self.default_notation = notation.map(|n| canonical_notation(&n));
564        self
565    }
566
567    pub fn with_csv_options(mut self, csv: quarb_csv::CsvOptions) -> Self {
568        self.csv = csv;
569        self
570    }
571
572    /// The source-boundary rule for this mount (builder-style):
573    /// the `?encoding=` option and the reporter the host chose.
574    /// Reaches grafted archives too.
575    pub fn with_decoding(mut self, decoding: SourceDecoding) -> Self {
576        self.decoding = decoding;
577        self
578    }
579
580    /// Hand document leaves to the host's reader first
581    /// (builder-style); needs the outer leaves' paths
582    /// ([`with_source_paths`](Self::with_source_paths)).
583    pub fn with_document_reader(mut self, reader: DocumentReader) -> Self {
584        self.document_reader = Some(reader);
585        self
586    }
587
588    /// Declare where each outer leaf's document is served from
589    /// (builder-style): a text-level graft joins its relative
590    /// references against that URL, and `-->` from any graft
591    /// lands on the leaf holding the referenced document (its
592    /// fragment's bearer when named) without a host registration.
593    pub fn with_document_urls(mut self, document_url: fn(&A, NodeId) -> Option<String>) -> Self {
594        self.document_url = Some(document_url);
595        self
596    }
597
598    /// The outer leaf serving `url` (fragment-stripped), from the
599    /// declared URLs; the whole outer tree is walked once.
600    fn leaf_by_url(&self, url: &str) -> Option<NodeId> {
601        let f = self.document_url?;
602        if self.urls.borrow().is_none() {
603            let mut map = HashMap::new();
604            let mut stack = vec![self.outer.root()];
605            while let Some(n) = stack.pop() {
606                let kids = self.outer.children(n);
607                if kids.is_empty() {
608                    if let Some(u) = f(&self.outer, n) {
609                        map.entry(u.split('#').next().unwrap_or(&u).to_string())
610                            .or_insert(n);
611                    }
612                } else {
613                    stack.extend(kids);
614                }
615            }
616            *self.urls.borrow_mut() = Some(map);
617        }
618        self.urls.borrow().as_ref()?.get(url).copied()
619    }
620
621    /// Choose the level source-file leaves graft at
622    /// (builder-style; the default is the syntax level).
623    pub fn with_source_graft(mut self, graft: SourceGraft) -> Self {
624        self.source_graft = graft;
625        self
626    }
627
628    /// Choose the level marked-up documents graft at
629    /// (builder-style; the default is the DOM).
630    pub fn with_document_graft(mut self, graft: DocumentGraft) -> Self {
631        self.document_graft = graft;
632        self
633    }
634
635    /// Like [`new`](Self::new), with a hook mapping outer leaves
636    /// to filesystem paths, so archive leaves (`.zip`,
637    /// `.tar[.gz]`) graft too. The grafted archive composes in
638    /// turn: its own parseable entries graft, and one path walks
639    /// filesystem → archive → document.
640    pub fn with_source_paths(outer: A, source_path: fn(&A, NodeId) -> Option<PathBuf>) -> Self {
641        ComposeAdapter {
642            source_path: Some(source_path),
643            ..Self::new(outer)
644        }
645    }
646
647    /// A hook mapping outer leaves to their bytes (builder-style):
648    /// an archive leaf with no filesystem path, a member of an
649    /// archive, grafts from them, and composes in turn.
650    pub fn with_source_bytes(mut self, bytes: fn(&A, NodeId) -> Option<Vec<u8>>) -> Self {
651        self.source_bytes = Some(bytes);
652        self
653    }
654
655    /// The wrapped adapter (for outer-specific calls).
656    pub fn outer(&self) -> &A {
657        &self.outer
658    }
659
660    /// A combined locator: `outer_locator(leaf)!inner-path` for
661    /// grafted nodes.
662    pub fn locator(&self, node: NodeId, outer_locator: impl Fn(NodeId) -> String) -> String {
663        match self.split(node) {
664            None => outer_locator(node),
665            Some((g, inner)) => {
666                let grafts = self.grafts.borrow();
667                let graft = &grafts[g];
668                if self.free.borrow().contains(&g) {
669                    // A graft on demand has no outer leaf: the text
670                    // it was parsed from stands for the source.
671                    return format!("graft({})!{}", graft.notation, graft.inner.locator(inner));
672                }
673                format!(
674                    "{}!{}",
675                    outer_locator(graft.outer),
676                    graft.inner.locator(inner)
677                )
678            }
679        }
680    }
681
682    /// Graft a text on demand (spec: Grafting, `graft(NOTATION)`).
683    /// The operand is written as a mount target is: `NOTATION` reads
684    /// the string under the notation's default reading (`json`; the
685    /// DOM for `markdown` and `html`; `text` is plain text under its
686    /// only reading); `READING:NOTATION` reads it under that
687    /// reading over that notation, as `READING:file.ext` would read
688    /// a source (`text:markdown`, `corpus:latex`, `koine:markdown`,
689    /// `lit:tei`, `code:rust`); `READING` alone takes the notation
690    /// the string declares (an XML declaration, a DOCTYPE) and plain
691    /// text otherwise; no operand takes the default reading of a
692    /// self-declaring string and refuses one that declares nothing.
693    /// The parsed document becomes a free root, parentless in the
694    /// arbor, that a path walks into; `Err` names what did not parse
695    /// or what the operand did not name. The `web` reading reads a
696    /// crawl, not a lone string, and refuses.
697    pub fn graft_text(&self, text: &str, operand: Option<&str>) -> Result<NodeId, String> {
698        let (reading, named): (Option<&str>, Option<String>) = match operand.map(str::trim) {
699            None | Some("") => (None, None),
700            Some(op) => match op.split_once(':') {
701                Some((r, n)) if READINGS.contains(&r) => (
702                    Some(r),
703                    (!n.trim().is_empty()).then(|| canonical_notation(n)),
704                ),
705                None if READINGS.contains(&op) => (Some(op), None),
706                _ => (None, Some(canonical_notation(op))),
707            },
708        };
709        let shown = operand.unwrap_or("").trim();
710        if reading == Some("web") {
711            return Err(format!(
712                "graft({shown}): the web reading reads a crawl, not a lone string"
713            ));
714        }
715        let declared = self_declared(text).map(str::to_string);
716        let notation = match (reading, named) {
717            (_, Some(n)) => n,
718            (Some(_), None) => declared.unwrap_or_else(|| "text".to_string()),
719            (None, None) => declared.ok_or_else(|| {
720                format!(
721                    "graft: the text declares no notation (no XML declaration or DOCTYPE); \
722                     name one, graft(NOTATION), with NOTATION one of {}, or a reading, \
723                     graft(text), graft(corpus:markdown)",
724                    NOTATIONS.join(", ")
725                )
726            })?,
727        };
728        let label = match reading {
729            Some(r) => format!("{r}:{notation}"),
730            None => notation.clone(),
731        };
732        let inner = match reading {
733            None => {
734                if !is_notation(&notation) {
735                    return Err(format!(
736                        "graft({shown}): '{notation}' names no notation; one of {} (or a \
737                         source language), or a reading prefix, graft(text:{notation})",
738                        NOTATIONS.join(", ")
739                    ));
740                }
741                // The notation's default reading: the DOM for the
742                // marked-up ones, plain text for `text`.
743                parse_as(
744                    &notation,
745                    text,
746                    self.source_graft,
747                    DocumentGraft::Dom,
748                    self.csv.clone(),
749                )
750                .ok_or_else(|| format!("graft({shown}): the text does not parse as {notation}"))?
751            }
752            Some("code") => {
753                if named_is_text(&label) {
754                    return Err(
755                        "graft(code): name the language, graft(code:rust), graft(code:py)"
756                            .to_string(),
757                    );
758                }
759                code_graft(text, &notation).ok_or_else(|| {
760                    format!(
761                        "graft({shown}): no source language '{notation}' here (rs/rust, \
762                         py/python, js/javascript, c), or the text does not parse as it"
763                    )
764                })?
765            }
766            Some(r) => {
767                // The host's reading first; the text reading of the
768                // notations this crate parses stands where the host
769                // has none.
770                let host = self
771                    .string_reader
772                    .as_ref()
773                    .and_then(|read| read(r, &notation, text));
774                match host {
775                    Some(Ok(model)) => Inner::Text(model),
776                    Some(Err(m)) => return Err(format!("graft({shown}): {m}")),
777                    None => match (r, text_reading_native(&notation, text)) {
778                        ("text", Some(inner)) => inner,
779                        _ if self.string_reader.is_none() => {
780                            return Err(format!(
781                                "graft({shown}): the '{r}:' reading of a string is not available \
782                                 in this host"
783                            ));
784                        }
785                        _ => {
786                            return Err(format!(
787                                "graft({shown}): the '{r}:' reading does not read {notation}"
788                            ));
789                        }
790                    },
791                }
792            }
793        };
794        let notation = label;
795        let root = inner.adapter().root();
796        let g = {
797            let mut grafts = self.grafts.borrow_mut();
798            grafts.push(Graft {
799                // filled below with the root's own composite id
800                outer: NodeId(0),
801                inner,
802                notation,
803            });
804            grafts.len() - 1
805        };
806        let id = self.intern(g, root);
807        self.grafts.borrow_mut()[g].outer = id;
808        self.free.borrow_mut().insert(g);
809        Ok(id)
810    }
811
812    /// Decode a composite id.
813    /// The graft's fill for a node inside a grafted document: the
814    /// outer leaf's provenance (the file's path and mtime) with the
815    /// mtime re-labelled as the source rung, and the node's path
816    /// inside the document.
817    fn graft_fill(&self, outer_leaf: NodeId, inner_path: String) -> quarb::Provenance {
818        let mut fill = self.outer.provenance(outer_leaf).as_source_rung();
819        fill.path = Some(inner_path);
820        fill
821    }
822
823    /// The fill for a node of a graft made on demand: no outer leaf
824    /// stands behind it, so only the node's path inside the parsed
825    /// document is known here; the text's own origins ride the
826    /// thread that grafted it.
827    fn free_fill(inner_path: String) -> quarb::Provenance {
828        quarb::Provenance {
829            path: Some(inner_path),
830            ..quarb::Provenance::default()
831        }
832    }
833
834    fn split(&self, node: NodeId) -> Option<(usize, NodeId)> {
835        if node.0 & GRAFT_BIT == 0 {
836            return None;
837        }
838        self.reverse
839            .borrow()
840            .get((node.0 & !GRAFT_BIT) as usize)
841            .copied()
842    }
843
844    fn intern(&self, graft: usize, inner: NodeId) -> NodeId {
845        if let Some(&id) = self.interned.borrow().get(&(graft, inner)) {
846            return id;
847        }
848        let mut rev = self.reverse.borrow_mut();
849        let id = NodeId(GRAFT_BIT | rev.len() as u64);
850        rev.push((graft, inner));
851        self.interned.borrow_mut().insert((graft, inner), id);
852        id
853    }
854
855    /// Whether a literal scope names a childless outer node, one a
856    /// child step would read into as a graft. The root is no leaf;
857    /// a scope that names several nodes, or none, counts as one.
858    fn scope_is_leaf(&self, scope: &[&str]) -> bool {
859        let mut at = self.outer.root();
860        for name in scope {
861            let mut hits = self.outer.children_named(at, name).into_iter();
862            let Some(first) = hits.next() else {
863                return true;
864            };
865            if hits.next().is_some() {
866                return true;
867            }
868            at = first;
869        }
870        at != self.outer.root() && self.outer.children(at).is_empty()
871    }
872
873    /// The graft at an outer leaf, probing (read + parse) on first
874    /// touch. Only childless outer nodes with text content are
875    /// candidates.
876    fn graft_at(&self, node: NodeId) -> Option<usize> {
877        self.graft_probe(node, None)
878    }
879
880    /// Read an outer leaf as `notation`, the query's `<NOTATION>` at
881    /// a step (spec: Grafting): true when the leaf is grafted as that
882    /// notation afterwards, whether by this call or before it.
883    pub fn graft_as(&self, node: NodeId, notation: &str) -> bool {
884        let want = canonical_notation(notation);
885        if let Some(Some(g)) = self.probed.borrow().get(&node).copied() {
886            return self.grafts.borrow()[g].notation == want;
887        }
888        // a leaf probed as nothing may still read under a request
889        self.probed.borrow_mut().remove(&node);
890        match self.graft_probe(node, Some(&want)) {
891            Some(g) => self.grafts.borrow()[g].notation == want,
892            None => false,
893        }
894    }
895
896    fn graft_probe(&self, node: NodeId, requested: Option<&str>) -> Option<usize> {
897        if self.on_demand_only && requested.is_none() {
898            return None;
899        }
900        if let Some(&g) = self.probed.borrow().get(&node) {
901            return g;
902        }
903        let g = (|| {
904            if !self.outer.children(node).is_empty() {
905                return None;
906            }
907            // a document leaf the host reads by node (spec: The
908            // Corpus Reading): its model is the graft
909            if let Some(read) = &self.document_nodes
910                && let Some(model) = read(&self.outer, node)
911            {
912                let mut grafts = self.grafts.borrow_mut();
913                grafts.push(Graft {
914                    outer: node,
915                    inner: Inner::Text(model),
916                    notation: "document".into(),
917                });
918                return Some(grafts.len() - 1);
919            }
920            let name = self.outer.name(node)?;
921            // An archive leaf: opened by its path where the substrate
922            // has one (a folder's file), else from its bytes where it
923            // holds them (a member of an archive: a zip inside a zip).
924            // The grafted archive composes in turn, and hands its
925            // own members' bytes on, so the nesting has no fixed
926            // depth.
927            let nested = || {
928                if let Some(path_of) = self.source_path
929                    && let Some(path) = path_of(&self.outer, node)
930                {
931                    return quarb_archive::ArchiveAdapter::open_with_decoding(
932                        &path,
933                        self.decoding.clone(),
934                    )
935                    .ok();
936                }
937                let bytes = self.source_bytes?(&self.outer, node)?;
938                quarb_archive::ArchiveAdapter::from_bytes_with_decoding(
939                    &bytes,
940                    self.decoding.clone(),
941                )
942                .ok()
943            };
944            if archive_name(&name)
945                && let Some(a) = nested()
946            {
947                let inner = Inner::Archive(Box::new(
948                    ComposeAdapter::new(a)
949                        .with_source_bytes(archive_member_bytes)
950                        .with_source_graft(self.source_graft)
951                        .with_document_graft(self.document_graft)
952                        .with_decoding(self.decoding.clone())
953                        .with_csv_options(self.csv.clone())
954                        .with_default_notation(self.default_notation.clone()),
955                ));
956                let mut grafts = self.grafts.borrow_mut();
957                grafts.push(Graft {
958                    outer: node,
959                    inner,
960                    notation: "archive".into(),
961                });
962                return Some(grafts.len() - 1);
963            }
964            if let Some(read) = &self.document_reader
965                && let Some(path_of) = self.source_path
966                && let Some(path) = path_of(&self.outer, node)
967                && let Some(model) = read(&path)
968            {
969                let mut grafts = self.grafts.borrow_mut();
970                grafts.push(Graft {
971                    outer: node,
972                    inner: Inner::Text(model),
973                    notation: "document".into(),
974                });
975                return Some(grafts.len() - 1);
976            }
977            // A leaf grafts only as declared (spec: Grafting): by
978            // the substrate (a json column), by the mount's
979            // `?format=`, by its name's extension, or by what the
980            // bytes say of themselves (an XML declaration, a
981            // DOCTYPE). A leaf nothing declares is a leaf, unread;
982            // a named leaf whose extension no reader takes (an
983            // image, a binary) likewise. Only a nameless leaf is
984            // worth reading for its own declaration.
985            let declared = requested
986                .map(|r| canonical_notation(r))
987                .or_else(|| {
988                    self.outer
989                        .declared_notation(node)
990                        .map(|n| canonical_notation(&n))
991                })
992                .or_else(|| self.default_notation.clone())
993                .or_else(|| notation_of_name(&name));
994            if declared.is_none() && name.contains('.') {
995                return None;
996            }
997            // Through the path when there is one: the bytes meet
998            // the boundary here, under the mount's rule, and the
999            // record stays with the graft. A leaf whose bytes refuse
1000            // to decode (not UTF-8, nothing declared) stays a leaf.
1001            let mut record = None;
1002            let content = match self
1003                .source_path
1004                .and_then(|path_of| path_of(&self.outer, node))
1005                .and_then(|p| std::fs::read(p).ok())
1006            {
1007                Some(bytes) => {
1008                    let d = self.decoding.decode(&name, &bytes).ok()?;
1009                    record = Some((d.encoding, d.replaced));
1010                    d.text
1011                }
1012                None => match self.outer.default_value(node)? {
1013                    Value::Str(s) => s,
1014                    _ => return None,
1015                },
1016            };
1017            let notation = declared.or_else(|| self_declared(&content).map(str::to_string))?;
1018            let mut inner = parse_as(
1019                &notation,
1020                &content,
1021                self.source_graft,
1022                self.document_graft,
1023                self.csv.clone(),
1024            )?;
1025            if let (Inner::Text(model), Some(f)) = (&mut inner, self.document_url)
1026                && let Some(u) = f(&self.outer, node)
1027            {
1028                model.set_document_url(&u);
1029            }
1030            let mut grafts = self.grafts.borrow_mut();
1031            grafts.push(Graft {
1032                outer: node,
1033                inner,
1034                notation,
1035            });
1036            if let Some(r) = record {
1037                self.decoded.borrow_mut().insert(grafts.len() - 1, r);
1038            }
1039            Some(grafts.len() - 1)
1040        })();
1041        self.probed.borrow_mut().insert(node, g);
1042        g
1043    }
1044
1045    /// Map an inner node up: the inner root becomes the outer
1046    /// leaf.
1047    fn wrap(&self, graft: usize, inner: NodeId) -> NodeId {
1048        let grafts = self.grafts.borrow();
1049        if inner == grafts[graft].inner.adapter().root() {
1050            grafts[graft].outer
1051        } else {
1052            drop(grafts);
1053            self.intern(graft, inner)
1054        }
1055    }
1056}
1057
1058impl<A: AstAdapter> AstAdapter for ComposeAdapter<A> {
1059    fn root(&self) -> NodeId {
1060        self.outer.root()
1061    }
1062
1063    fn graft_text(&self, text: &str, notation: Option<&str>) -> Option<Result<NodeId, String>> {
1064        Some(ComposeAdapter::graft_text(self, text, notation))
1065    }
1066
1067    fn grafts_on_demand(&self) -> bool {
1068        true
1069    }
1070    fn form_of(&self, node: NodeId) -> Option<quarb::Form> {
1071        match self.split(node) {
1072            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().form_of(inner),
1073            None => self.outer.form_of(node),
1074        }
1075    }
1076
1077    fn children(&self, node: NodeId) -> Vec<NodeId> {
1078        match self.split(node) {
1079            Some((g, inner)) => {
1080                let ids: Vec<NodeId> = {
1081                    let grafts = self.grafts.borrow();
1082                    grafts[g].inner.adapter().children(inner)
1083                };
1084                ids.into_iter().map(|c| self.wrap(g, c)).collect()
1085            }
1086            None => {
1087                let outer = self.outer.children(node);
1088                if !outer.is_empty() {
1089                    return outer;
1090                }
1091                match self.graft_at(node) {
1092                    Some(g) => {
1093                        let ids: Vec<NodeId> = {
1094                            let grafts = self.grafts.borrow();
1095                            let a = grafts[g].inner.adapter();
1096                            a.children(a.root())
1097                        };
1098                        ids.into_iter().map(|c| self.wrap(g, c)).collect()
1099                    }
1100                    None => Vec::new(),
1101                }
1102            }
1103        }
1104    }
1105
1106    /// A child by name: the outer source's own lookup first (a
1107    /// database reads `/books/7` by key), and the listing only where
1108    /// the node may hold a grafted document — a leaf with a path or
1109    /// with text. A miss on a node that cannot hold one stays a
1110    /// miss, without listing its children.
1111    fn children_named(&self, node: NodeId, name: &str) -> Vec<NodeId> {
1112        match self.split(node) {
1113            Some((g, inner)) => {
1114                let ids: Vec<NodeId> = {
1115                    let grafts = self.grafts.borrow();
1116                    grafts[g].inner.adapter().children_named(inner, name)
1117                };
1118                ids.into_iter().map(|c| self.wrap(g, c)).collect()
1119            }
1120            None => {
1121                let named = self.outer.children_named(node, name);
1122                if !named.is_empty() {
1123                    return named;
1124                }
1125                // (or an archive leaf the substrate holds the bytes of:
1126                // it has no text, and its members are its children)
1127                let holds_archive = || {
1128                    self.source_bytes.is_some()
1129                        && self.outer.name(node).is_some_and(|n| archive_name(&n))
1130                };
1131                if self.source_path.is_none()
1132                    && !matches!(self.outer.default_value(node), Some(Value::Str(_)))
1133                    && !holds_archive()
1134                {
1135                    return Vec::new();
1136                }
1137                self.children(node)
1138                    .into_iter()
1139                    .filter(|&c| self.answers_to(c, name))
1140                    .collect()
1141            }
1142        }
1143    }
1144
1145    fn name(&self, node: NodeId) -> Option<String> {
1146        match self.split(node) {
1147            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().name(inner),
1148            None => self.outer.name(node),
1149        }
1150    }
1151
1152    fn parent(&self, node: NodeId) -> Option<NodeId> {
1153        match self.split(node) {
1154            Some((g, inner)) => {
1155                let p = self.grafts.borrow()[g].inner.adapter().parent(inner)?;
1156                Some(self.wrap(g, p))
1157            }
1158            None => self.outer.parent(node),
1159        }
1160    }
1161
1162    fn child_host(&self, node: NodeId) -> NodeId {
1163        match self.split(node) {
1164            Some((g, inner)) => {
1165                let h = self.grafts.borrow()[g].inner.adapter().child_host(inner);
1166                self.wrap(g, h)
1167            }
1168            None => self.outer.child_host(node),
1169        }
1170    }
1171
1172    fn properties(&self, node: NodeId) -> Vec<(String, Value)> {
1173        match self.split(node) {
1174            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().properties(inner),
1175            None => self.outer.properties(node),
1176        }
1177    }
1178
1179    /// The walk is open when the outer tree opens to it (a graft is
1180    /// read whole once reached).
1181    fn walks_for_references(&self) -> bool {
1182        self.outer.walks_for_references()
1183    }
1184    /// A declaration answers on its own side of the boundary; across
1185    /// it only a reference property of the source's own can reach.
1186    fn can_refer_to(&self, source: NodeId, target: NodeId) -> Option<bool> {
1187        match (self.split(source), self.split(target)) {
1188            (None, None) => self.outer.can_refer_to(source, target),
1189            (Some((g, s)), Some((h, t))) if g == h => {
1190                self.grafts.borrow()[g].inner.adapter().can_refer_to(s, t)
1191            }
1192            _ => self.ref_property(source).map(|_| true),
1193        }
1194    }
1195    fn reference_properties(&self, source: NodeId, target: NodeId) -> Vec<String> {
1196        match (self.split(source), self.split(target)) {
1197            (None, None) => self.outer.reference_properties(source, target),
1198            (Some((g, s)), Some((h, t))) if g == h => self.grafts.borrow()[g]
1199                .inner
1200                .adapter()
1201                .reference_properties(s, t),
1202            _ => self.ref_property(source).into_iter().collect(),
1203        }
1204    }
1205    /// The outer source's own index over a scope of its own nodes
1206    /// (a database reading `/books/*` by key).
1207    fn index_referrers(
1208        &self,
1209        scope: &str,
1210        property: &str,
1211        label: Option<&str>,
1212        target: NodeId,
1213    ) -> Option<Vec<NodeId>> {
1214        match self.split(target) {
1215            None => self.outer.index_referrers(scope, property, label, target),
1216            Some(_) => None,
1217        }
1218    }
1219    fn tree_identities(&self) -> Vec<(String, NodeId)> {
1220        self.outer.tree_identities()
1221    }
1222    fn reverse_label(&self, target: NodeId) -> Option<String> {
1223        match self.split(target) {
1224            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().reverse_label(inner),
1225            None => self.outer.reverse_label(target),
1226        }
1227    }
1228    fn resolve_needs_label(&self, node: NodeId, property: &str) -> bool {
1229        match self.split(node) {
1230            Some((g, inner)) => self.grafts.borrow()[g]
1231                .inner
1232                .adapter()
1233                .resolve_needs_label(inner, property),
1234            None => self.outer.resolve_needs_label(node, property),
1235        }
1236    }
1237    fn property_names(&self, node: NodeId) -> Vec<String> {
1238        match self.split(node) {
1239            Some((g, inner)) => self.grafts.borrow()[g]
1240                .inner
1241                .adapter()
1242                .property_names(inner),
1243            // The graft root IS the outer leaf: the properties the
1244            // grafted document's root answers are the leaf's (see
1245            // `property`), so they are among its names. (A JSON
1246            // column's cell answered `::total` and listed no
1247            // property: `:props` was empty at the graft and right
1248            // one step in.)
1249            None => {
1250                let mut names = self.outer.property_names(node);
1251                if let Some(g) = self.graft_at(node) {
1252                    let grafts = self.grafts.borrow();
1253                    let a = grafts[g].inner.adapter();
1254                    for name in a.property_names(a.root()) {
1255                        if !names.contains(&name) {
1256                            names.push(name);
1257                        }
1258                    }
1259                }
1260                names
1261            }
1262        }
1263    }
1264    /// The outer source, or any document grafted so far.
1265    fn resolves_references(&self) -> bool {
1266        self.outer.resolves_references()
1267            || self
1268                .grafts
1269                .borrow()
1270                .iter()
1271                .any(|g| g.inner.adapter().resolves_references())
1272    }
1273
1274    /// The outer tree's non-tree nodes, then each graft's (the
1275    /// grafts already read).
1276    fn non_tree_nodes(&self) -> Vec<NodeId> {
1277        let mut out = self.outer.non_tree_nodes();
1278        let grafts = self.grafts.borrow();
1279        for (g, graft) in grafts.iter().enumerate() {
1280            out.extend(
1281                graft
1282                    .inner
1283                    .adapter()
1284                    .non_tree_nodes()
1285                    .into_iter()
1286                    .map(|n| self.wrap(g, n)),
1287            );
1288        }
1289        out
1290    }
1291
1292    /// A written name reaches a node by the owning adapter's rule
1293    /// (its aliases included).
1294    fn answers_to(&self, node: NodeId, name: &str) -> bool {
1295        match self.split(node) {
1296            Some((g, inner)) => self.grafts.borrow()[g]
1297                .inner
1298                .adapter()
1299                .answers_to(inner, name),
1300            None => self.outer.answers_to(node, name),
1301        }
1302    }
1303
1304    /// The graft root IS the outer leaf, so the leaf wears the
1305    /// grafted document's own traits too — a page's declared tags
1306    /// on the file that holds it.
1307    fn traits(&self, node: NodeId) -> Vec<String> {
1308        match self.split(node) {
1309            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().traits(inner),
1310            None => {
1311                let mut out = self.outer.traits(node);
1312                if let Some(g) = self.graft_at(node) {
1313                    let grafts = self.grafts.borrow();
1314                    let a = grafts[g].inner.adapter();
1315                    for t in a.traits(a.root()) {
1316                        if !out.contains(&t) {
1317                            out.push(t);
1318                        }
1319                    }
1320                }
1321                out
1322            }
1323        }
1324    }
1325
1326    fn property(&self, node: NodeId, name: &str) -> Option<Value> {
1327        match self.split(node) {
1328            Some((g, inner)) => self.grafts.borrow()[g]
1329                .inner
1330                .adapter()
1331                .property(inner, name),
1332            // The graft root IS the outer leaf, so a property the
1333            // outer can't answer falls through to the grafted
1334            // document's root — `::key` dual exposure works *at*
1335            // the graft, not only one level in.
1336            None => self.outer.property(node, name).or_else(|| {
1337                let g = self.graft_at(node)?;
1338                let grafts = self.grafts.borrow();
1339                let a = grafts[g].inner.adapter();
1340                a.property(a.root(), name)
1341            }),
1342        }
1343    }
1344
1345    fn default_value(&self, node: NodeId) -> Option<Value> {
1346        match self.split(node) {
1347            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().default_value(inner),
1348            // A leaf that did not graft (plain text, a format this
1349            // crate does not parse) is still a source: read through
1350            // its path under the mount's rule, so `?encoding=` and
1351            // a declaration reach it. The outer adapter's own text
1352            // (strict UTF-8) stands where there is no path.
1353            None => {
1354                if self.decoding.explicit.is_some()
1355                    && self.outer.children(node).is_empty()
1356                    && let Some(path_of) = self.source_path
1357                    && let Some(p) = path_of(&self.outer, node)
1358                    && p.is_file()
1359                    && let Ok(bytes) = std::fs::read(&p)
1360                {
1361                    let name = self.outer.name(node).unwrap_or_default();
1362                    return self
1363                        .decoding
1364                        .decode(&name, &bytes)
1365                        .ok()
1366                        .map(|d| Value::Str(d.text));
1367                }
1368                self.outer.default_value(node)
1369            }
1370        }
1371    }
1372
1373    fn metadata(&self, node: NodeId, key: &str) -> Option<Value> {
1374        match self.split(node) {
1375            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().metadata(inner, key),
1376            // Like properties: what the outer cannot answer, the
1377            // grafted document's root may (`:::level`, a reader's
1378            // own key, on the file that holds the document).
1379            None => self.outer.metadata(node, key).or_else(|| {
1380                let g = self.graft_at(node)?;
1381                if matches!(key, "encoding" | "replaced") {
1382                    // A leaf the host's reader read by path has no
1383                    // record yet: decode its bytes under the mount's
1384                    // rule once, for the record alone.
1385                    if !self.decoded.borrow().contains_key(&g)
1386                        && let Some(path_of) = self.source_path
1387                        && let Some(p) = path_of(&self.outer, node)
1388                        && let Ok(bytes) = std::fs::read(&p)
1389                    {
1390                        let name = self.outer.name(node).unwrap_or_default();
1391                        if let Ok(d) = self.decoding.decode(&name, &bytes) {
1392                            self.decoded
1393                                .borrow_mut()
1394                                .insert(g, (d.encoding, d.replaced));
1395                        }
1396                    }
1397                    if let Some((enc, replaced)) = self.decoded.borrow().get(&g) {
1398                        return Some(match key {
1399                            "encoding" => Value::Str(enc.clone()),
1400                            _ => Value::Int(*replaced as i64),
1401                        });
1402                    }
1403                }
1404                let grafts = self.grafts.borrow();
1405                let a = grafts[g].inner.adapter();
1406                a.metadata(a.root(), key)
1407            }),
1408        }
1409    }
1410
1411    fn metadata_keys(&self, node: NodeId) -> Vec<String> {
1412        match self.split(node) {
1413            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().metadata_keys(inner),
1414            None => {
1415                let mut keys = self.outer.metadata_keys(node);
1416                if self.graft_at(node).is_some() {
1417                    for k in ["encoding", "replaced"] {
1418                        if self.metadata(node, k).is_some() && !keys.iter().any(|x| x == k) {
1419                            keys.push(k.to_string());
1420                        }
1421                    }
1422                }
1423                keys
1424            }
1425        }
1426    }
1427
1428    /// A graft's own aliases are not merged: a node either belongs
1429    /// to the outer document or to a graft, and the alias list is
1430    /// consulted only after the owning adapter's `property` misses.
1431    fn aliased_metadata(&self, node: NodeId) -> &'static [&'static str] {
1432        match self.split(node) {
1433            Some((g, inner)) => self.grafts.borrow()[g]
1434                .inner
1435                .adapter()
1436                .aliased_metadata(inner),
1437            None => self.outer.aliased_metadata(node),
1438        }
1439    }
1440
1441    /// A graft is a provenance layer: the grafted document's own
1442    /// components win, and the outer *leaf* it was parsed from fills
1443    /// the rest (with an fs outer: the file's path and mtime). The
1444    /// jar-style composite locator is deliberately not the source —
1445    /// `?src` names a document, and the intra-document address is
1446    /// dpid's job.
1447    fn provenance(&self, node: NodeId) -> quarb::Provenance {
1448        match self.split(node) {
1449            Some((g, inner)) => {
1450                // Clone what we need out of the borrow before calling
1451                // into `self.outer` (which may re-enter the graft
1452                // tables).
1453                let (inner_prov, outer_leaf, inner_path) = {
1454                    let grafts = self.grafts.borrow();
1455                    let a = grafts[g].inner.adapter();
1456                    (
1457                        a.provenance(inner),
1458                        grafts[g].outer,
1459                        quarb::name_path(a, inner),
1460                    )
1461                };
1462                if self.free.borrow().contains(&g) {
1463                    return inner_prov.or(Self::free_fill(inner_path));
1464                }
1465                inner_prov.or(self.graft_fill(outer_leaf, inner_path))
1466            }
1467            None => self.outer.provenance(node),
1468        }
1469    }
1470    /// The same layering, entry by entry.
1471    fn provenance_list(&self, node: NodeId) -> quarb::ProvenanceList {
1472        match self.split(node) {
1473            Some((g, inner)) => {
1474                let (inner_list, outer_leaf, inner_path) = {
1475                    let grafts = self.grafts.borrow();
1476                    let a = grafts[g].inner.adapter();
1477                    (
1478                        a.provenance_list(inner),
1479                        grafts[g].outer,
1480                        quarb::name_path(a, inner),
1481                    )
1482                };
1483                if self.free.borrow().contains(&g) {
1484                    return inner_list.or(Self::free_fill(inner_path));
1485                }
1486                inner_list.or(self.graft_fill(outer_leaf, inner_path))
1487            }
1488            None => self.outer.provenance_list(node),
1489        }
1490    }
1491
1492    fn resolve(&self, node: NodeId, property: &str, hint: Option<&str>) -> Option<NodeId> {
1493        match self.split(node) {
1494            Some((g, inner)) => {
1495                let t = self.grafts.borrow()[g]
1496                    .inner
1497                    .adapter()
1498                    .resolve(inner, property, hint)?;
1499                Some(self.wrap(g, t))
1500            }
1501            None => self.outer.resolve(node, property, hint),
1502        }
1503    }
1504
1505    /// A trait test reaches the graft — and, on the outer leaf,
1506    /// the graft's root, as `traits` does.
1507    fn has_trait(&self, node: NodeId, name: &str) -> bool {
1508        match self.split(node) {
1509            Some((g, inner)) => self.grafts.borrow()[g]
1510                .inner
1511                .adapter()
1512                .has_trait(inner, name),
1513            None => {
1514                // `<json>` on a step reads the leaf as JSON (spec:
1515                // Grafting): the trait holds when it grafts as such
1516                if is_notation(name) && self.outer.children(node).is_empty() {
1517                    return self.graft_as(node, name) || self.outer.has_trait(node, name);
1518                }
1519                self.outer.has_trait(node, name)
1520                    || self.graft_at(node).is_some_and(|g| {
1521                        let grafts = self.grafts.borrow();
1522                        let a = grafts[g].inner.adapter();
1523                        a.has_trait(a.root(), name)
1524                    })
1525            }
1526        }
1527    }
1528
1529    fn ref_property(&self, node: NodeId) -> Option<String> {
1530        match self.split(node) {
1531            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().ref_property(inner),
1532            None => self.outer.ref_property(node),
1533        }
1534    }
1535
1536    /// A graft's external references (a text-level ref leaving
1537    /// its document) come through; an outer leaf's own do too.
1538    fn external_ref(
1539        &self,
1540        node: NodeId,
1541        property: &str,
1542        hint: Option<&str>,
1543    ) -> Option<quarb::ExternalRef> {
1544        match self.split(node) {
1545            Some((g, inner)) => self.grafts.borrow()[g]
1546                .inner
1547                .adapter()
1548                .external_ref(inner, property, hint),
1549            None => self.outer.external_ref(node, property, hint),
1550        }
1551    }
1552
1553    fn ref_label(&self, node: NodeId, property: &str) -> Option<String> {
1554        match self.split(node) {
1555            Some((g, inner)) => self.grafts.borrow()[g]
1556                .inner
1557                .adapter()
1558                .ref_label(inner, property),
1559            None => self.outer.ref_label(node, property),
1560        }
1561    }
1562
1563    /// A fragment lands inside the document: on an outer leaf
1564    /// that holds a graft, inside that graft.
1565    fn resolve_fragment(&self, node: NodeId, fragment: &str) -> Option<NodeId> {
1566        match self.split(node) {
1567            Some((g, inner)) => {
1568                let t = self.grafts.borrow()[g]
1569                    .inner
1570                    .adapter()
1571                    .resolve_fragment(inner, fragment)?;
1572                Some(self.wrap(g, t))
1573            }
1574            None => match self.graft_at(node) {
1575                Some(g) => {
1576                    let t = {
1577                        let grafts = self.grafts.borrow();
1578                        let a = grafts[g].inner.adapter();
1579                        a.resolve_fragment(a.root(), fragment)?
1580                    };
1581                    Some(self.wrap(g, t))
1582                }
1583                None => self.outer.resolve_fragment(node, fragment),
1584            },
1585        }
1586    }
1587
1588    /// The leaf serving a URL, from the declared document URLs;
1589    /// else whatever the outer answers.
1590    fn document_by_ref(&self, id: &str) -> Option<NodeId> {
1591        if let Some(leaf) = self.leaf_by_url(id) {
1592            // The graft is parsed here so a fragment can land.
1593            let _ = self.graft_at(leaf);
1594            return Some(leaf);
1595        }
1596        self.outer.document_by_ref(id)
1597    }
1598
1599    /// A reverse index answers on one side of the boundary only:
1600    /// inside a graft, the graft's own; on the outer tree, the
1601    /// outer's declared references (a catalog key, a model `ref`),
1602    /// which no graft can hold a referrer for.
1603    fn reverse_resolve(
1604        &self,
1605        node: NodeId,
1606        property: Option<&str>,
1607        hint: Option<&str>,
1608    ) -> Option<Vec<NodeId>> {
1609        match self.split(node) {
1610            Some((g, inner)) => {
1611                let v = self.grafts.borrow()[g]
1612                    .inner
1613                    .adapter()
1614                    .reverse_resolve(inner, property, hint)?;
1615                Some(v.into_iter().map(|t| self.wrap(g, t)).collect())
1616            }
1617            None => self.outer.reverse_resolve(node, property, hint),
1618        }
1619    }
1620
1621    /// Inside a graft the graft's index answers; on the outer tree
1622    /// a name may also live inside grafts, so the walk stays.
1623    fn descendants_named(&self, node: NodeId, name: &str) -> Option<Vec<(NodeId, usize)>> {
1624        let (g, inner) = self.split(node)?;
1625        let v = self.grafts.borrow()[g]
1626            .inner
1627            .adapter()
1628            .descendants_named(inner, name)?;
1629        Some(v.into_iter().map(|(t, d)| (self.wrap(g, t), d)).collect())
1630    }
1631
1632    fn descendants_where(
1633        &self,
1634        node: NodeId,
1635        name: &str,
1636        property: &str,
1637        value: &Value,
1638    ) -> Option<Vec<(NodeId, usize)>> {
1639        let (g, inner) = self.split(node)?;
1640        let v = self.grafts.borrow()[g]
1641            .inner
1642            .adapter()
1643            .descendants_where(inner, name, property, value)?;
1644        Some(v.into_iter().map(|(t, d)| (self.wrap(g, t), d)).collect())
1645    }
1646
1647    fn select(&self, from: NodeId, plan: &quarb::StepPlan<'_>) -> Option<quarb::Selection> {
1648        match self.split(from) {
1649            // Inside a graft: its adapter's own answer, wrapped.
1650            Some((g, inner)) => {
1651                let sel = self.grafts.borrow()[g]
1652                    .inner
1653                    .adapter()
1654                    .select(inner, plan)?;
1655                Some(quarb::Selection {
1656                    nodes: sel
1657                        .nodes
1658                        .into_iter()
1659                        .map(|(t, d)| (self.wrap(g, t), d))
1660                        .collect(),
1661                    applied: sel.applied,
1662                })
1663            }
1664            // Outside: the outer adapter's descendants may cross
1665            // into grafts, which the walk handles; a child step is
1666            // this adapter's own `children_named`.
1667            // A prefix the plan asks for (`@| [..n]` right after the
1668            // step, ruling 2026-11-05) is the outer source's to cut
1669            // where it lists its rows lazily; its nodes are its own.
1670            None => match plan.axis {
1671                quarb::PlanAxis::Child => plan
1672                    .limit
1673                    .and_then(|_| self.outer.select(from, plan))
1674                    .or_else(|| quarb::adapter::select_by_hooks(self, from, plan)),
1675                quarb::PlanAxis::Descendant => {
1676                    plan.limit.and_then(|_| self.outer.select(from, plan))
1677                }
1678            },
1679        }
1680    }
1681
1682    fn index_lookup(&self, scope: &str, property: &str, value: &Value) -> Option<Vec<NodeId>> {
1683        self.outer.index_lookup(scope, property, value)
1684    }
1685
1686    fn select_plan(&self, scope: &[&str], plan: &quarb::StepPlan<'_>) -> Option<Vec<bool>> {
1687        self.outer.select_plan(scope, plan)
1688    }
1689
1690    /// The outer source prices its own tree. Where this layer grafts
1691    /// by kind, a leaf beneath the scope may be a document it has not
1692    /// read, so a step that reaches into leaves (a descendant step
1693    /// anywhere, a child step from a leaf) keeps the outer's lower
1694    /// bound and loses its upper one: a strict budget refuses it as
1695    /// unbounded, a lenient one lets the walk price it. A layer that
1696    /// grafts on demand only reads no leaf the query does not name,
1697    /// so the outer's estimate stands.
1698    fn estimate(&self, scope: &[&str], plan: &quarb::StepPlan<'_>) -> Option<quarb::Estimate> {
1699        let e = self.outer.estimate(scope, plan)?;
1700        if self.on_demand_only {
1701            return Some(e);
1702        }
1703        let reaches_leaves = match plan.axis {
1704            quarb::PlanAxis::Descendant => true,
1705            quarb::PlanAxis::Child => self.scope_is_leaf(scope),
1706        };
1707        if !reaches_leaves {
1708            return Some(e);
1709        }
1710        Some(quarb::Estimate {
1711            nodes: (e.nodes.0, u64::MAX),
1712            confidence: quarb::Confidence::Bound,
1713            ..e
1714        })
1715    }
1716
1717    fn has_node(&self, node: NodeId) -> bool {
1718        match self.split(node) {
1719            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().has_node(inner),
1720            None => self.outer.has_node(node),
1721        }
1722    }
1723
1724    fn unit_scale(&self, expr: &str) -> Option<(f64, String)> {
1725        self.outer.unit_scale(expr)
1726    }
1727
1728    // The hooks that are the outer source's alone, forwarded as they
1729    // are: a document's unit names (a kaiv document's `.faiv`
1730    // imports), its metadata catalogue, the graph it declares and the
1731    // measures it stores, what it withholds. Every source carries
1732    // this layer now (grafting on demand), so a hook this layer does
1733    // not forward is a hook no source answers.
1734    fn unit_names(&self) -> Vec<String> {
1735        self.outer.unit_names()
1736    }
1737
1738    fn metadata_catalogue(&self) -> &'static [&'static str] {
1739        self.outer.metadata_catalogue()
1740    }
1741
1742    fn graph_bound(&self) -> usize {
1743        self.outer.graph_bound()
1744    }
1745
1746    fn graph_declarations(&self) -> Vec<quarb::GraphDeclaration> {
1747        self.outer.graph_declarations()
1748    }
1749
1750    fn graph_measure(
1751        &self,
1752        scope: &str,
1753        hop: &str,
1754        measure: &str,
1755        nodes: &[NodeId],
1756    ) -> Option<Vec<Value>> {
1757        if nodes.iter().any(|&n| self.split(n).is_some()) {
1758            return None;
1759        }
1760        self.outer.graph_measure(scope, hop, measure, nodes)
1761    }
1762
1763    fn store_graph_measure(
1764        &self,
1765        scope: &str,
1766        hop: &str,
1767        measure: &str,
1768        nodes: &[NodeId],
1769        values: &[Value],
1770    ) {
1771        if nodes.iter().all(|&n| self.split(n).is_none()) {
1772            self.outer
1773                .store_graph_measure(scope, hop, measure, nodes, values);
1774        }
1775    }
1776
1777    fn acyclic_link(&self, label: &str) -> Option<String> {
1778        self.outer.acyclic_link(label)
1779    }
1780
1781    fn nodes_withheld(&self) -> bool {
1782        self.outer.nodes_withheld()
1783    }
1784
1785    fn withheld_properties(&self) -> Vec<String> {
1786        self.outer.withheld_properties()
1787    }
1788
1789    fn property_withheld(&self, node: NodeId, name: &str) -> bool {
1790        match self.split(node) {
1791            Some((g, inner)) => self.grafts.borrow()[g]
1792                .inner
1793                .adapter()
1794                .property_withheld(inner, name),
1795            None => self.outer.property_withheld(node, name),
1796        }
1797    }
1798
1799    fn declared_notation(&self, node: NodeId) -> Option<String> {
1800        match self.split(node) {
1801            Some((g, inner)) => self.grafts.borrow()[g]
1802                .inner
1803                .adapter()
1804                .declared_notation(inner),
1805            None => self.outer.declared_notation(node),
1806        }
1807    }
1808
1809    fn link_property_names(&self, source: NodeId, label: &str, target: NodeId) -> Vec<String> {
1810        match (self.split(source), self.split(target)) {
1811            (None, None) => self.outer.link_property_names(source, label, target),
1812            (Some((g, s)), Some((h, t))) if g == h => self.grafts.borrow()[g]
1813                .inner
1814                .adapter()
1815                .link_property_names(s, label, t),
1816            _ => Vec::new(),
1817        }
1818    }
1819
1820    fn edge_weights(
1821        &self,
1822        source: NodeId,
1823        label: &str,
1824        target: NodeId,
1825        row: Option<NodeId>,
1826        forward: bool,
1827    ) -> Vec<Value> {
1828        match (self.split(source), self.split(target)) {
1829            (None, None) => self.outer.edge_weights(source, label, target, row, forward),
1830            (Some((g, s)), Some((h, t))) if g == h => {
1831                let row = row.and_then(|r| match self.split(r) {
1832                    Some((k, inner)) if k == g => Some(inner),
1833                    _ => None,
1834                });
1835                self.grafts.borrow()[g]
1836                    .inner
1837                    .adapter()
1838                    .edge_weights(s, label, t, row, forward)
1839            }
1840            _ => Vec::new(),
1841        }
1842    }
1843
1844    fn prefetch_properties(&self, nodes: &[NodeId], names: &[&str]) {
1845        let outer: Vec<NodeId> = nodes
1846            .iter()
1847            .copied()
1848            .filter(|&n| self.split(n).is_none())
1849            .collect();
1850        if !outer.is_empty() {
1851            self.outer.prefetch_properties(&outer, names);
1852        }
1853    }
1854
1855    fn count(&self, from: NodeId, plan: &quarb::StepPlan<'_>) -> Option<usize> {
1856        match self.split(from) {
1857            Some(_) => None,
1858            None => self.outer.count(from, plan),
1859        }
1860    }
1861
1862    fn row_columns(&self, node: NodeId) -> Option<Vec<String>> {
1863        match self.split(node) {
1864            Some((g, inner)) => self.grafts.borrow()[g].inner.adapter().row_columns(inner),
1865            None => self.outer.row_columns(node),
1866        }
1867    }
1868
1869    /// A grafted document's surface, its container named from the
1870    /// leaf it is grafted on.
1871    fn surface(&self, node: NodeId) -> Option<quarb::Surface> {
1872        match self.split(node) {
1873            Some((g, inner)) => {
1874                let (surface, outer) = {
1875                    let grafts = self.grafts.borrow();
1876                    (grafts[g].inner.adapter().surface(inner)?, grafts[g].outer)
1877                };
1878                Some(surface.under(&quarb::name_path(self, outer)))
1879            }
1880            None => self.outer.surface(node),
1881        }
1882    }
1883
1884    fn intrinsic(&self, node: NodeId) -> NodeId {
1885        match self.split(node) {
1886            Some((g, inner)) => {
1887                let i = self.grafts.borrow()[g].inner.adapter().intrinsic(inner);
1888                self.intern(g, i)
1889            }
1890            None => self.outer.intrinsic(node),
1891        }
1892    }
1893
1894    fn row_text(&self, node: NodeId, f: &mut dyn FnMut(&[&str])) -> bool {
1895        match self.split(node) {
1896            Some(_) => false,
1897            None => self.outer.row_text(node, f),
1898        }
1899    }
1900
1901    /// The outer source's own hint for its nodes; a leaf that may
1902    /// still graft (the layer probes leaves) may hold a document
1903    /// below, so the hint stands open there.
1904    fn may_hold_below(&self, node: NodeId, name: Option<&str>, traits: &[&str]) -> bool {
1905        match self.split(node) {
1906            Some((g, inner)) => self.grafts.borrow()[g]
1907                .inner
1908                .adapter()
1909                .may_hold_below(inner, name, traits),
1910            None => {
1911                self.outer.may_hold_below(node, name, traits)
1912                    || (!self.on_demand_only && self.outer.children(node).is_empty())
1913            }
1914        }
1915    }
1916
1917    fn quantifier_bound(&self) -> usize {
1918        self.outer.quantifier_bound()
1919    }
1920
1921    fn frontier_bound(&self) -> usize {
1922        self.outer.frontier_bound()
1923    }
1924
1925    fn whole_listings(&self) {
1926        self.outer.whole_listings()
1927    }
1928
1929    fn prefetch_links(&self, nodes: &[NodeId], dir: quarb::LinkDir) {
1930        let outer: Vec<NodeId> = nodes
1931            .iter()
1932            .copied()
1933            .filter(|n| self.split(*n).is_none())
1934            .collect();
1935        if !outer.is_empty() {
1936            self.outer.prefetch_links(&outer, dir);
1937        }
1938    }
1939
1940    fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
1941        match self.split(node) {
1942            Some((g, inner)) => {
1943                let ls: Vec<(String, NodeId)> = {
1944                    let grafts = self.grafts.borrow();
1945                    grafts[g].inner.adapter().links(inner)
1946                };
1947                ls.into_iter().map(|(l, n)| (l, self.wrap(g, n))).collect()
1948            }
1949            None => self.outer.links(node),
1950        }
1951    }
1952
1953    fn backlinks(&self, node: NodeId) -> Vec<(String, NodeId)> {
1954        match self.split(node) {
1955            Some((g, inner)) => {
1956                let ls: Vec<(String, NodeId)> = {
1957                    let grafts = self.grafts.borrow();
1958                    grafts[g].inner.adapter().backlinks(inner)
1959                };
1960                ls.into_iter().map(|(l, n)| (l, self.wrap(g, n))).collect()
1961            }
1962            None => self.outer.backlinks(node),
1963        }
1964    }
1965
1966    fn link_consumed(&self, source: NodeId, label: &str) -> bool {
1967        match self.split(source) {
1968            Some((g, inner)) => {
1969                let grafts = self.grafts.borrow();
1970                grafts[g].inner.adapter().link_consumed(inner, label)
1971            }
1972            None => self.outer.link_consumed(source, label),
1973        }
1974    }
1975
1976    // The row-bearing forms and the edges `edges` collects, each
1977    // node and row wrapped: the trait defaults would read `links`
1978    // and lose the row and the grafted level's own edge rule.
1979    fn link_rows(&self, node: NodeId) -> Vec<(String, NodeId, Option<NodeId>)> {
1980        match self.split(node) {
1981            Some((g, inner)) => {
1982                let rows: Vec<(String, NodeId, Option<NodeId>)> = {
1983                    let grafts = self.grafts.borrow();
1984                    grafts[g].inner.adapter().link_rows(inner)
1985                };
1986                rows.into_iter()
1987                    .map(|(l, t, row)| (l, self.wrap(g, t), row.map(|r| self.wrap(g, r))))
1988                    .collect()
1989            }
1990            None => self.outer.link_rows(node),
1991        }
1992    }
1993
1994    fn edge_rows(&self, node: NodeId) -> Vec<(String, NodeId, Option<NodeId>)> {
1995        match self.split(node) {
1996            Some((g, inner)) => {
1997                let rows: Vec<(String, NodeId, Option<NodeId>)> = {
1998                    let grafts = self.grafts.borrow();
1999                    grafts[g].inner.adapter().edge_rows(inner)
2000                };
2001                rows.into_iter()
2002                    .map(|(l, t, row)| (l, self.wrap(g, t), row.map(|r| self.wrap(g, r))))
2003                    .collect()
2004            }
2005            None => self.outer.edge_rows(node),
2006        }
2007    }
2008
2009    fn backlink_rows(&self, node: NodeId) -> Vec<(String, NodeId, Option<NodeId>)> {
2010        match self.split(node) {
2011            Some((g, inner)) => {
2012                let rows: Vec<(String, NodeId, Option<NodeId>)> = {
2013                    let grafts = self.grafts.borrow();
2014                    grafts[g].inner.adapter().backlink_rows(inner)
2015                };
2016                rows.into_iter()
2017                    .map(|(l, s, row)| (l, self.wrap(g, s), row.map(|r| self.wrap(g, r))))
2018                    .collect()
2019            }
2020            None => self.outer.backlink_rows(node),
2021        }
2022    }
2023
2024    // A grafted level that cannot walk its links back says so for
2025    // its own nodes, the outer source for the rest.
2026    fn backlinks_unsupported(&self, node: NodeId, label: Option<&str>) -> bool {
2027        match self.split(node) {
2028            Some((g, inner)) => {
2029                let grafts = self.grafts.borrow();
2030                grafts[g]
2031                    .inner
2032                    .adapter()
2033                    .backlinks_unsupported(inner, label)
2034            }
2035            None => self.outer.backlinks_unsupported(node, label),
2036        }
2037    }
2038
2039    fn link_property(
2040        &self,
2041        source: NodeId,
2042        label: &str,
2043        target: NodeId,
2044        name: &str,
2045    ) -> Option<Value> {
2046        // An edge lives on one side of the graft boundary: both
2047        // endpoints are inner (same graft) or both outer.
2048        match (self.split(source), self.split(target)) {
2049            (Some((g, src)), Some((gt, tgt))) if g == gt => self.grafts.borrow()[g]
2050                .inner
2051                .adapter()
2052                .link_property(src, label, tgt, name),
2053            (None, None) => self.outer.link_property(source, label, target, name),
2054            _ => None,
2055        }
2056    }
2057}