1use quarb::source::SourceDecoding;
34use quarb::{AstAdapter, NodeId, Value};
35use std::cell::RefCell;
36use std::collections::HashMap;
37use std::path::PathBuf;
38
39enum 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
94pub enum SourceGraft {
95 #[default]
96 Syntax,
97 Code,
98}
99
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
106pub enum DocumentGraft {
107 #[default]
108 Dom,
109 Text,
110}
111
112pub 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" => quarb_text_rtf::declared_encoding(bytes),
126 _ => quarb_xml::declared_encoding(bytes).or_else(|| quarb_html::declared_encoding(bytes)),
127 }
128}
129
130pub 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
140pub 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
152pub fn archive_member_bytes(a: &quarb_archive::ArchiveAdapter, node: NodeId) -> Option<Vec<u8>> {
156 a.member_bytes(node)
157}
158
159fn archive_name(name: &str) -> bool {
162 quarb_archive::archive_extension(name.rsplit('.').next().unwrap_or(""))
163}
164
165pub const NOTATIONS: &[&str] = &[
170 "json", "jsonl", "yaml", "toml", "xml", "html", "markdown", "text", "csv", "tsv", "fb2",
171];
172
173pub 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
202pub 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
215pub 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
230pub 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 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
256fn 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 #[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 "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
345fn 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
374fn named_is_text(label: &str) -> bool {
377 label.ends_with(":text")
378}
379
380#[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
403struct Graft {
405 outer: NodeId,
406 inner: Inner,
407 notation: String,
409}
410
411const GRAFT_BIT: u64 = 1 << 55;
420
421pub type DocumentReader = std::rc::Rc<dyn Fn(&std::path::Path) -> Option<quarb_text::TextModel>>;
425
426pub type DocumentNodes<A> = std::rc::Rc<dyn Fn(&A, NodeId) -> Option<quarb_text::TextModel>>;
431
432pub type StringReader =
438 std::rc::Rc<dyn Fn(&str, &str, &str) -> Option<Result<quarb_text::TextModel, String>>>;
439
440pub const READINGS: &[&str] = &["text", "corpus", "lit", "koine", "code", "web"];
443
444pub struct ComposeAdapter<A: AstAdapter> {
445 outer: A,
446 grafts: RefCell<Vec<Graft>>,
447 probed: RefCell<HashMap<NodeId, Option<usize>>>,
450 interned: RefCell<HashMap<(usize, NodeId), NodeId>>,
452 reverse: RefCell<Vec<(usize, NodeId)>>,
453 source_path: Option<fn(&A, NodeId) -> Option<PathBuf>>,
457 source_bytes: Option<fn(&A, NodeId) -> Option<Vec<u8>>>,
461 source_graft: SourceGraft,
463 document_graft: DocumentGraft,
465 document_url: Option<fn(&A, NodeId) -> Option<String>>,
469 urls: RefCell<Option<HashMap<String, NodeId>>>,
471 document_reader: Option<DocumentReader>,
476 decoding: SourceDecoding,
482 decoded: RefCell<HashMap<usize, (String, usize)>>,
485 csv: quarb_csv::CsvOptions,
488 default_notation: Option<String>,
491 document_nodes: Option<DocumentNodes<A>>,
493 free: RefCell<std::collections::HashSet<usize>>,
498 string_reader: Option<StringReader>,
501 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 pub fn on_demand_only(mut self) -> Self {
539 self.on_demand_only = true;
540 self
541 }
542
543 pub fn with_string_reader(mut self, reader: StringReader) -> Self {
546 self.string_reader = Some(reader);
547 self
548 }
549
550 pub fn with_document_nodes(mut self, reader: DocumentNodes<A>) -> Self {
555 self.document_nodes = Some(reader);
556 self
557 }
558
559 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 pub fn with_decoding(mut self, decoding: SourceDecoding) -> Self {
576 self.decoding = decoding;
577 self
578 }
579
580 pub fn with_document_reader(mut self, reader: DocumentReader) -> Self {
584 self.document_reader = Some(reader);
585 self
586 }
587
588 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 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 pub fn with_source_graft(mut self, graft: SourceGraft) -> Self {
624 self.source_graft = graft;
625 self
626 }
627
628 pub fn with_document_graft(mut self, graft: DocumentGraft) -> Self {
631 self.document_graft = graft;
632 self
633 }
634
635 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 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 pub fn outer(&self) -> &A {
657 &self.outer
658 }
659
660 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 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 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(¬ation) {
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 parse_as(
744 ¬ation,
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, ¬ation).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 let host = self
771 .string_reader
772 .as_ref()
773 .and_then(|read| read(r, ¬ation, 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(¬ation, 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 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 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 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 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 fn graft_at(&self, node: NodeId) -> Option<usize> {
877 self.graft_probe(node, None)
878 }
879
880 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 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 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 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 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 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 ¬ation,
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 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 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 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 fn walks_for_references(&self) -> bool {
1182 self.outer.walks_for_references()
1183 }
1184 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 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 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 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 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 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 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 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 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 None => self.outer.metadata(node, key).or_else(|| {
1380 let g = self.graft_at(node)?;
1381 if matches!(key, "encoding" | "replaced") {
1382 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 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 fn provenance(&self, node: NodeId) -> quarb::Provenance {
1448 match self.split(node) {
1449 Some((g, inner)) => {
1450 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 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 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 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 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 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 fn document_by_ref(&self, id: &str) -> Option<NodeId> {
1591 if let Some(leaf) = self.leaf_by_url(id) {
1592 let _ = self.graft_at(leaf);
1594 return Some(leaf);
1595 }
1596 self.outer.document_by_ref(id)
1597 }
1598
1599 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 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 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 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 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 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 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 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 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 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 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}