Skip to main content

quarb/graph/
adapter.rs

1//! The adapter surface: how a data source plugs into the engine.
2//!
3//! The live methods — those the engine currently drives — are
4//! the navigation set ([`root`](AstAdapter::root),
5//! [`children`](AstAdapter::children), [`name`](AstAdapter::name),
6//! [`parent`](AstAdapter::parent)) plus the projection set
7//! ([`traits`](AstAdapter::traits), [`property`](AstAdapter::property),
8//! [`default_value`](AstAdapter::default_value),
9//! [`metadata`](AstAdapter::metadata)). The projection methods have
10//! defaults, so an adapter can implement only what its domain
11//! supports. The reference cluster (`->`, `<-`, `-->`, `<--`,
12//! `=>`), the search fast paths and provenance are documented on
13//! the trait, group by group. See `doc/impl.tex`.
14
15use crate::value::Value;
16
17/// The name of the item at zero-based `index` of a list: its
18/// position counted from one, as every position in Quarb is (ruling
19/// 2026-11-14: `/shelves/1` is the first shelf, and `:name` agrees
20/// with `:index`). Every adapter that names the items of a list by
21/// their position names them through this; a name the source itself
22/// writes (an object's key, a kaiv namepath's segment) is not one.
23pub fn item_name(index: usize) -> String {
24    (index + 1).to_string()
25}
26
27/// The zero-based index a list item's name stands for, when the name
28/// is a position as [`item_name`] writes it (`"1"` the first; `"0"`,
29/// `"01"` and `"+1"` name nothing).
30pub fn item_index(name: &str) -> Option<usize> {
31    let n: usize = name.parse().ok()?;
32    (n > 0 && n.to_string() == name).then(|| n - 1)
33}
34
35/// An opaque handle to a node in an arbor.
36///
37/// The engine treats a `NodeId` as an opaque token: it is minted and
38/// interpreted solely by the adapter that produced it. The `u64`
39/// payload is an adapter-private index or key.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
41pub struct NodeId(pub u64);
42
43/// Per-node data provenance: the three optional components behind
44/// the `:source` / `:instant` / `:dpid` core-metadata keys and
45/// their composite `:provenance` (`?src@ts#dpid`, kaiv's
46/// spelling). A component is present only where the source genuinely
47/// records it; wrapper adapters layer them ([`or`](Self::or), inner
48/// wins per component).
49#[derive(Debug, Clone, Default, PartialEq)]
50pub struct Provenance {
51    /// Where the datum came from: the document, file, store or
52    /// page — the innermost source that holds the node (a grafted
53    /// node's source is the file the graft opened, not the
54    /// directory above it).
55    pub source: Option<String>,
56    /// The node's path within its source — its name-path from the
57    /// source's root — so a source and a path name the node
58    /// without the engine's id. Filled by the layer that knows
59    /// where the source begins (a mount, a graft), else by the
60    /// engine from the arbor root.
61    pub path: Option<String>,
62    /// When the datum was observed — `(secs, nanos, offset_min)`,
63    /// the shape `Value::Instant` carries — by the rung
64    /// [`instant_from`](Self::instant_from) names.
65    pub instant: Option<(i64, u32, Option<i16>)>,
66    /// Which rung answered the instant: the datum's own
67    /// timestamp, its source's modification time, or the moment of
68    /// reading. `None` with no instant.
69    pub instant_from: Option<InstantFrom>,
70    /// The source-assigned data-point identifier (kaiv `#dpid`).
71    pub dpid: Option<String>,
72}
73
74/// The rung an instant came from — three facts that share one
75/// field: a row's own timestamp, a file's mtime, the clock at the
76/// read.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum InstantFrom {
79    /// The datum's own timestamp (a kaiv `@ts`, a commit date, a
80    /// row's `modified`).
81    Node,
82    /// The source's modification time (a file's mtime).
83    Source,
84    /// The moment the query read it: the invocation instant.
85    Access,
86}
87
88impl InstantFrom {
89    pub fn name(self) -> &'static str {
90        match self {
91            InstantFrom::Node => "node",
92            InstantFrom::Source => "source",
93            InstantFrom::Access => "access",
94        }
95    }
96}
97
98impl Provenance {
99    /// Component-wise layering: `self` (inner, more specific) wins;
100    /// missing components fill from `outer`. The instant and its
101    /// rung travel together.
102    pub fn or(self, outer: Provenance) -> Provenance {
103        let (instant, instant_from) = if self.instant.is_some() {
104            (self.instant, self.instant_from)
105        } else {
106            (outer.instant, outer.instant_from)
107        };
108        Provenance {
109            source: self.source.or(outer.source),
110            path: self.path.or(outer.path),
111            instant,
112            instant_from,
113            dpid: self.dpid.or(outer.dpid),
114        }
115    }
116
117    /// Nothing recorded — the path does not count, it is derivable.
118    pub fn is_empty(&self) -> bool {
119        self.source.is_none() && self.instant.is_none() && self.dpid.is_none()
120    }
121
122    /// The instant re-labelled as the source's — what a graft does
123    /// to the file's own mtime when it fills a node inside the file.
124    pub fn as_source_rung(mut self) -> Provenance {
125        if self.instant.is_some() {
126            self.instant_from = Some(InstantFrom::Source);
127        }
128        self
129    }
130
131    /// The canonical text of a list: `?a@ts#x;b#y;+N` — one `?`,
132    /// the entries separated by `;` (kaiv's list separator), each
133    /// in its own optionality grammar, the elision marker `+N` last
134    /// when `elided > 0`. `None` when no entry has a component.
135    pub fn canonical_list(entries: &[Provenance], elided: u32) -> Option<String> {
136        // Entries that write alike are one in the text (the path is
137        // not part of it).
138        let mut parts: Vec<String> = Vec::new();
139        for c in entries.iter().filter_map(|e| e.canonical()) {
140            let c = c.trim_start_matches('?').to_string();
141            if !parts.contains(&c) {
142                parts.push(c);
143            }
144        }
145        if parts.is_empty() {
146            return None;
147        }
148        let mut out = format!("?{}", parts.join(";"));
149        if elided > 0 {
150            out.push_str(&format!(";+{elided}"));
151        }
152        Some(out)
153    }
154
155    /// The composite canonical text `?src@ts#dpid` — kaiv's
156    /// optionality grammar (`?src`, `?src@ts`, `?@ts#dpid`, …), the
157    /// instant in Quarb's dashed-extended display form. `None` when
158    /// fully empty.
159    pub fn canonical(&self) -> Option<String> {
160        if self.is_empty() {
161            return None;
162        }
163        let mut out = String::from("?");
164        if let Some(src) = &self.source {
165            out.push_str(src);
166        }
167        if let Some((secs, _, offset)) = self.instant {
168            // kaiv's instant has no sub-second field: whole seconds,
169            // whatever the rung recorded.
170            out.push('@');
171            out.push_str(&crate::temporal::format_instant(secs, 0, offset));
172        }
173        if let Some(dpid) = &self.dpid {
174            out.push('#');
175            out.push_str(dpid);
176        }
177        Some(out)
178    }
179}
180
181/// A node's provenance as a list: several entries where the datum
182/// was recorded from several sources (a kaiv leaf's `?a;b`), and how
183/// many further sources the record elides (its `;+N`). The singular
184/// [`AstAdapter::provenance`] is the list's anchoring first entry.
185#[derive(Debug, Clone, Default, PartialEq)]
186pub struct ProvenanceList {
187    pub entries: Vec<Provenance>,
188    pub elided: u32,
189}
190
191impl ProvenanceList {
192    /// The one-entry list — empty when the entry is.
193    pub fn single(p: Provenance) -> ProvenanceList {
194        ProvenanceList {
195            entries: if p.is_empty() { Vec::new() } else { vec![p] },
196            elided: 0,
197        }
198    }
199
200    /// The anchoring entry (the first), empty when there is none.
201    pub fn first(&self) -> Provenance {
202        self.entries.first().cloned().unwrap_or_default()
203    }
204
205    /// The latest instant any entry carries: a datum with several
206    /// sources is as fresh as its newest.
207    pub fn instant_max(&self) -> Option<(i64, u32, Option<i16>)> {
208        self.entries
209            .iter()
210            .filter_map(|p| p.instant)
211            .max_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)))
212    }
213
214    /// The canonical list text, `?a@ts#x;b#y;+N`.
215    pub fn canonical(&self) -> Option<String> {
216        Provenance::canonical_list(&self.entries, self.elided)
217    }
218
219    /// Component-wise layering of every entry over `outer` (see
220    /// [`Provenance::or`]); an empty list takes `outer` as its one
221    /// entry.
222    pub fn or(self, outer: Provenance) -> ProvenanceList {
223        if self.entries.is_empty() {
224            return ProvenanceList {
225                entries: ProvenanceList::single(outer).entries,
226                elided: self.elided,
227            };
228        }
229        ProvenanceList {
230            entries: self
231                .entries
232                .into_iter()
233                .map(|p| p.or(outer.clone()))
234                .collect(),
235            elided: self.elided,
236        }
237    }
238}
239
240/// The direction of a crosslink walk, for the batching hint
241/// [`AstAdapter::prefetch_links`].
242#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
243pub enum LinkDir {
244    /// `->`: the links a node carries.
245    Out,
246    /// `<-`: the links that reach a node.
247    In,
248}
249
250/// What a step names of the crosslinks it follows, for an adapter
251/// that reads its links when asked: a link step's one label
252/// (`<-manager`), or the property a resolution reads
253/// (`::order_id-->`, `<--(::order_id)`).
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
255pub enum LinkBy<'a> {
256    Label(&'a str),
257    Property(&'a str),
258}
259
260/// A reference to a document outside the arbor, as an adapter read
261/// it from its own reference syntax: which document, and where in
262/// it. The engine treats both as opaque.
263#[derive(Debug, Clone, PartialEq, Eq)]
264pub struct ExternalRef {
265    /// The document's identity (a URL, a path, a key — whatever
266    /// the mounts are registered under).
267    pub document: String,
268    /// The location within that document, for the adapter that
269    /// owns it to resolve; `None` for the document itself.
270    pub within: Option<String>,
271}
272
273impl ExternalRef {
274    /// Read a URI reference: everything before the first `#` is the
275    /// document, a non-empty fragment after it the location. A
276    /// convenience for adapters whose references are URIs (html,
277    /// the text level, a JSON `$ref`); an adapter with another
278    /// syntax builds the two parts its own way.
279    pub fn uri(reference: &str) -> Self {
280        match reference.split_once('#') {
281            Some((document, fragment)) => ExternalRef {
282                document: document.to_string(),
283                within: (!fragment.is_empty()).then(|| fragment.to_string()),
284            },
285            None => ExternalRef {
286                document: reference.to_string(),
287                within: None,
288            },
289        }
290    }
291
292    /// The reference as one URI again.
293    pub fn to_uri(&self) -> String {
294        match &self.within {
295            Some(w) => format!("{}#{w}", self.document),
296            None => self.document.clone(),
297        }
298    }
299}
300
301/// What one navigation step asks of an adapter, lowered for
302/// [`AstAdapter::select`]: the axis, the name matcher, the
303/// predicate conjuncts the engine can express as plain comparisons,
304/// and — when the command after the step consumes them — a limit and
305/// an order. An adapter answers from an index what it can and names
306/// what it applied; the engine tests the rest.
307#[derive(Debug, Clone)]
308pub struct StepPlan<'a> {
309    /// The axis: a child step or a descendant search.
310    pub axis: PlanAxis,
311    /// The name the step matches, when it is one literal name.
312    pub name: Option<&'a str>,
313    /// The leading predicates lowered to comparisons, in order.
314    pub conjuncts: Vec<Conjunct<'a>>,
315    /// The step's `<trait>` filters, each one literal trait name
316    /// (a clause with alternatives or a negation is not lowered).
317    pub traits: Vec<&'a str>,
318    /// How many results the command after the step keeps, when it
319    /// keeps a prefix (`[..n]`, `@| first(n)`).
320    pub limit: Option<usize>,
321    /// Where an estimator may stop counting: past this many nodes
322    /// or bytes the answer already exceeds the run's budget, so a
323    /// listing, a header walk or an arena count stops there and
324    /// reports `(counted, u64::MAX)`. Unbounded when no budget.
325    pub cap: Cap,
326    /// The property the command after the step orders by, and whether
327    /// ascending.
328    pub order: Option<(&'a str, bool)>,
329}
330
331/// Where counting may stop: the most nodes and bytes a budget
332/// allows, so an estimator short-circuits at the first entry past
333/// either ([`StepPlan::cap`], [`Catalog`] producers).
334#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
335pub struct Cap {
336    pub nodes: Option<u64>,
337    pub bytes: Option<u64>,
338}
339
340impl Cap {
341    /// No cap: count everything (within the walk's own budget).
342    pub const NONE: Cap = Cap {
343        nodes: None,
344        bytes: None,
345    };
346
347    /// Whether `nodes` counted or `bytes` summed so far already
348    /// pass the cap: the walk may stop.
349    pub fn past(&self, nodes: u64, bytes: u64) -> bool {
350        self.nodes.is_some_and(|max| nodes > max) || self.bytes.is_some_and(|max| bytes > max)
351    }
352}
353
354/// The axis of a [`StepPlan`].
355#[derive(Debug, Clone, Copy, PartialEq, Eq)]
356pub enum PlanAxis {
357    /// `/name`: the children.
358    Child,
359    /// `//name`: the descendants, each with its depth.
360    Descendant,
361}
362
363/// One lowered predicate of a [`StepPlan`].
364#[derive(Debug, Clone)]
365pub enum Conjunct<'a> {
366    /// `[::prop = value]` under the engine's standard equality, with
367    /// a text value: what an index or a keyed read answers.
368    Equals(&'a str, &'a Value),
369    /// `[::prop OP literal]`: a comparison on one property, lowered
370    /// for pricing (a listing's sizes, a store's statistics). An
371    /// adapter never applies it in [`AstAdapter::select`]; the
372    /// engine runs it. `Cmp::Eq` here is an equality on a
373    /// non-text literal.
374    Compare(&'a str, Cmp, &'a Value),
375}
376
377/// A comparison a [`Conjunct::Compare`] lowers.
378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
379pub enum Cmp {
380    Eq,
381    Ne,
382    Lt,
383    Le,
384    Gt,
385    Ge,
386    /// `*=`: the property's text contains the literal.
387    Contains,
388}
389
390impl Cmp {
391    /// The operator as written.
392    pub fn text(self) -> &'static str {
393        match self {
394            Cmp::Eq => "=",
395            Cmp::Ne => "!=",
396            Cmp::Lt => "<",
397            Cmp::Le => "<=",
398            Cmp::Gt => ">",
399            Cmp::Ge => ">=",
400            Cmp::Contains => "*=",
401        }
402    }
403
404    /// Whether `value` stands to `literal` as the operator says,
405    /// under the engine's value ordering.
406    pub fn holds(self, value: &Value, literal: &Value) -> bool {
407        use std::cmp::Ordering::*;
408        match self {
409            Cmp::Contains => match (value, literal) {
410                (Value::Str(a), Value::Str(b)) => a.contains(b.as_str()),
411                _ => false,
412            },
413            _ => {
414                // the comparison the predicate makes, so a listing
415                // prices what the engine would answer: a bare literal
416                // beside a size reads in the size's written unit
417                use crate::syntax::ast::CmpOp;
418                let op = match self {
419                    Cmp::Eq => CmpOp::Eq,
420                    Cmp::Ne => CmpOp::Ne,
421                    Cmp::Lt => CmpOp::Lt,
422                    Cmp::Le => CmpOp::Le,
423                    Cmp::Gt => CmpOp::Gt,
424                    Cmp::Ge => CmpOp::Ge,
425                    Cmp::Contains => unreachable!(),
426                };
427                let _ = (Equal, Less, Greater);
428                crate::stdlib::compare::compare(
429                    value,
430                    op,
431                    literal,
432                    &crate::value::quantity::scale_expr,
433                )
434            }
435        }
436    }
437}
438
439/// What an adapter answers to a [`StepPlan`]: the nodes (each with
440/// its depth from the step's base; children are depth 1) in
441/// document order, and which conjuncts the adapter already applied
442/// (the engine runs the rest).
443#[derive(Debug, Clone, Default)]
444pub struct Selection {
445    pub nodes: Vec<(NodeId, usize)>,
446    pub applied: Vec<bool>,
447}
448
449/// What reaching one step's nodes would cost, as an adapter can
450/// say before running it ([`AstAdapter::estimate`]): intervals, a
451/// request count, a latency class and how sure the adapter is. A
452/// host composes these along a query ([`crate::graph::plan::Plan`]) and
453/// refuses before running when a budget is exceeded.
454#[derive(Debug, Clone, PartialEq)]
455pub struct Estimate {
456    /// The nodes the step yields, from the least to the most.
457    pub nodes: (u64, u64),
458    /// The bytes read to yield them, when the adapter can say (a
459    /// warehouse's dry run, a file's size).
460    pub bytes: Option<(u64, u64)>,
461    /// Round trips to a remote, when any.
462    pub requests: Option<u32>,
463    pub latency: Latency,
464    pub confidence: Confidence,
465}
466
467/// Where a step's cost is paid.
468#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
469pub enum Latency {
470    /// The nodes are in memory.
471    Memory,
472    /// A local file or store.
473    Local,
474    /// A network round trip.
475    Remote,
476}
477
478/// How much an [`Estimate`] is worth.
479#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
480pub enum Confidence {
481    /// A guess from statistics or defaults.
482    Guess,
483    /// An upper bound (a clustered table's dry run, a partition's
484    /// size): the actual may come in lower.
485    Bound,
486    /// Exact: the catalog or the store knows.
487    Exact,
488}
489
490/// The surface a source declares for a container
491/// ([`AstAdapter::surface`]): what its members have, all of it. Each
492/// side is declared or open on its own: a CSV declares its columns
493/// and not what a model will link.
494#[derive(Debug, Clone, Default, PartialEq)]
495pub struct Surface {
496    /// The members, as a message names them from the source's root:
497    /// a table by its path (`/employees`), a CSV's rows by theirs
498    /// (`/row`).
499    pub container: String,
500    /// The names of the properties a member has (a table's columns),
501    /// where the list is whole; `None` where it is open.
502    pub properties: Option<Vec<String>>,
503    /// The labels of the edges that leave or reach a member (the
504    /// table's declared keys and those that point at it), where the
505    /// list is whole; `None` where it is open.
506    pub labels: Option<Vec<String>>,
507}
508
509impl Surface {
510    /// The surface as a composite hands it on: the container named
511    /// from the composite's root, the source's own root standing at
512    /// `at` there (`/db` before `/employees`).
513    pub fn under(mut self, at: &str) -> Surface {
514        let at = at.trim_end_matches('/');
515        if !at.is_empty() {
516            self.container = if self.container == "/" {
517                at.to_string()
518            } else {
519                format!("{at}{}", self.container)
520            };
521        }
522        self
523    }
524}
525
526/// What a source knows about itself before it is read: how many
527/// entries it holds (files under a directory, members of an
528/// archive, rows of a table, documents on a shelf) and how many
529/// bytes they come to — from a listing, a central directory, a
530/// `stat`, a store's catalog, never from the contents. A latent
531/// mount answers the plan from it; an [`Unopened`] source is only
532/// it; an opened arena answers from its nodes instead.
533#[derive(Debug, Clone, PartialEq)]
534pub struct Catalog {
535    /// The entries, from the least to the most. A listing that
536    /// stopped early reports `(counted, u64::MAX)`: unbounded.
537    pub entries: (u64, u64),
538    /// Their bytes, when the listing says.
539    pub bytes: Option<(u64, u64)>,
540    pub latency: Latency,
541    pub confidence: Confidence,
542    /// Which of the asked conjuncts the listing applied before
543    /// counting (empty: none; a catalog that applies filters sets
544    /// one flag per conjunct asked).
545    pub applied: Vec<bool>,
546    /// Whether the asked trait filters were all applied.
547    pub traits_applied: bool,
548}
549
550impl Catalog {
551    /// A catalog that applied nothing.
552    pub fn plain(
553        entries: (u64, u64),
554        bytes: Option<(u64, u64)>,
555        latency: Latency,
556        confidence: Confidence,
557    ) -> Catalog {
558        Catalog {
559            entries,
560            bytes,
561            latency,
562            confidence,
563            applied: Vec::new(),
564            traits_applied: false,
565        }
566    }
567}
568
569/// What a catalog is asked for: the literal path under the source,
570/// where counting may stop, and the step's filters a listing may
571/// apply before counting (it says which in [`Catalog::applied`]).
572pub struct Ask<'a> {
573    pub scope: &'a [&'a str],
574    pub cap: Cap,
575    pub conjuncts: &'a [Conjunct<'a>],
576    pub traits: &'a [&'a str],
577}
578
579impl<'a> Ask<'a> {
580    /// A bare ask: the path and the cap, no filters.
581    pub fn at(scope: &'a [&'a str], cap: Cap) -> Ask<'a> {
582        Ask {
583            scope,
584            cap,
585            conjuncts: &[],
586            traits: &[],
587        }
588    }
589}
590
591/// A source known only by its catalog: a root with nothing under
592/// it, answering the plan's estimate for a step from the root out
593/// of the catalog. A front end plans and budgets a query against
594/// it before paying to open the source — a directory of a hundred
595/// thousand files, a tarball of books — and opens only within
596/// budget.
597pub struct Unopened(pub CatalogLookup);
598
599/// A catalog by literal path from a source's root: `&[]` is the
600/// whole source, `&["shelf", "emma.txt"]` one entry under it (a
601/// folder's own listing, one member's header), `None` where the
602/// path names nothing the catalog can see. The cap says where
603/// counting may stop.
604pub type CatalogLookup = Box<dyn Fn(&Ask<'_>) -> Option<Catalog>>;
605
606impl Unopened {
607    /// A source with one catalog, for its root alone.
608    pub fn fixed(c: Catalog) -> Unopened {
609        Unopened(Box::new(move |ask| ask.scope.is_empty().then(|| c.clone())))
610    }
611}
612
613/// The bare root (spec: the expression head): the source a
614/// calculator query runs against — one node, no name, no children,
615/// no properties. `qua '= expr'` without an input and `qc` run on
616/// it, so the two agree by construction.
617pub struct Bare;
618
619impl AstAdapter for Bare {
620    fn root(&self) -> NodeId {
621        NodeId(0)
622    }
623    fn children(&self, _: NodeId) -> Vec<NodeId> {
624        Vec::new()
625    }
626    fn name(&self, _: NodeId) -> Option<String> {
627        None
628    }
629}
630
631impl AstAdapter for Unopened {
632    fn root(&self) -> NodeId {
633        NodeId(0)
634    }
635    fn children(&self, _: NodeId) -> Vec<NodeId> {
636        Vec::new()
637    }
638    fn name(&self, _: NodeId) -> Option<String> {
639        None
640    }
641    fn estimate(&self, scope: &[&str], plan: &StepPlan<'_>) -> Option<Estimate> {
642        Estimate::at_catalog(&*self.0, scope, plan)
643    }
644}
645
646impl Estimate {
647    /// The estimate a catalog gives a step from the source's root.
648    /// The entries are files or members, the step yields nodes,
649    /// and the two meet only as bounds: a child step reaches at most
650    /// the entries (`/*`, or a named one, a subset), an unfiltered
651    /// descendant step reaches at least every entry (`//*`: each is
652    /// a node, with what the reading finds under it), anything else
653    /// is open. The bytes are the source's: what opening it reads.
654    pub fn from_catalog(c: &Catalog, plan: &StepPlan<'_>) -> Estimate {
655        // Filters the listing applied make the count a bound on the
656        // matches: nothing under an entry answers a listing's
657        // property, so a filtered descendant step is bounded too.
658        let filtered = !plan.conjuncts.is_empty() || !plan.traits.is_empty();
659        let applied = filtered
660            && c.applied.len() == plan.conjuncts.len()
661            && c.applied.iter().all(|&b| b)
662            && (plan.traits.is_empty() || c.traits_applied);
663        let rows = match (plan.axis, plan.name, filtered) {
664            (PlanAxis::Child, _, _) => (0, c.entries.1),
665            (PlanAxis::Descendant, None, false) => (c.entries.0, u64::MAX),
666            (PlanAxis::Descendant, None, true) if applied => (0, c.entries.1),
667            _ => (0, u64::MAX),
668        };
669        Estimate {
670            nodes: rows,
671            bytes: c.bytes,
672            requests: Some(0),
673            latency: c.latency,
674            confidence: c.confidence.min(Confidence::Bound),
675        }
676    }
677
678    /// The estimate a catalogued source gives a step at a literal
679    /// `scope`, narrowing to the path the plan records: a bare step
680    /// by name is one entry when the catalog finds it (and costs
681    /// nothing; the step that reads under it is priced by that
682    /// entry's own catalog) and may read the whole when it does not
683    /// (a node inside a document); a reading step at a path the
684    /// catalog resolves is priced by it, and one the catalog cannot
685    /// place is a bounded unknown under the source. `None` when the
686    /// source itself has no catalog.
687    pub fn at_catalog(
688        lookup: &dyn Fn(&Ask<'_>) -> Option<Catalog>,
689        scope: &[&str],
690        plan: &StepPlan<'_>,
691    ) -> Option<Estimate> {
692        let whole = |scope: &[&str]| lookup(&Ask::at(scope, plan.cap));
693        let bare =
694            plan.conjuncts.is_empty() && plan.traits.is_empty() && plan.axis == PlanAxis::Child;
695        if bare && let Some(name) = plan.name {
696            let mut sub: Vec<&str> = scope.to_vec();
697            sub.push(name);
698            return Some(match whole(&sub) {
699                Some(c) => Estimate {
700                    nodes: (1, 1),
701                    bytes: None,
702                    requests: Some(0),
703                    latency: c.latency,
704                    confidence: Confidence::Exact,
705                },
706                // Not an entry the catalog sees (a node inside a
707                // document): reaching it from the root may read the
708                // whole; deeper, the whole was charged already.
709                None => {
710                    let whole = whole(&[])?;
711                    if scope.is_empty() {
712                        Estimate::from_catalog(&whole, plan)
713                    } else {
714                        Estimate::beneath_catalog(&whole)
715                    }
716                }
717            });
718        }
719        // A reading step asks with its filters: a listing that can
720        // apply them counts the matches alone.
721        let ask = Ask {
722            scope,
723            cap: plan.cap,
724            conjuncts: &plan.conjuncts,
725            traits: &plan.traits,
726        };
727        Some(match lookup(&ask) {
728            Some(c) => Estimate::from_catalog(&c, plan),
729            None => Estimate::beneath_catalog(&whole(&[])?),
730        })
731    }
732
733    /// The estimate a catalog gives a step deeper than the root:
734    /// nothing is known of the nodes, and the bytes were counted at
735    /// the root (`None` here, so the branch keeps them).
736    pub fn beneath_catalog(c: &Catalog) -> Estimate {
737        Estimate {
738            nodes: (0, u64::MAX),
739            bytes: None,
740            requests: Some(0),
741            latency: c.latency,
742            confidence: Confidence::Bound,
743        }
744    }
745
746    /// `self` followed by `next` along one branch: the nodes are
747    /// the next step's, the bytes and requests add, the latency is
748    /// the slower, the confidence the weaker.
749    pub fn then(&self, next: &Estimate) -> Estimate {
750        Estimate {
751            nodes: next.nodes,
752            bytes: match (self.bytes, next.bytes) {
753                (Some(a), Some(b)) => Some((a.0.saturating_add(b.0), a.1.saturating_add(b.1))),
754                (a, None) => a,
755                (None, b) => b,
756            },
757            requests: match (self.requests, next.requests) {
758                (Some(a), Some(b)) => Some(a + b),
759                (a, None) => a,
760                (None, b) => b,
761            },
762            latency: self.latency.max(next.latency),
763            confidence: self.confidence.min(next.confidence),
764        }
765    }
766
767    /// `self` beside `other` (two branches of one query): nodes,
768    /// bytes and requests add.
769    pub fn beside(&self, other: &Estimate) -> Estimate {
770        Estimate {
771            nodes: (
772                self.nodes.0.saturating_add(other.nodes.0),
773                self.nodes.1.saturating_add(other.nodes.1),
774            ),
775            ..self.then(other)
776        }
777    }
778}
779
780/// Nodes an arena walk may touch while estimating before it stops
781/// counting: past this many the count is a lower bound.
782pub const ARENA_ESTIMATE_BUDGET: u64 = 2_000_000;
783
784/// An estimate for an adapter whose arbor is in memory (a parsed
785/// document, a walked directory, an archive's member table, a
786/// shelf of documents): the plan's base found by the literal
787/// `scope` from the root (one hit per name, else unknown), then the
788/// step's nodes counted — the children answering to the name, or
789/// the descendants — with `bytes_of` summing what the adapter knows
790/// per node. Exact; a bound under a conjunct or past the walk's
791/// budget. Not the trait's default: for a lazy or remote adapter a
792/// walk is a read.
793pub fn arena_estimate<A: AstAdapter + ?Sized>(
794    adapter: &A,
795    scope: &[&str],
796    plan: &StepPlan<'_>,
797    latency: Latency,
798    bytes_of: Option<&dyn Fn(NodeId) -> Option<u64>>,
799) -> Option<Estimate> {
800    let mut at = adapter.root();
801    for name in scope {
802        let mut hits = adapter.children_named(at, name).into_iter();
803        at = hits.next()?;
804        if hits.next().is_some() {
805            return None;
806        }
807    }
808    let matches = |c: NodeId| plan.name.is_none_or(|n| adapter.answers_to(c, n));
809    let mut n: u64 = 0;
810    let mut bytes: u64 = 0;
811    let mut cut = false;
812    // Counts one node; `true` once the cap is passed: stop.
813    let mut count = |c: NodeId| {
814        if matches(c) {
815            n += 1;
816            if let Some(f) = bytes_of {
817                bytes += f(c).unwrap_or(0);
818            }
819        }
820        plan.cap.past(n, bytes)
821    };
822    match plan.axis {
823        PlanAxis::Child => {
824            for c in adapter.children(at) {
825                if count(c) {
826                    cut = true;
827                    break;
828                }
829            }
830        }
831        PlanAxis::Descendant => {
832            let mut visited: u64 = 0;
833            let mut stack = adapter.children(at);
834            while let Some(c) = stack.pop() {
835                visited += 1;
836                if visited > ARENA_ESTIMATE_BUDGET || count(c) {
837                    cut = true;
838                    break;
839                }
840                stack.extend(adapter.children(c));
841            }
842        }
843    }
844    let filtered = !plan.conjuncts.is_empty();
845    Some(Estimate {
846        nodes: if cut {
847            (n, u64::MAX)
848        } else if filtered {
849            (0, n)
850        } else {
851            (n, n)
852        },
853        bytes: bytes_of.map(|_| if cut { (bytes, u64::MAX) } else { (0, bytes) }),
854        requests: Some(0),
855        latency,
856        confidence: if cut || filtered {
857            Confidence::Bound
858        } else {
859            Confidence::Exact
860        },
861    })
862}
863
864/// [`AstAdapter::select`]'s default, through the individual hooks:
865/// a child step by `children_named`; a descendant search by
866/// `descendants_where` when the plan leads with an equality the
867/// adapter indexes, else `descendants_named`. A wrapper that
868/// translates node ids forwards `select` to its inner adapter and
869/// falls back to this over its own hooks.
870pub fn select_by_hooks<A: AstAdapter + ?Sized>(
871    adapter: &A,
872    from: NodeId,
873    plan: &StepPlan<'_>,
874) -> Option<Selection> {
875    let name = plan.name?;
876    match plan.axis {
877        PlanAxis::Child => Some(Selection {
878            nodes: adapter
879                .children_named(from, name)
880                .into_iter()
881                .map(|n| (n, 1))
882                .collect(),
883            applied: vec![false; plan.conjuncts.len()],
884        }),
885        PlanAxis::Descendant => {
886            if let Some(Conjunct::Equals(prop, value)) = plan.conjuncts.first()
887                && let Some(nodes) = adapter.descendants_where(from, name, prop, value)
888            {
889                let mut applied = vec![false; plan.conjuncts.len()];
890                applied[0] = true;
891                return Some(Selection { nodes, applied });
892            }
893            let nodes = adapter.descendants_named(from, name)?;
894            Some(Selection {
895                nodes,
896                applied: vec![false; plan.conjuncts.len()],
897            })
898        }
899    }
900}
901
902/// The probe behind [`AstAdapter::has_node`]'s default: run a
903/// closure that may panic on a foreign node id, answering `false`
904/// when it does, without the panic reaching stderr. The process's
905/// hook is wrapped once (the first probe installs the wrapper,
906/// which defers to whatever hook was there) and a thread-local
907/// flag silences it only on the probing thread.
908mod probe {
909    use std::cell::Cell;
910    use std::sync::Once;
911
912    thread_local! {
913        static SILENT: Cell<bool> = const { Cell::new(false) };
914    }
915    static INSTALL: Once = Once::new();
916
917    pub(super) fn silently<R: Default>(f: impl FnOnce() -> R) -> R {
918        INSTALL.call_once(|| {
919            let previous = std::panic::take_hook();
920            std::panic::set_hook(Box::new(move |info| {
921                if !SILENT.with(|s| s.get()) {
922                    previous(info);
923                }
924            }));
925        });
926        SILENT.with(|s| s.set(true));
927        let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).unwrap_or_default();
928        SILENT.with(|s| s.set(false));
929        out
930    }
931}
932
933/// The kind word of a value held by a node (spec: Traits): the one
934/// structural word an adapter leads its traits with when the node
935/// is a field holding that value — what JSON's adapter mints for
936/// its scalars and containers, so every store's fields answer
937/// `:kind` alike.
938pub fn value_kind(v: &crate::Value) -> &'static str {
939    use crate::Value;
940    match v {
941        Value::Record(_) => "map",
942        Value::List(_) => "array",
943        Value::Str(_) => "string",
944        Value::Int(_) | Value::Float(_) => "number",
945        Value::Bool(_) => "boolean",
946        Value::Null => "null",
947        Value::Instant { .. } => "instant",
948        Value::Quantity { base, .. } if base == "s" => "duration",
949        Value::Period { .. } => "period",
950        Value::Quantity { .. } => "quantity",
951        Value::Table(_) => "table",
952        Value::Foreign(_) => "opaque",
953        Value::Node(_) => "node",
954        Value::Projection { .. } => "projector",
955        Value::Quarq(_) => "quarq",
956    }
957}
958
959/// The interface a data source implements to be queried by Quarb.
960///
961/// An adapter maps its native structure onto the arbor model: a tree
962/// backbone whose edges carry *names*. The engine drives navigation
963/// purely through this trait, so the same query language runs over
964/// any adapter. Three methods are required (`root`, `children`,
965/// `name`); every other one has a default an adapter overrides
966/// only where its substrate has more to say. The methods fall into
967/// groups:
968///
969/// - **The tree**: `root`, `children`, `name`, `parent`,
970///   `child_host` (a transparent link lends its target's
971///   children), `non_tree_nodes` (joined by crosslinks alone),
972///   `has_node`.
973/// - **Naming and traits**: `answers_to` (per-node spelling
974///   aliases, consulted wherever a literal name is matched),
975///   `traits`, `has_trait`.
976/// - **Properties and metadata**: `property`, `properties`,
977///   `property_names`, `default_value`, `metadata`,
978///   `aliased_metadata`.
979/// - **References**, three protocols the engine consults in this
980///   order. *Materialized edges*: `links` / `backlinks` (the `->` /
981///   `<-` steps) with `link_property` and the `prefetch_links`
982///   batching hint. *Property resolution* (`::prop-->`, `-->`,
983///   `<--`): `resolve`, `ref_property`, `ref_label`,
984///   `resolve_needs_label`, `reverse_resolve`, `reverse_label`,
985///   `can_refer_to`, `reference_properties`,
986///   `walks_for_references`, `resolves_references`. *Cross-document*
987///   (a reference naming another document): `external_ref`,
988///   `resolve_fragment`, `document_by_ref`, `tree_identities`; the
989///   engine joins the identity against the tree the reference was
990///   written in and lands through the host's registered targets,
991///   then `document_by_ref`, then the identities, and records what
992///   it could not reach. The engine performs no I/O for any of it.
993/// - **Declared indexes** (a model's `index SCOPE::prop;`):
994///   `index_lookup`, `index_referrers`.
995/// - **Search fast paths**: [`select`](Self::select) — one plan
996///   per step (axis, name matcher, the conjuncts the engine can
997///   lower, a limit, an order) an adapter may answer from an index;
998///   its default folds `children_named`, `descendants_named` and
999///   `descendants_where`, which an adapter may still implement
1000///   individually. A fast path changes cost, never the answer.
1001/// - **Evaluation hints**: `quantifier_bound` (the depth the
1002///   adapter's own structures need; a run may override it),
1003///   `unit_scale`.
1004/// - **Provenance**: `provenance`, `provenance_list`.
1005///
1006/// Pairs the engine relies on being observationally equal, so an
1007/// override must keep them so: `children_named(n, x)` is
1008/// `children(n)` filtered by `answers_to(_, x)` (except deliberate
1009/// container-scoped aliasing, documented on the method);
1010/// `has_trait(n, t)` is `t ∈ traits(n)`; `property_names(n)` covers
1011/// the names of `properties(n)`, the `ref_property`, and the child
1012/// names; `provenance_list(n)`'s first entry is `provenance(n)`;
1013/// `select` answers exactly what the walk would find. The
1014/// conformance suite ([`crate::graph::conformance::check`]) tests these
1015/// over a sample of an adapter's nodes.
1016///
1017/// Optional capabilities with a single implementor each — fine to
1018/// leave at the default: `unit_scale` (kaiv's units),
1019/// `descendants_where` (the corpus reading's positional index),
1020/// `child_host` (filesystem symlinks), `aliased_metadata` (git's
1021/// closed surface), `provenance_list` (kaiv's layered sources),
1022/// `index_lookup` / `index_referrers` (a model's declared indexes).
1023pub trait AstAdapter {
1024    /// The root node — the initial navigation context.
1025    fn root(&self) -> NodeId;
1026
1027    /// The tree children of `node`, in document order.
1028    ///
1029    /// Returns an empty vector for a leaf (or an unreadable node).
1030    fn children(&self, node: NodeId) -> Vec<NodeId>;
1031
1032    /// The name of `node` — the label of its incoming tree edge.
1033    ///
1034    /// `None` when the adapter leaves a node unnamed (typically the
1035    /// root; e.g. the filesystem root `/` carries no name).
1036    fn name(&self, node: NodeId) -> Option<String>;
1037
1038    /// The parent of `node`, or `None` for the root.
1039    fn parent(&self, _node: NodeId) -> Option<NodeId> {
1040        None
1041    }
1042
1043    /// The traits of `node` — its adapter-defined classifications,
1044    /// used by `<trait>` navigation filters (e.g. a filesystem
1045    /// adapter's `<dir>`, `<code>`, `<image>`).
1046    fn traits(&self, _node: NodeId) -> Vec<String> {
1047        Vec::new()
1048    }
1049
1050    /// A named property of `node` — `::prop`. `None` if absent.
1051    fn property(&self, _node: NodeId, _name: &str) -> Option<Value> {
1052        None
1053    }
1054
1055    /// The node's own properties, enumerated — name and value, in
1056    /// the source's order — for readings that keep values off the
1057    /// tree (the JSON property reading, where an object's scalar
1058    /// fields are no nodes). The serializers (`| json`, `| xml`,
1059    /// `| kaiv`) merge them with the children, a child winning a
1060    /// shared name. The default is none: for a reading whose values
1061    /// are all nodes, the children already say everything.
1062    fn properties(&self, _node: NodeId) -> Vec<(String, Value)> {
1063        Vec::new()
1064    }
1065
1066    /// Whether a reverse resolution or a value match with no scope
1067    /// may walk the whole arbor to find its referrers. An adapter
1068    /// over a small, in-memory source opens to the walk; a store or
1069    /// a service does not, and such a query is refused with a message
1070    /// asking for a scope — an empty answer could not be told from an
1071    /// absence of referrers. A declared reference (a foreign key, a
1072    /// model `ref`) answers through [`reverse_resolve`](Self::reverse_resolve)
1073    /// and needs no walk.
1074    fn walks_for_references(&self) -> bool {
1075        false
1076    }
1077
1078    /// Whether a reference *declared* on `source` — a catalog key, a
1079    /// model `ref`, a reference property the format defines — can
1080    /// land in `target`'s container. A question of the schema, never
1081    /// of the data; `None` where nothing is declared at the node.
1082    /// The default: a node with a reference property of its own can
1083    /// refer anywhere (an href may point at any element).
1084    fn can_refer_to(&self, source: NodeId, _target: NodeId) -> Option<bool> {
1085        self.ref_property(source).map(|_| true)
1086    }
1087
1088    /// The reference properties declared on `source` that can land
1089    /// in `target`'s container: a catalog's key columns into the
1090    /// target's table, the fields of a model's `ref`s, the node's
1091    /// own reference property. What `t<--` and `t<--(SCOPE)` read
1092    /// when the query names no property; empty where none is
1093    /// declared.
1094    fn reference_properties(&self, source: NodeId, _target: NodeId) -> Vec<String> {
1095        self.ref_property(source).into_iter().collect()
1096    }
1097
1098    /// Whether resolving `property` of `node` needs a reference
1099    /// label, because the property itself declares no target: a
1100    /// column with no key, or any property of a property graph,
1101    /// where a value names a node only under a node label. A
1102    /// label-less `::p-->` over such a property is refused with the
1103    /// remedy, since an empty answer would read as "points nowhere".
1104    fn resolve_needs_label(&self, _node: NodeId, _property: &str) -> bool {
1105        false
1106    }
1107
1108    /// The reference label under which a referrer's property is
1109    /// also resolved when a reverse arrow asks about `target` and
1110    /// the query writes no label. `None` (the default): only the
1111    /// label-less resolution counts. An adapter whose label names a
1112    /// container (a table, a collection, a node label) returns the
1113    /// one `target` stands in, so `/authors/1<--(/books/*::author_id)`
1114    /// reads `author_id` as a key into `authors` without the query
1115    /// saying so. The engine derives no label of its own.
1116    fn reverse_label(&self, _target: NodeId) -> Option<String> {
1117        None
1118    }
1119
1120    /// The trees of this arbor other trees refer to by name: each
1121    /// identity (a URL, a path, any string a reference may hold)
1122    /// with the node that stands for the tree. An identity ending
1123    /// in a separator is a base: every identity beneath it names
1124    /// the node reached beneath the base's node by the remainder's
1125    /// segments. Declared in a model (`tree IDENTITY: PATH;`) and
1126    /// automatic for a mount's own target; the engine reads nothing
1127    /// inside an identity beyond prefix and separator.
1128    fn tree_identities(&self) -> Vec<(String, NodeId)> {
1129        Vec::new()
1130    }
1131
1132    /// The names of the properties a node has — what "any
1133    /// property" means for `<--(SCOPE::*)`. By default its off-tree
1134    /// properties, its reference property, and its children's names
1135    /// (a row's columns, an object's keys are properties under the
1136    /// same names); an adapter whose properties are not children
1137    /// (an element's attributes) lists them.
1138    fn property_names(&self, node: NodeId) -> Vec<String> {
1139        let mut ps: Vec<String> = self.properties(node).into_iter().map(|(k, _)| k).collect();
1140        if let Some(r) = self.ref_property(node)
1141            && !ps.contains(&r)
1142        {
1143            ps.push(r);
1144        }
1145        for c in self.children(node) {
1146            if let Some(name) = self.name(c)
1147                && !ps.contains(&name)
1148            {
1149                ps.push(name);
1150            }
1151        }
1152        ps
1153    }
1154
1155    /// Whether this source resolves references at all. An adapter
1156    /// with no notion of a reference (a CSV file, a directory, a
1157    /// log stream) says no, and a reverse arrow over it is refused
1158    /// with the value match as the remedy, rather than answered
1159    /// with an empty set that would read as "nothing points here".
1160    fn resolves_references(&self) -> bool {
1161        true
1162    }
1163
1164    /// `index SCOPE::prop;` — the nodes of the declared scope whose
1165    /// property holds `value`, from an index the model keeps; `None`
1166    /// when no declaration covers the pair (the walk answers). An
1167    /// index changes cost, never the answer: the caller still tests
1168    /// each node it names.
1169    fn index_lookup(&self, _scope: &str, _property: &str, _value: &Value) -> Option<Vec<NodeId>> {
1170        None
1171    }
1172    /// The declared-scope nodes whose `property` resolves (under the
1173    /// relation `label`, when given) to `target`, from the same index;
1174    /// `None` when no declaration covers the pair.
1175    fn index_referrers(
1176        &self,
1177        _scope: &str,
1178        _property: &str,
1179        _label: Option<&str>,
1180        _target: NodeId,
1181    ) -> Option<Vec<NodeId>> {
1182        None
1183    }
1184
1185    /// The nodes of the arbor that are not in the tree — joined to
1186    /// it by crosslinks alone, with no parent and no path. The
1187    /// universal search `*//` reaches them after the tree, in this
1188    /// order; `:is-non-tree` is true on them. The default is
1189    /// none: every shipped adapter puts every node in the tree.
1190    fn non_tree_nodes(&self) -> Vec<NodeId> {
1191        Vec::new()
1192    }
1193
1194    /// The node whose children an explicit child step from `node`
1195    /// reads. The default is `node` itself. An adapter whose tree
1196    /// holds transparent links (a filesystem's symlink to a
1197    /// directory) answers the link's target, so `/link/name` lands
1198    /// on the target's own child — the same node `/target/name`
1199    /// reaches. The descendant walk never consults this: it reads
1200    /// [`children`](Self::children) alone, so a linked subtree is
1201    /// walked once, under its own parent, and a cycle of links
1202    /// cannot trap it.
1203    fn child_host(&self, node: NodeId) -> NodeId {
1204        node
1205    }
1206
1207    /// The children of `node` whose edge name is exactly `name` —
1208    /// the engine's fast path for name-matcher child steps. The
1209    /// default filters [`children`](Self::children); an adapter
1210    /// whose containers cannot be enumerated (permission-scoped or
1211    /// unbounded remote trees) overrides this with a direct,
1212    /// name-addressed lookup. Must be observationally identical to
1213    /// the default wherever enumeration works. The adapter owns the
1214    /// name test: it may deliberately *alias* — resolve a name to a
1215    /// node whose edge name differs (git revision syntax landing on
1216    /// a hash-named commit) — and the engine will not re-filter.
1217    /// Container-scoped resolution like that stays child-axis only;
1218    /// per-node spelling aliases belong in
1219    /// [`answers_to`](Self::answers_to), which this default
1220    /// consults.
1221    fn children_named(&self, node: NodeId, name: &str) -> Vec<NodeId> {
1222        self.children(node)
1223            .into_iter()
1224            .filter(|&c| self.answers_to(c, name))
1225            .collect()
1226    }
1227
1228    /// Whether `node` answers to `name` as a literal spelling
1229    ///. The default is canonical equality. An adapter
1230    /// may declare per-node aliases — a social feed spelling a
1231    /// handle `@alice` while the stripped `alice` is the step name —
1232    /// and the engine consults this wherever a *literal* name is
1233    /// matched, on every axis, so one override keeps `/@alice` and
1234    /// `//@alice` in agreement. `:name` stays canonical (locators
1235    /// and reflection print it; an alias is a way in, never a way
1236    /// out), and name patterns (`~(...)`, `*`) test the canonical
1237    /// name only.
1238    fn answers_to(&self, node: NodeId, name: &str) -> bool {
1239        self.name(node).as_deref() == Some(name)
1240    }
1241
1242    /// Whether `node` bears `name` as a trait, as written in a
1243    /// `<...>` clause. The default is membership in
1244    /// [`traits`](Self::traits); an adapter may declare aliases the
1245    /// way [`answers_to`](Self::answers_to) does for names — a
1246    /// model file's `alias <chunk> <block>;` or
1247    /// `alias <s/^tag://i>;` — and the engine consults this
1248    /// wherever a written trait is matched. Reflection and
1249    /// serialization print the canonical traits only.
1250    fn has_trait(&self, node: NodeId, name: &str) -> bool {
1251        self.traits(node).iter().any(|t| t == name)
1252    }
1253
1254    /// The default projection of `node` — bare `::`, adapter-specific
1255    /// (a filesystem adapter returns file content).
1256    fn default_value(&self, _node: NodeId) -> Option<Value> {
1257        None
1258    }
1259
1260    /// Adapter-defined metadata — `:::key` (a filesystem adapter's
1261    /// `size`, `modified`, `permissions`, …). `None` if absent.
1262    fn metadata(&self, _node: NodeId, _key: &str) -> Option<Value> {
1263        None
1264    }
1265
1266    /// The `:::` keys this node answers (spec: the `:meta` core
1267    /// field, draft 164): the adapter's catalogue filtered by what
1268    /// the node answers. A composite adapter delegates to the
1269    /// adapter that owns the node.
1270    fn metadata_keys(&self, node: NodeId) -> Vec<String> {
1271        self.metadata_catalogue()
1272            .iter()
1273            .filter(|k| self.metadata(node, k).is_some())
1274            .map(|k| k.to_string())
1275            .collect()
1276    }
1277
1278    /// Every `:::` key this adapter can answer, for `metadata_keys`;
1279    /// an adapter with none declared lists none.
1280    fn metadata_catalogue(&self) -> &'static [&'static str] {
1281        &[]
1282    }
1283
1284    /// Metadata keys this adapter also answers at `::` (ruling
1285    /// #29), for the given node — per node, because a composite
1286    /// adapter (a multi-mount, a graft) answers for whichever
1287    /// document owns it. Only an adapter whose property surface is *closed* —
1288    /// fixed by the adapter, never grown by document content — may
1289    /// declare aliases: a git commit cannot sprout a `short` field,
1290    /// where a JSON object can sprout anything. Data always wins:
1291    /// the engine consults `property` first and falls through only
1292    /// when it answers `None` for that node, so an alias can never
1293    /// shadow a document. A core field (`:`) is never aliased —
1294    /// `name`, `id` and `index` exist on every node, and aliasing
1295    /// them would change what `::name` means wherever a document
1296    /// happens to lack that field.
1297    fn aliased_metadata(&self, _node: NodeId) -> &'static [&'static str] {
1298        &[]
1299    }
1300
1301    /// Outgoing crosslinks from `node`, as `(label, target)` pairs,
1302    /// for `->` navigation (a filesystem adapter's symlinks).
1303    fn links(&self, _node: NodeId) -> Vec<(String, NodeId)> {
1304        Vec::new()
1305    }
1306
1307    /// Incoming crosslinks to `node`, as `(label, source)` pairs, for
1308    /// `<-` navigation. May be expensive (an adapter that does not
1309    /// precompute edges must search for referrers).
1310    fn backlinks(&self, _node: NodeId) -> Vec<(String, NodeId)> {
1311        Vec::new()
1312    }
1313
1314    /// `links` with each edge's identity: the node that IS the edge,
1315    /// for an adapter whose edges are rows (a model's `edge … as
1316    /// flight` over a flights table: the row is the edge, its cells
1317    /// the edge's properties), `None` for an edge that is nothing but
1318    /// a link. Two rows on one leg are two edges — each its own
1319    /// thread, each its own `$-` (spec: Edge rows). The default reads
1320    /// `links` with no identity.
1321    fn link_rows(&self, node: NodeId) -> Vec<(String, NodeId, Option<NodeId>)> {
1322        self.links(node)
1323            .into_iter()
1324            .map(|(l, t)| (l, t, None))
1325            .collect()
1326    }
1327
1328    /// The edges of the graph as a table (spec: The graph as a
1329    /// table, The graph library): what `edges` collects and the
1330    /// graph library reads, from `node` outward. By default the link
1331    /// rows; a level whose step lands inside the target — the web's
1332    /// fragment link, which `links` lands on the section — reports
1333    /// the edge to the target node itself, so that the induced
1334    /// subgraph of the pages carries it and the stored rank's graph
1335    /// is the one the library ranks.
1336    fn edge_rows(&self, node: NodeId) -> Vec<(String, NodeId, Option<NodeId>)> {
1337        self.link_rows(node)
1338    }
1339
1340    /// `backlinks` with each edge's identity, as `link_rows`.
1341    fn backlink_rows(&self, node: NodeId) -> Vec<(String, NodeId, Option<NodeId>)> {
1342        self.backlinks(node)
1343            .into_iter()
1344            .map(|(l, s)| (l, s, None))
1345            .collect()
1346    }
1347
1348    /// `link_rows` for a step that names one label (`->customer`):
1349    /// the rows a step by `label` can take, and any others the
1350    /// adapter cares to add (the engine selects by the label either
1351    /// way). An adapter that reads its links when asked reads the
1352    /// one reference the label names: a relational source the row
1353    /// one foreign key points at, not the row behind every key of
1354    /// the table. The default is every row.
1355    fn link_rows_by(&self, node: NodeId, _label: &str) -> Vec<(String, NodeId, Option<NodeId>)> {
1356        self.link_rows(node)
1357    }
1358
1359    /// `backlink_rows` for a step that names one label
1360    /// (`<-manager`), as `link_rows_by`: a relational source reads
1361    /// the referrers under the one key that carries the label, not
1362    /// every table with a key into this one.
1363    fn backlink_rows_by(
1364        &self,
1365        node: NodeId,
1366        _label: &str,
1367    ) -> Vec<(String, NodeId, Option<NodeId>)> {
1368        self.backlink_rows(node)
1369    }
1370
1371    /// Whether the links into `node` are ones this source cannot walk
1372    /// back (spec: The adapter contract): it answers `links` and
1373    /// provides no `backlinks`, as a document store whose references
1374    /// live in the referring documents does. A step that needs the
1375    /// backward direction there (`<-`, `--`, the navop wildcard,
1376    /// `edges` over any of them) is refused, the refusal naming what
1377    /// the source lacks, rather than answered with an empty set that
1378    /// would read as "nothing points here". `label` is the one label
1379    /// the step names when it names exactly one, `None` for a
1380    /// wildcard, a pattern or a selection: a layer that walks some
1381    /// labels back itself (a model's declared references over such a
1382    /// source) answers for those and hands the rest down. A source
1383    /// with no links at all says no: there is nothing to walk back,
1384    /// and the empty answer is the true one. False by default.
1385    fn backlinks_unsupported(&self, _node: NodeId, _label: Option<&str>) -> bool {
1386        false
1387    }
1388
1389    /// Whether the link from `source` under `label` is a reference
1390    /// an edge declaration consumed: a bare wildcard step (`->*`,
1391    /// `<-*`, `--*`, the crosslink part of `~`) skips it, the label
1392    /// named (`<-origin`) still walks it (spec: Model Files, Edge
1393    /// rows). A model's `edge /flights/*: ::origin -- ::dest`
1394    /// consumes the two references its fields resolve through, so a
1395    /// wildcard from an airport reaches the carrier edges and not the
1396    /// flight rows; a reference no edge consumed stays visible to
1397    /// wildcards. The default consumes nothing.
1398    fn link_consumed(&self, _source: NodeId, _label: &str) -> bool {
1399        false
1400    }
1401
1402    /// Resolve a cross-reference: `::property-->hint` maps `node`'s
1403    /// `property` (a value that references another node) to its target,
1404    /// with an optional adapter-specific `hint` (a relation type such as
1405    /// an html `rel`, or a target container such as a table). A JSON
1406    /// adapter resolves a `$ref` JSON Pointer; `None` if unresolvable.
1407    fn resolve(&self, _node: NodeId, _property: &str, _hint: Option<&str>) -> Option<NodeId> {
1408        None
1409    }
1410
1411    /// The external reference `node`'s `property` holds, if any: the
1412    /// identity of a document *outside this arbor* and, where the
1413    /// reference says so, the location within it — both as the
1414    /// adapter reads them out of its own reference syntax (for html,
1415    /// the anchor's absolute URL and its fragment). The engine does
1416    /// not look inside either string: it asks for the document among
1417    /// the mounts (the host's registration, then
1418    /// [`document_by_ref`](Self::document_by_ref)), and hands the
1419    /// location to [`resolve_fragment`](Self::resolve_fragment) on
1420    /// the document it found. Consulted by `::property-->` when
1421    /// in-document resolution misses; an unmounted document lands
1422    /// among the run's unresolved external references for the
1423    /// host's acquisition loop. The engine itself never fetches.
1424    fn external_ref(
1425        &self,
1426        _node: NodeId,
1427        _property: &str,
1428        _hint: Option<&str>,
1429    ) -> Option<ExternalRef> {
1430        None
1431    }
1432
1433    /// The element `fragment` names inside the document `node`
1434    /// belongs to — html's `id` lookup. The landing rung of a
1435    /// fragment-carrying external reference, once its document is
1436    /// mounted.
1437    fn resolve_fragment(&self, _node: NodeId, _fragment: &str) -> Option<NodeId> {
1438        None
1439    }
1440
1441    /// The property carrying `node`'s own reference, for the bare
1442    /// arrow (`//a-->`): an html anchor's `href`, an iframe's
1443    /// `src`. `None` for a node that references nothing.
1444    fn ref_property(&self, _node: NodeId) -> Option<String> {
1445        None
1446    }
1447
1448    /// The relation name a resolution edge from `node` via
1449    /// `property` carries — html's `rel` attribute. `None` falls
1450    /// back to the property name as the edge label.
1451    fn ref_label(&self, _node: NodeId, _property: &str) -> Option<String> {
1452        None
1453    }
1454
1455    /// A property of the crosslink `source --label--> target` — the
1456    /// `$-::prop` read. Adapters whose edges carry data (a property
1457    /// graph's relationship properties) override this; `None` if the
1458    /// edge is bare or unknown. Where parallel edges share source,
1459    /// label, and target, the adapter answers for one of them,
1460    /// consistently.
1461    fn link_property(
1462        &self,
1463        _source: NodeId,
1464        _label: &str,
1465        _target: NodeId,
1466        _name: &str,
1467    ) -> Option<Value> {
1468        None
1469    }
1470
1471    /// The document this arbor holds under an external-reference
1472    /// identifier (a URL, fragment-stripped), when it can answer
1473    /// without the host's registration: the landing rung of `-->`
1474    /// after the mounted-document table misses. An adapter over a
1475    /// store of pages answers by URL lookup; the engine performs
1476    /// no IO either way.
1477    fn document_by_ref(&self, _id: &str) -> Option<NodeId> {
1478        None
1479    }
1480
1481    /// Every node whose `property` (or, when `None`, own reference
1482    /// property) resolves to `node`, in document order — the
1483    /// reverse index behind `<--`. `None` keeps the engine's walk
1484    /// of the whole arbor; `Some` is the adapter's complete answer.
1485    fn reverse_resolve(
1486        &self,
1487        _node: NodeId,
1488        _property: Option<&str>,
1489        _hint: Option<&str>,
1490    ) -> Option<Vec<NodeId>> {
1491        None
1492    }
1493
1494    /// The descendants of `node` that answer to `name`, each with
1495    /// its depth (children are depth 1), in document order — the
1496    /// fast path behind `//name` for an adapter whose substrate
1497    /// indexes names. `None` keeps the engine's walk; `Some` must
1498    /// be exactly what the walk would find.
1499    fn descendants_named(&self, _node: NodeId, _name: &str) -> Option<Vec<(NodeId, usize)>> {
1500        None
1501    }
1502
1503    /// The descendants of `node` named `name` whose property
1504    /// `property` equals `value`, each with its depth, in document
1505    /// order — the fast path behind `//name[::property = "value"]`
1506    /// for an adapter that indexes a property (the corpus reading's
1507    /// positional index answers `//token[::lower = "tom"]` from it).
1508    /// `None` keeps the engine's walk and its comparison; `Some`
1509    /// must be exactly what the walk would find under the standard
1510    /// equality, so an adapter answers only the values it can
1511    /// compare as the engine does (text against text).
1512    fn descendants_where(
1513        &self,
1514        _node: NodeId,
1515        _name: &str,
1516        _property: &str,
1517        _value: &Value,
1518    ) -> Option<Vec<(NodeId, usize)>> {
1519        None
1520    }
1521
1522    /// Whether a deep walk looking for `name` (None for any name)
1523    /// with `traits` may still find a match below `node`; a cost
1524    /// hint only, never a reading. An adapter whose subtrees are
1525    /// typed answers false where nothing sought can stand beneath
1526    /// (a web page's subtree is its document: no page, dir, redirect,
1527    /// tag or category below it), and the walk skips the subtree.
1528    /// True by default.
1529    fn may_hold_below(&self, _node: NodeId, _name: Option<&str>, _traits: &[&str]) -> bool {
1530        true
1531    }
1532
1533    /// The search fast path: the nodes one step reaches from `from`
1534    /// under `plan`, answered from an index — `None` keeps the
1535    /// engine's walk (the default folds `children_named`,
1536    /// `descendants_named` and `descendants_where`:
1537    /// [`select_by_hooks`]). `Some` must be exactly what the walk
1538    /// would find for the conjuncts it marks applied, under the
1539    /// engine's standard equality; the engine tests the remaining
1540    /// conjuncts and every other predicate on the nodes returned. A
1541    /// child plan's answer is never re-filtered by name (the adapter
1542    /// owns the name test, as `children_named` does); a descendant
1543    /// plan's nodes still pass the nameless tests.
1544    fn select(&self, from: NodeId, plan: &StepPlan<'_>) -> Option<Selection> {
1545        select_by_hooks(self, from, plan)
1546    }
1547    /// The dry-run form of [`select`](Self::select): which of the
1548    /// plan's conjuncts the adapter would apply, decided from its
1549    /// catalog alone (a column's existence and type, an index's
1550    /// presence), with no node in hand. `scope` is the literal path
1551    /// from the root to the step's base (`["invoices"]` for
1552    /// `/invoices/*[...]`), empty at the root. `None` when the
1553    /// adapter cannot say — the static plan then counts every
1554    /// conjunct as the engine's.
1555    fn select_plan(&self, _scope: &[&str], _plan: &StepPlan<'_>) -> Option<Vec<bool>> {
1556        None
1557    }
1558    /// What reaching one step's nodes would cost, said from the
1559    /// catalog with no node in hand (`scope` as for
1560    /// [`select_plan`](Self::select_plan)): a warehouse's dry run,
1561    /// a table's statistics, a file's size, an arena's count.
1562    /// `None` where the adapter has no estimator — the plan then
1563    /// reads "unknown" for the step.
1564    fn estimate(&self, _scope: &[&str], _plan: &StepPlan<'_>) -> Option<Estimate> {
1565        None
1566    }
1567    /// How many nodes one step reaches from `from` under `plan`,
1568    /// without materializing them — `@| count` right after the step
1569    /// asks before walking. `None` walks; `Some` must be exactly the
1570    /// walk's count for the conjuncts the plan carries (every one of
1571    /// them, or none: a count cannot be partially applied). SQL:
1572    /// `SELECT COUNT(*)`; a document index: the bucket's length.
1573    fn count(&self, _from: NodeId, _plan: &StepPlan<'_>) -> Option<usize> {
1574        None
1575    }
1576    /// The surface the source declares for the container `node` is a
1577    /// member of (ruling 2026-11-10): where a source declares every
1578    /// property its members have and every label that leaves or
1579    /// reaches them (a table's columns and keys, a CSV's header), it
1580    /// says so for a member (a row), and a query that names what the
1581    /// surface lacks is warned. `None`, the default, is a source that
1582    /// declares nothing: a key absent from one JSON object is
1583    /// ordinary data, and nothing is said. So is a node that is no
1584    /// member (the table itself, a cell). A composite answers for
1585    /// the adapter that owns the node and names the container from
1586    /// its own root ([`Surface::under`]).
1587    fn surface(&self, _node: NodeId) -> Option<Surface> {
1588        None
1589    }
1590    /// The columns of the rows `row_text` serves, asked for the
1591    /// source `node` belongs to (the one-pass typed build,
1592    /// 2026-11-06): a source whose rows are records of one shape — a
1593    /// CSV's — names them; `None` where the rows have no one shape,
1594    /// and a table build reads each node's record. A mount of several
1595    /// sources answers for the one holding `node`.
1596    fn row_columns(&self, _node: NodeId) -> Option<Vec<String>> {
1597        None
1598    }
1599    /// The node `node` stands for (ruling 2026-11-06, identity is
1600    /// intrinsic): a node of a model's role answers the source node
1601    /// it aliases, so `:id`, `:name` and `:path` are the source's and
1602    /// `collapse`, `unique`, `((!N))` and the cycle check see one
1603    /// node; the role stays visible to navigation alone. Every other
1604    /// node stands for itself.
1605    fn intrinsic(&self, node: NodeId) -> NodeId {
1606        node
1607    }
1608    /// The cells of a row node as text, in the order of
1609    /// `row_columns`, handed to `f` once — an empty text a cell the
1610    /// row lacks (null), each text in the source's canonical form —
1611    /// and `true`; `false` where the node is no row of that shape,
1612    /// and the build reads its record. The one-pass typed build
1613    /// parses the cells from the text, no value made on the way.
1614    fn row_text(&self, _node: NodeId, _f: &mut dyn FnMut(&[&str])) -> bool {
1615        false
1616    }
1617    /// A batching hint, the projection twin of `prefetch_links`: the
1618    /// engine is about to read the properties `names` of every node
1619    /// in `nodes` (the next command projects them). A remote adapter
1620    /// fetches the columns for the frontier in one round trip;
1621    /// semantics are unchanged either way.
1622    fn prefetch_properties(&self, _nodes: &[NodeId], _names: &[&str]) {}
1623    /// A batching hint: the engine is about to follow `dir`
1624    /// crosslinks from every node in `nodes`. An adapter backed by
1625    /// a store may fetch them in one statement; semantics are
1626    /// unchanged either way.
1627    fn prefetch_links(&self, _nodes: &[NodeId], _dir: LinkDir) {}
1628    /// `prefetch_links` for a step that names what it follows: the
1629    /// one label of a link step, or the property a resolution reads.
1630    /// A store fetches that reference alone. The default is the
1631    /// whole hint.
1632    fn prefetch_links_by(&self, nodes: &[NodeId], dir: LinkDir, _by: LinkBy<'_>) {
1633        self.prefetch_links(nodes, dir)
1634    }
1635    /// Drop any pushed-down listing filter: from here on every
1636    /// table's listing is the whole table. A model's fabric indexes
1637    /// a ref's target container by listing it, and a listing the
1638    /// planner narrowed to the query's rows would drop every edge
1639    /// whose far end the predicate excluded; the engine re-applies
1640    /// the pushed predicates, so a whole listing changes no answer.
1641    /// A no-op for an adapter that never filters a listing.
1642    fn whole_listings(&self) {}
1643    /// A standing session is about to run a query (`--resident`, a
1644    /// notebook's session): a source that can change under the
1645    /// session looks again at what may have moved, so the query
1646    /// answers the source as it stands. A git repository looks at
1647    /// its refs (one `git show-ref`) and forgets what it read off
1648    /// them where one moved; what a hash names it keeps. A no-op for
1649    /// a source read whole at the open, which a session serves as
1650    /// it was then.
1651    fn refresh(&self) {}
1652
1653    /// The names of the properties an edge carries — the weights a
1654    /// budget quantifier may sum (spec: The budget quantifier) and
1655    /// the columns `@| edges` lists. Empty by default: an adapter
1656    /// whose edges carry properties ([`AstAdapter::link_property`])
1657    /// names them here, so the engine can pick the one of the
1658    /// budget's dimension.
1659    fn link_property_names(&self, _source: NodeId, _label: &str, _target: NodeId) -> Vec<String> {
1660        Vec::new()
1661    }
1662
1663    /// The WEIGHTS an edge carries (spec: the edge model, ruling
1664    /// 2026-11-07): quantities with pairwise distinct dimensions,
1665    /// none dimensionless, in the canonical dimension order — what a
1666    /// budget quantifier sums for its dimension and `--weight=UNIT`
1667    /// reads, never inferred from the edge's properties. Empty by
1668    /// default: a model declares them (`weights(::km)`, a
1669    /// `weight-potential`); a substrate that carries weights of its
1670    /// own mints them here. `row` is the edge's own row where the
1671    /// edge is one; `forward` whether the walk crosses the edge from
1672    /// its source to its target (a potential's difference flips its
1673    /// sign with the traversal).
1674    fn edge_weights(
1675        &self,
1676        _source: NodeId,
1677        _label: &str,
1678        _target: NodeId,
1679        _row: Option<NodeId>,
1680        _forward: bool,
1681    ) -> Vec<Value> {
1682        Vec::new()
1683    }
1684
1685    /// The promise that no walk over the link `label` returns to a
1686    /// node (spec: Model Files, Acyclic links): the declaration, or
1687    /// the source's own word, that makes it — for the refusal that
1688    /// names it when the data breaks it. `None` for a link that
1689    /// makes no promise, every link by default. Under the promise the
1690    /// exact forms of a quantified walk expand by node and round
1691    /// instead of by history.
1692    fn acyclic_link(&self, _label: &str) -> Option<String> {
1693        None
1694    }
1695
1696    /// The quantifier bound N_max: the depth to which open-ended path
1697    /// quantifiers (`+`, `*`, `{m,}`) expand, and the ceiling of any
1698    /// explicit `{m,n}` (the effective upper bound is min(n, N_max)).
1699    /// An adapter whose natural structures run deep may raise it; a
1700    /// run may override it (`Run::quantifier_bound`, the CLI's
1701    /// `--quantifier-bound`). The shell gate and the invocation
1702    /// instant are the run's alone (`Run::allow_shell`, `Run::now`).
1703    fn quantifier_bound(&self) -> usize {
1704        32
1705    }
1706
1707    /// The frontier bound: the most expansion paths one round of a
1708    /// quantified walk may hold in flight. A set walk (an open
1709    /// quantifier with a floor of at most one, under all matches or
1710    /// the proximal reach, no push or mark) reaches each node once
1711    /// and never nears it; an exact walk keeps one acyclic walk per
1712    /// history, and over data with many routes to a node that count
1713    /// explodes — the bound refuses the walk by name instead of
1714    /// running for hours. A run
1715    /// may override it (`Run::frontier_bound`, the CLI's
1716    /// `--frontier-bound`).
1717    fn frontier_bound(&self) -> usize {
1718        100_000
1719    }
1720
1721    /// Whether `property(node, name)` answered None because the caller
1722    /// may not read the property, rather than the node lacking it
1723    /// (spec: omitted data). Asked only after an absent read. The
1724    /// property stays absent; the engine warns once per query, and
1725    /// refuses where the read would key a filter, a sort, a group or
1726    /// an aggregate. False by default.
1727    fn property_withheld(&self, _node: NodeId, _name: &str) -> bool {
1728        false
1729    }
1730
1731    /// The properties the caller may not read anywhere in the source
1732    /// (spec: omitted data): never pushed into the store's query as a
1733    /// conjunct or an index lookup. None by default.
1734    fn withheld_properties(&self) -> Vec<String> {
1735        Vec::new()
1736    }
1737
1738    /// Whether the source dropped whole nodes for the caller in this
1739    /// run (spec: omitted data): a gated table or branch that is
1740    /// simply not there. Asked once after the run; true raises the
1741    /// omission warning. False by default.
1742    fn nodes_withheld(&self) -> bool {
1743        false
1744    }
1745
1746    /// The graph bound (spec: The graph library, Other bounds): the
1747    /// most cost units a library command may compute over, a unit
1748    /// being a node or an edge of the induced subgraph (their product
1749    /// for betweenness); reaching it refuses before the command
1750    /// computes. Ten million unless the adapter says otherwise.
1751    fn graph_bound(&self) -> usize {
1752        10_000_000
1753    }
1754
1755    /// The graphs the source maintains measures over (spec: Graph
1756    /// Declarations): a model's `graph` statements, or a level's own
1757    /// stored measures (the web level's rank). None by default.
1758    fn graph_declarations(&self) -> Vec<crate::graph::edges::GraphDeclaration> {
1759        Vec::new()
1760    }
1761
1762    /// A declared measure's values for `nodes`, the declared scope
1763    /// entire in the engine's order, once the engine has found the
1764    /// command's step, options and context to be the declared ones:
1765    /// one value per node, or one table for a table-answering
1766    /// command. `None` declines, and the engine computes.
1767    fn graph_measure(
1768        &self,
1769        _scope: &str,
1770        _hop: &str,
1771        _measure: &str,
1772        _nodes: &[NodeId],
1773    ) -> Option<Vec<Value>> {
1774        None
1775    }
1776
1777    /// The values the engine computed for a declared measure the
1778    /// source declined, offered for the source to keep and answer
1779    /// next time; nothing by default.
1780    fn store_graph_measure(
1781        &self,
1782        _scope: &str,
1783        _hop: &str,
1784        _measure: &str,
1785        _nodes: &[NodeId],
1786        _values: &[Value],
1787    ) {
1788    }
1789
1790    /// The data provenance of `node` — the `:source` /
1791    /// `:instant` / `:dpid` / `:provenance` core-metadata
1792    /// keys. Empty by default: an adapter answers only the
1793    /// components its substrate genuinely records (never the
1794    /// invocation clock); wrapper adapters fill missing components
1795    /// from what they know — the mount its target, a graft its
1796    /// outer leaf, a model its derivation — and forward the rest
1797    /// inward, so resolution is nearest-ancestor per component.
1798    fn provenance(&self, _node: NodeId) -> Provenance {
1799        Provenance::default()
1800    }
1801
1802    /// Whether `node` is an id this adapter minted — the guard
1803    /// behind the node-id anchor `((!N))`, which may name an id
1804    /// from an earlier run (ids are minted deterministically: the
1805    /// same source, the same ids). The default probes the id
1806    /// through `parent` and `name` and treats a panic as absence,
1807    /// so an adapter that indexes by id needs no override; one that
1808    /// can answer cheaply should.
1809    fn has_node(&self, node: NodeId) -> bool {
1810        if node == self.root() {
1811            return true;
1812        }
1813        // An adapter that indexes its arena panics on a foreign id;
1814        // the probe catches that. The panic hook is installed once
1815        // for the process and silenced per thread while probing —
1816        // never swapped, so other threads keep theirs.
1817        probe::silently(|| self.parent(node).is_some() || self.name(node).is_some())
1818    }
1819
1820    /// The data provenance of `node` as a list — every source the
1821    /// substrate records for the datum, and how many it elides.
1822    /// The default is the singular answer as a one-entry list; an
1823    /// adapter whose substrate records several (kaiv's `?a;b;+N`)
1824    /// overrides it, and a wrapper layers each entry.
1825    fn provenance_list(&self, node: NodeId) -> ProvenanceList {
1826        ProvenanceList::single(self.provenance(node))
1827    }
1828
1829    /// The scale of a unit expression — (factor, canonical SI-base
1830    /// expansion) — for the unital reading's criterion text (spec:
1831    /// The Quantital Fragment). The default answers from the
1832    /// engine's frozen built-in table; a unit-aware adapter (kaiv)
1833    /// overrides it to include the mounted document's own custom
1834    /// units, so `[::range < '50kellicam']` resolves through the
1835    /// document's `.!units` imports.
1836    fn unit_scale(&self, expr: &str) -> Option<(f64, String)> {
1837        crate::value::quantity::scale_expr(expr)
1838    }
1839
1840    /// The unit names the mounted source adds to the built-in
1841    /// table, every spelling (a model's declarations, a kaiv
1842    /// document's own units); empty by default. The parser judges
1843    /// the operand of `convert(U)` and `unit(U)` against the table
1844    /// and this list (spec: The conversion): an unknown name there
1845    /// is refused, where a value's unknown unit stays opaque.
1846    fn unit_names(&self) -> Vec<String> {
1847        Vec::new()
1848    }
1849
1850    /// The notation the substrate declares for a leaf's text (spec:
1851    /// Grafting): a column typed json or jsonb answers `json`, an
1852    /// HTTP response its content type's notation. The composition
1853    /// layer grafts such a leaf as declared; a leaf nothing declares
1854    /// (not this, not its name, not the mount, not the query) is a
1855    /// leaf. `None` by default.
1856    fn declared_notation(&self, _node: NodeId) -> Option<String> {
1857        None
1858    }
1859
1860    /// Graft a text on demand (spec: Grafting, `graft(NOTATION)`):
1861    /// parse `text` as the notation named, or as what it declares
1862    /// about itself when none is, and answer the parsed document's
1863    /// root, a free root with no parent in the arbor. `None` when
1864    /// this adapter has no composing layer to graft with; `Some(Err)`
1865    /// names what did not parse or what the operand did not name.
1866    fn graft_text(&self, _text: &str, _notation: Option<&str>) -> Option<Result<NodeId, String>> {
1867        None
1868    }
1869
1870    /// Whether a composing layer stands in this adapter, so that
1871    /// `graft_text` answers and a host need not add one (the host
1872    /// wraps every other source in a graft-only layer at the mount).
1873    fn grafts_on_demand(&self) -> bool {
1874        false
1875    }
1876
1877    /// The construct a node of a reflected query stands for, cloned
1878    /// (design paper: a handle from each reflected node to its AST
1879    /// node): what a template expansion grafts when a hole reaches
1880    /// the node. `None` for every arbor that is no query.
1881    fn form_of(&self, _node: NodeId) -> Option<crate::Form> {
1882        None
1883    }
1884}
1885
1886/// Forwards every [`AstAdapter`] method to a wrapped adapter — the
1887/// one definition behind the wrappers (the boxed carrier, the
1888/// decoding layer, the mount and model wrappers), so a method added to the
1889/// trait is forwarded everywhere at once instead of silently
1890/// falling back to the trait default in whichever wrapper the
1891/// hand-written list missed.
1892///
1893/// The first argument names the wrapped adapter: a field (`inner`,
1894/// `0`) reached as `self.FIELD`, or `*` for a `Box<dyn AstAdapter>`
1895/// forwarding through `**self`. The optional `except` list names the
1896/// methods the wrapper defines itself, right after the invocation:
1897///
1898/// ```ignore
1899/// impl<A: AstAdapter> AstAdapter for Bounded<'_, A> {
1900///     quarb::forward_ast_adapter!(inner; except quantifier_bound);
1901///     fn quantifier_bound(&self) -> usize {
1902///         self.bound
1903///     }
1904/// }
1905/// ```
1906///
1907/// The method table inside the macro is checked against the trait
1908/// by `forwarding::the_macro_lists_every_trait_method`, and each
1909/// shipped wrapper against a probe adapter by
1910/// `forwarding::every_wrapper_forwards_every_method`.
1911#[macro_export]
1912macro_rules! forward_ast_adapter {
1913    ($inner:tt $(; except $($except:ident),+ $(,)?)? $(;)?) => {
1914        $crate::forward_ast_adapter!(@each [$inner] [$($($except)+)?]
1915            // Every method of `AstAdapter`, in the trait's order; the
1916            // coverage test reads this list from the source.
1917            root children name parent traits property properties
1918            walks_for_references can_refer_to reference_properties
1919            resolve_needs_label reverse_label tree_identities
1920            property_names resolves_references index_lookup
1921            index_referrers non_tree_nodes child_host children_named
1922            answers_to has_trait default_value metadata
1923            metadata_keys metadata_catalogue
1924            aliased_metadata links backlinks link_rows edge_rows backlink_rows
1925            link_rows_by backlink_rows_by backlinks_unsupported
1926            link_consumed resolve external_ref
1927            resolve_fragment ref_property ref_label link_property
1928            document_by_ref reverse_resolve descendants_named
1929            descendants_where may_hold_below select select_plan estimate count
1930            surface row_columns intrinsic row_text prefetch_properties
1931            prefetch_links prefetch_links_by whole_listings refresh link_property_names edge_weights acyclic_link quantifier_bound frontier_bound
1932            property_withheld withheld_properties nodes_withheld
1933            graph_bound graph_declarations graph_measure store_graph_measure
1934            provenance has_node
1935            provenance_list unit_scale unit_names declared_notation graft_text grafts_on_demand
1936            form_of
1937        );
1938    };
1939    (@each [$inner:tt] $ex:tt $($m:ident)*) => {
1940        $( $crate::forward_ast_adapter!(@unless [$inner] $ex $m); )*
1941    };
1942
1943    // The excepted method heads the list: emit nothing. One arm per
1944    // method, since a macro cannot compare two captured identifiers.
1945    (@unless [$i:tt] [root $($r:ident)*] root) => {};
1946    (@unless [$i:tt] [children $($r:ident)*] children) => {};
1947    (@unless [$i:tt] [name $($r:ident)*] name) => {};
1948    (@unless [$i:tt] [parent $($r:ident)*] parent) => {};
1949    (@unless [$i:tt] [traits $($r:ident)*] traits) => {};
1950    (@unless [$i:tt] [property $($r:ident)*] property) => {};
1951    (@unless [$i:tt] [properties $($r:ident)*] properties) => {};
1952    (@unless [$i:tt] [walks_for_references $($r:ident)*] walks_for_references) => {};
1953    (@unless [$i:tt] [can_refer_to $($r:ident)*] can_refer_to) => {};
1954    (@unless [$i:tt] [reference_properties $($r:ident)*] reference_properties) => {};
1955    (@unless [$i:tt] [resolve_needs_label $($r:ident)*] resolve_needs_label) => {};
1956    (@unless [$i:tt] [reverse_label $($r:ident)*] reverse_label) => {};
1957    (@unless [$i:tt] [tree_identities $($r:ident)*] tree_identities) => {};
1958    (@unless [$i:tt] [property_names $($r:ident)*] property_names) => {};
1959    (@unless [$i:tt] [resolves_references $($r:ident)*] resolves_references) => {};
1960    (@unless [$i:tt] [index_lookup $($r:ident)*] index_lookup) => {};
1961    (@unless [$i:tt] [index_referrers $($r:ident)*] index_referrers) => {};
1962    (@unless [$i:tt] [non_tree_nodes $($r:ident)*] non_tree_nodes) => {};
1963    (@unless [$i:tt] [child_host $($r:ident)*] child_host) => {};
1964    (@unless [$i:tt] [children_named $($r:ident)*] children_named) => {};
1965    (@unless [$i:tt] [answers_to $($r:ident)*] answers_to) => {};
1966    (@unless [$i:tt] [has_trait $($r:ident)*] has_trait) => {};
1967    (@unless [$i:tt] [default_value $($r:ident)*] default_value) => {};
1968    (@unless [$i:tt] [metadata $($r:ident)*] metadata) => {};
1969    (@unless [$i:tt] [metadata_keys $($r:ident)*] metadata_keys) => {};
1970    (@unless [$i:tt] [metadata_catalogue $($r:ident)*] metadata_catalogue) => {};
1971    (@unless [$i:tt] [aliased_metadata $($r:ident)*] aliased_metadata) => {};
1972    (@unless [$i:tt] [links $($r:ident)*] links) => {};
1973    (@unless [$i:tt] [backlinks $($r:ident)*] backlinks) => {};
1974    (@unless [$i:tt] [link_rows $($r:ident)*] link_rows) => {};
1975    (@unless [$i:tt] [edge_rows $($r:ident)*] edge_rows) => {};
1976    (@unless [$i:tt] [graph_bound $($r:ident)*] graph_bound) => {};
1977    (@unless [$i:tt] [may_hold_below $($r:ident)*] may_hold_below) => {};
1978    (@unless [$i:tt] [property_withheld $($r:ident)*] property_withheld) => {};
1979    (@unless [$i:tt] [withheld_properties $($r:ident)*] withheld_properties) => {};
1980    (@unless [$i:tt] [nodes_withheld $($r:ident)*] nodes_withheld) => {};
1981    (@unless [$i:tt] [graph_declarations $($r:ident)*] graph_declarations) => {};
1982    (@unless [$i:tt] [graph_measure $($r:ident)*] graph_measure) => {};
1983    (@unless [$i:tt] [store_graph_measure $($r:ident)*] store_graph_measure) => {};
1984    (@unless [$i:tt] [backlink_rows $($r:ident)*] backlink_rows) => {};
1985    (@unless [$i:tt] [link_rows_by $($r:ident)*] link_rows_by) => {};
1986    (@unless [$i:tt] [backlink_rows_by $($r:ident)*] backlink_rows_by) => {};
1987    (@unless [$i:tt] [prefetch_links_by $($r:ident)*] prefetch_links_by) => {};
1988    // A wrapper that defines its own links defines what a step by
1989    // one label takes too: the narrowed methods are not forwarded
1990    // past it, and the trait's defaults read the wrapper's own.
1991    (@unless [$i:tt] [links $($r:ident)*] link_rows_by) => {};
1992    (@unless [$i:tt] [link_rows $($r:ident)*] link_rows_by) => {};
1993    (@unless [$i:tt] [backlinks $($r:ident)*] backlink_rows_by) => {};
1994    (@unless [$i:tt] [backlink_rows $($r:ident)*] backlink_rows_by) => {};
1995    (@unless [$i:tt] [prefetch_links $($r:ident)*] prefetch_links_by) => {};
1996    (@unless [$i:tt] [backlinks_unsupported $($r:ident)*] backlinks_unsupported) => {};
1997    (@unless [$i:tt] [link_consumed $($r:ident)*] link_consumed) => {};
1998    (@unless [$i:tt] [resolve $($r:ident)*] resolve) => {};
1999    (@unless [$i:tt] [external_ref $($r:ident)*] external_ref) => {};
2000    (@unless [$i:tt] [resolve_fragment $($r:ident)*] resolve_fragment) => {};
2001    (@unless [$i:tt] [ref_property $($r:ident)*] ref_property) => {};
2002    (@unless [$i:tt] [ref_label $($r:ident)*] ref_label) => {};
2003    (@unless [$i:tt] [link_property $($r:ident)*] link_property) => {};
2004    (@unless [$i:tt] [document_by_ref $($r:ident)*] document_by_ref) => {};
2005    (@unless [$i:tt] [reverse_resolve $($r:ident)*] reverse_resolve) => {};
2006    (@unless [$i:tt] [descendants_named $($r:ident)*] descendants_named) => {};
2007    (@unless [$i:tt] [descendants_where $($r:ident)*] descendants_where) => {};
2008    (@unless [$i:tt] [select $($r:ident)*] select) => {};
2009    (@unless [$i:tt] [select_plan $($r:ident)*] select_plan) => {};
2010    (@unless [$i:tt] [estimate $($r:ident)*] estimate) => {};
2011    (@unless [$i:tt] [count $($r:ident)*] count) => {};
2012    (@unless [$i:tt] [row_columns $($r:ident)*] row_columns) => {};
2013    (@unless [$i:tt] [surface $($r:ident)*] surface) => {};
2014    (@unless [$i:tt] [intrinsic $($r:ident)*] intrinsic) => {};
2015    (@unless [$i:tt] [row_text $($r:ident)*] row_text) => {};
2016    (@unless [$i:tt] [prefetch_properties $($r:ident)*] prefetch_properties) => {};
2017    (@unless [$i:tt] [prefetch_links $($r:ident)*] prefetch_links) => {};
2018    (@unless [$i:tt] [whole_listings $($r:ident)*] whole_listings) => {};
2019    (@unless [$i:tt] [refresh $($r:ident)*] refresh) => {};
2020    (@unless [$i:tt] [quantifier_bound $($r:ident)*] quantifier_bound) => {};
2021    (@unless [$i:tt] [frontier_bound $($r:ident)*] frontier_bound) => {};
2022    (@unless [$i:tt] [link_property_names $($r:ident)*] link_property_names) => {};
2023    (@unless [$i:tt] [edge_weights $($r:ident)*] edge_weights) => {};
2024    (@unless [$i:tt] [acyclic_link $($r:ident)*] acyclic_link) => {};
2025    (@unless [$i:tt] [provenance $($r:ident)*] provenance) => {};
2026    (@unless [$i:tt] [has_node $($r:ident)*] has_node) => {};
2027    (@unless [$i:tt] [provenance_list $($r:ident)*] provenance_list) => {};
2028    (@unless [$i:tt] [unit_scale $($r:ident)*] unit_scale) => {};
2029    (@unless [$i:tt] [unit_names $($r:ident)*] unit_names) => {};
2030    (@unless [$i:tt] [declared_notation $($r:ident)*] declared_notation) => {};
2031    (@unless [$i:tt] [graft_text $($r:ident)*] graft_text) => {};
2032    (@unless [$i:tt] [grafts_on_demand $($r:ident)*] grafts_on_demand) => {};
2033    (@unless [$i:tt] [form_of $($r:ident)*] form_of) => {};
2034    // Another method heads the list: look further down.
2035    (@unless [$i:tt] [$x:ident $($r:ident)*] $m:ident) => {
2036        $crate::forward_ast_adapter!(@unless [$i] [$($r)*] $m);
2037    };
2038    // Not excepted: forward.
2039    (@unless [$i:tt] [] $m:ident) => {
2040        $crate::forward_ast_adapter!(@fwd [$i] $m);
2041    };
2042
2043    // The wrapped adapter, as an expression on `self`.
2044    (@target $s:ident *) => { (**$s) };
2045    (@target $s:ident $f:tt) => { $s.$f };
2046
2047    (@fwd [$i:tt] root) => {
2048        fn root(&self) -> $crate::NodeId {
2049            $crate::forward_ast_adapter!(@target self $i).root()
2050        }
2051    };
2052    (@fwd [$i:tt] children) => {
2053        fn children(&self, node: $crate::NodeId) -> Vec<$crate::NodeId> {
2054            $crate::forward_ast_adapter!(@target self $i).children(node)
2055        }
2056    };
2057    (@fwd [$i:tt] name) => {
2058        fn name(&self, node: $crate::NodeId) -> Option<String> {
2059            $crate::forward_ast_adapter!(@target self $i).name(node)
2060        }
2061    };
2062    (@fwd [$i:tt] parent) => {
2063        fn parent(&self, node: $crate::NodeId) -> Option<$crate::NodeId> {
2064            $crate::forward_ast_adapter!(@target self $i).parent(node)
2065        }
2066    };
2067    (@fwd [$i:tt] traits) => {
2068        fn traits(&self, node: $crate::NodeId) -> Vec<String> {
2069            $crate::forward_ast_adapter!(@target self $i).traits(node)
2070        }
2071    };
2072    (@fwd [$i:tt] property) => {
2073        fn property(&self, node: $crate::NodeId, name: &str) -> Option<$crate::Value> {
2074            $crate::forward_ast_adapter!(@target self $i).property(node, name)
2075        }
2076    };
2077    (@fwd [$i:tt] properties) => {
2078        fn properties(&self, node: $crate::NodeId) -> Vec<(String, $crate::Value)> {
2079            $crate::forward_ast_adapter!(@target self $i).properties(node)
2080        }
2081    };
2082    (@fwd [$i:tt] walks_for_references) => {
2083        fn walks_for_references(&self) -> bool {
2084            $crate::forward_ast_adapter!(@target self $i).walks_for_references()
2085        }
2086    };
2087    (@fwd [$i:tt] can_refer_to) => {
2088        fn can_refer_to(&self, source: $crate::NodeId, target: $crate::NodeId) -> Option<bool> {
2089            $crate::forward_ast_adapter!(@target self $i).can_refer_to(source, target)
2090        }
2091    };
2092    (@fwd [$i:tt] reference_properties) => {
2093        fn reference_properties(
2094            &self,
2095            source: $crate::NodeId,
2096            target: $crate::NodeId,
2097        ) -> Vec<String> {
2098            $crate::forward_ast_adapter!(@target self $i).reference_properties(source, target)
2099        }
2100    };
2101    (@fwd [$i:tt] resolve_needs_label) => {
2102        fn resolve_needs_label(&self, node: $crate::NodeId, property: &str) -> bool {
2103            $crate::forward_ast_adapter!(@target self $i).resolve_needs_label(node, property)
2104        }
2105    };
2106    (@fwd [$i:tt] reverse_label) => {
2107        fn reverse_label(&self, target: $crate::NodeId) -> Option<String> {
2108            $crate::forward_ast_adapter!(@target self $i).reverse_label(target)
2109        }
2110    };
2111    (@fwd [$i:tt] tree_identities) => {
2112        fn tree_identities(&self) -> Vec<(String, $crate::NodeId)> {
2113            $crate::forward_ast_adapter!(@target self $i).tree_identities()
2114        }
2115    };
2116    (@fwd [$i:tt] property_names) => {
2117        fn property_names(&self, node: $crate::NodeId) -> Vec<String> {
2118            $crate::forward_ast_adapter!(@target self $i).property_names(node)
2119        }
2120    };
2121    (@fwd [$i:tt] resolves_references) => {
2122        fn resolves_references(&self) -> bool {
2123            $crate::forward_ast_adapter!(@target self $i).resolves_references()
2124        }
2125    };
2126    (@fwd [$i:tt] index_lookup) => {
2127        fn index_lookup(
2128            &self,
2129            scope: &str,
2130            property: &str,
2131            value: &$crate::Value,
2132        ) -> Option<Vec<$crate::NodeId>> {
2133            $crate::forward_ast_adapter!(@target self $i).index_lookup(scope, property, value)
2134        }
2135    };
2136    (@fwd [$i:tt] index_referrers) => {
2137        fn index_referrers(
2138            &self,
2139            scope: &str,
2140            property: &str,
2141            label: Option<&str>,
2142            target: $crate::NodeId,
2143        ) -> Option<Vec<$crate::NodeId>> {
2144            $crate::forward_ast_adapter!(@target self $i)
2145                .index_referrers(scope, property, label, target)
2146        }
2147    };
2148    (@fwd [$i:tt] non_tree_nodes) => {
2149        fn non_tree_nodes(&self) -> Vec<$crate::NodeId> {
2150            $crate::forward_ast_adapter!(@target self $i).non_tree_nodes()
2151        }
2152    };
2153    (@fwd [$i:tt] child_host) => {
2154        fn child_host(&self, node: $crate::NodeId) -> $crate::NodeId {
2155            $crate::forward_ast_adapter!(@target self $i).child_host(node)
2156        }
2157    };
2158    (@fwd [$i:tt] children_named) => {
2159        fn children_named(&self, node: $crate::NodeId, name: &str) -> Vec<$crate::NodeId> {
2160            $crate::forward_ast_adapter!(@target self $i).children_named(node, name)
2161        }
2162    };
2163    (@fwd [$i:tt] answers_to) => {
2164        fn answers_to(&self, node: $crate::NodeId, name: &str) -> bool {
2165            $crate::forward_ast_adapter!(@target self $i).answers_to(node, name)
2166        }
2167    };
2168    (@fwd [$i:tt] has_trait) => {
2169        fn has_trait(&self, node: $crate::NodeId, name: &str) -> bool {
2170            $crate::forward_ast_adapter!(@target self $i).has_trait(node, name)
2171        }
2172    };
2173    (@fwd [$i:tt] default_value) => {
2174        fn default_value(&self, node: $crate::NodeId) -> Option<$crate::Value> {
2175            $crate::forward_ast_adapter!(@target self $i).default_value(node)
2176        }
2177    };
2178    (@fwd [$i:tt] metadata) => {
2179        fn metadata(&self, node: $crate::NodeId, key: &str) -> Option<$crate::Value> {
2180            $crate::forward_ast_adapter!(@target self $i).metadata(node, key)
2181        }
2182    };
2183    (@fwd [$i:tt] metadata_keys) => {
2184        fn metadata_keys(&self, node: $crate::NodeId) -> Vec<String> {
2185            $crate::forward_ast_adapter!(@target self $i).metadata_keys(node)
2186        }
2187    };
2188    (@fwd [$i:tt] metadata_catalogue) => {
2189        fn metadata_catalogue(&self) -> &'static [&'static str] {
2190            $crate::forward_ast_adapter!(@target self $i).metadata_catalogue()
2191        }
2192    };
2193    (@fwd [$i:tt] aliased_metadata) => {
2194        fn aliased_metadata(&self, node: $crate::NodeId) -> &'static [&'static str] {
2195            $crate::forward_ast_adapter!(@target self $i).aliased_metadata(node)
2196        }
2197    };
2198    (@fwd [$i:tt] links) => {
2199        fn links(&self, node: $crate::NodeId) -> Vec<(String, $crate::NodeId)> {
2200            $crate::forward_ast_adapter!(@target self $i).links(node)
2201        }
2202    };
2203    (@fwd [$i:tt] backlinks) => {
2204        fn backlinks(&self, node: $crate::NodeId) -> Vec<(String, $crate::NodeId)> {
2205            $crate::forward_ast_adapter!(@target self $i).backlinks(node)
2206        }
2207    };
2208    (@fwd [$i:tt] link_rows) => {
2209        fn link_rows(&self, node: $crate::NodeId) -> Vec<(String, $crate::NodeId, Option<$crate::NodeId>)> {
2210            $crate::forward_ast_adapter!(@target self $i).link_rows(node)
2211        }
2212    };
2213    (@fwd [$i:tt] edge_rows) => {
2214        fn edge_rows(&self, node: $crate::NodeId) -> Vec<(String, $crate::NodeId, Option<$crate::NodeId>)> {
2215            $crate::forward_ast_adapter!(@target self $i).edge_rows(node)
2216        }
2217    };
2218    (@fwd [$i:tt] graph_bound) => {
2219        fn graph_bound(&self) -> usize {
2220            $crate::forward_ast_adapter!(@target self $i).graph_bound()
2221        }
2222    };
2223    (@fwd [$i:tt] may_hold_below) => {
2224        fn may_hold_below(&self, node: $crate::NodeId, name: Option<&str>, traits: &[&str]) -> bool {
2225            $crate::forward_ast_adapter!(@target self $i).may_hold_below(node, name, traits)
2226        }
2227    };
2228    (@fwd [$i:tt] property_withheld) => {
2229        fn property_withheld(&self, node: $crate::NodeId, name: &str) -> bool {
2230            $crate::forward_ast_adapter!(@target self $i).property_withheld(node, name)
2231        }
2232    };
2233    (@fwd [$i:tt] withheld_properties) => {
2234        fn withheld_properties(&self) -> Vec<String> {
2235            $crate::forward_ast_adapter!(@target self $i).withheld_properties()
2236        }
2237    };
2238    (@fwd [$i:tt] nodes_withheld) => {
2239        fn nodes_withheld(&self) -> bool {
2240            $crate::forward_ast_adapter!(@target self $i).nodes_withheld()
2241        }
2242    };
2243    (@fwd [$i:tt] graph_declarations) => {
2244        fn graph_declarations(&self) -> Vec<$crate::GraphDeclaration> {
2245            $crate::forward_ast_adapter!(@target self $i).graph_declarations()
2246        }
2247    };
2248    (@fwd [$i:tt] graph_measure) => {
2249        fn graph_measure(&self, scope: &str, hop: &str, measure: &str, nodes: &[$crate::NodeId]) -> Option<Vec<$crate::Value>> {
2250            $crate::forward_ast_adapter!(@target self $i).graph_measure(scope, hop, measure, nodes)
2251        }
2252    };
2253    (@fwd [$i:tt] store_graph_measure) => {
2254        fn store_graph_measure(&self, scope: &str, hop: &str, measure: &str, nodes: &[$crate::NodeId], values: &[$crate::Value]) {
2255            $crate::forward_ast_adapter!(@target self $i).store_graph_measure(scope, hop, measure, nodes, values)
2256        }
2257    };
2258    (@fwd [$i:tt] backlink_rows) => {
2259        fn backlink_rows(&self, node: $crate::NodeId) -> Vec<(String, $crate::NodeId, Option<$crate::NodeId>)> {
2260            $crate::forward_ast_adapter!(@target self $i).backlink_rows(node)
2261        }
2262    };
2263    (@fwd [$i:tt] backlinks_unsupported) => {
2264        fn backlinks_unsupported(&self, node: $crate::NodeId, label: Option<&str>) -> bool {
2265            $crate::forward_ast_adapter!(@target self $i).backlinks_unsupported(node, label)
2266        }
2267    };
2268    (@fwd [$i:tt] link_consumed) => {
2269        fn link_consumed(&self, source: $crate::NodeId, label: &str) -> bool {
2270            $crate::forward_ast_adapter!(@target self $i).link_consumed(source, label)
2271        }
2272    };
2273    (@fwd [$i:tt] resolve) => {
2274        fn resolve(
2275            &self,
2276            node: $crate::NodeId,
2277            property: &str,
2278            hint: Option<&str>,
2279        ) -> Option<$crate::NodeId> {
2280            $crate::forward_ast_adapter!(@target self $i).resolve(node, property, hint)
2281        }
2282    };
2283    (@fwd [$i:tt] external_ref) => {
2284        fn external_ref(
2285            &self,
2286            node: $crate::NodeId,
2287            property: &str,
2288            hint: Option<&str>,
2289        ) -> Option<$crate::ExternalRef> {
2290            $crate::forward_ast_adapter!(@target self $i).external_ref(node, property, hint)
2291        }
2292    };
2293    (@fwd [$i:tt] resolve_fragment) => {
2294        fn resolve_fragment(&self, node: $crate::NodeId, fragment: &str) -> Option<$crate::NodeId> {
2295            $crate::forward_ast_adapter!(@target self $i).resolve_fragment(node, fragment)
2296        }
2297    };
2298    (@fwd [$i:tt] ref_property) => {
2299        fn ref_property(&self, node: $crate::NodeId) -> Option<String> {
2300            $crate::forward_ast_adapter!(@target self $i).ref_property(node)
2301        }
2302    };
2303    (@fwd [$i:tt] ref_label) => {
2304        fn ref_label(&self, node: $crate::NodeId, property: &str) -> Option<String> {
2305            $crate::forward_ast_adapter!(@target self $i).ref_label(node, property)
2306        }
2307    };
2308    (@fwd [$i:tt] link_property) => {
2309        fn link_property(
2310            &self,
2311            source: $crate::NodeId,
2312            label: &str,
2313            target: $crate::NodeId,
2314            name: &str,
2315        ) -> Option<$crate::Value> {
2316            $crate::forward_ast_adapter!(@target self $i).link_property(source, label, target, name)
2317        }
2318    };
2319    (@fwd [$i:tt] document_by_ref) => {
2320        fn document_by_ref(&self, id: &str) -> Option<$crate::NodeId> {
2321            $crate::forward_ast_adapter!(@target self $i).document_by_ref(id)
2322        }
2323    };
2324    (@fwd [$i:tt] reverse_resolve) => {
2325        fn reverse_resolve(
2326            &self,
2327            node: $crate::NodeId,
2328            property: Option<&str>,
2329            hint: Option<&str>,
2330        ) -> Option<Vec<$crate::NodeId>> {
2331            $crate::forward_ast_adapter!(@target self $i).reverse_resolve(node, property, hint)
2332        }
2333    };
2334    (@fwd [$i:tt] descendants_named) => {
2335        fn descendants_named(
2336            &self,
2337            node: $crate::NodeId,
2338            name: &str,
2339        ) -> Option<Vec<($crate::NodeId, usize)>> {
2340            $crate::forward_ast_adapter!(@target self $i).descendants_named(node, name)
2341        }
2342    };
2343    (@fwd [$i:tt] descendants_where) => {
2344        fn descendants_where(
2345            &self,
2346            node: $crate::NodeId,
2347            name: &str,
2348            property: &str,
2349            value: &$crate::Value,
2350        ) -> Option<Vec<($crate::NodeId, usize)>> {
2351            $crate::forward_ast_adapter!(@target self $i)
2352                .descendants_where(node, name, property, value)
2353        }
2354    };
2355    (@fwd [$i:tt] select) => {
2356        fn select(
2357            &self,
2358            from: $crate::NodeId,
2359            plan: &$crate::adapter::StepPlan<'_>,
2360        ) -> Option<$crate::adapter::Selection> {
2361            $crate::forward_ast_adapter!(@target self $i).select(from, plan)
2362        }
2363    };
2364    (@fwd [$i:tt] select_plan) => {
2365        fn select_plan(
2366            &self,
2367            scope: &[&str],
2368            plan: &$crate::adapter::StepPlan<'_>,
2369        ) -> Option<Vec<bool>> {
2370            $crate::forward_ast_adapter!(@target self $i).select_plan(scope, plan)
2371        }
2372    };
2373    (@fwd [$i:tt] estimate) => {
2374        fn estimate(
2375            &self,
2376            scope: &[&str],
2377            plan: &$crate::adapter::StepPlan<'_>,
2378        ) -> Option<$crate::adapter::Estimate> {
2379            $crate::forward_ast_adapter!(@target self $i).estimate(scope, plan)
2380        }
2381    };
2382    (@fwd [$i:tt] count) => {
2383        fn count(&self, from: $crate::NodeId, plan: &$crate::adapter::StepPlan<'_>) -> Option<usize> {
2384            $crate::forward_ast_adapter!(@target self $i).count(from, plan)
2385        }
2386    };
2387    (@fwd [$i:tt] row_columns) => {
2388        fn row_columns(&self, node: $crate::NodeId) -> Option<Vec<String>> {
2389            $crate::forward_ast_adapter!(@target self $i).row_columns(node)
2390        }
2391    };
2392    (@fwd [$i:tt] surface) => {
2393        fn surface(&self, node: $crate::NodeId) -> Option<$crate::Surface> {
2394            $crate::forward_ast_adapter!(@target self $i).surface(node)
2395        }
2396    };
2397    (@fwd [$i:tt] intrinsic) => {
2398        fn intrinsic(&self, node: $crate::NodeId) -> $crate::NodeId {
2399            $crate::forward_ast_adapter!(@target self $i).intrinsic(node)
2400        }
2401    };
2402    (@fwd [$i:tt] row_text) => {
2403        fn row_text(&self, node: $crate::NodeId, f: &mut dyn FnMut(&[&str])) -> bool {
2404            $crate::forward_ast_adapter!(@target self $i).row_text(node, f)
2405        }
2406    };
2407    (@fwd [$i:tt] prefetch_properties) => {
2408        fn prefetch_properties(&self, nodes: &[$crate::NodeId], names: &[&str]) {
2409            $crate::forward_ast_adapter!(@target self $i).prefetch_properties(nodes, names)
2410        }
2411    };
2412    (@fwd [$i:tt] prefetch_links) => {
2413        fn prefetch_links(&self, nodes: &[$crate::NodeId], dir: $crate::LinkDir) {
2414            $crate::forward_ast_adapter!(@target self $i).prefetch_links(nodes, dir)
2415        }
2416    };
2417    (@fwd [$i:tt] prefetch_links_by) => {
2418        fn prefetch_links_by(
2419            &self,
2420            nodes: &[$crate::NodeId],
2421            dir: $crate::LinkDir,
2422            by: $crate::LinkBy<'_>,
2423        ) {
2424            $crate::forward_ast_adapter!(@target self $i).prefetch_links_by(nodes, dir, by)
2425        }
2426    };
2427    (@fwd [$i:tt] link_rows_by) => {
2428        fn link_rows_by(
2429            &self,
2430            node: $crate::NodeId,
2431            label: &str,
2432        ) -> Vec<(String, $crate::NodeId, Option<$crate::NodeId>)> {
2433            $crate::forward_ast_adapter!(@target self $i).link_rows_by(node, label)
2434        }
2435    };
2436    (@fwd [$i:tt] backlink_rows_by) => {
2437        fn backlink_rows_by(
2438            &self,
2439            node: $crate::NodeId,
2440            label: &str,
2441        ) -> Vec<(String, $crate::NodeId, Option<$crate::NodeId>)> {
2442            $crate::forward_ast_adapter!(@target self $i).backlink_rows_by(node, label)
2443        }
2444    };
2445    (@fwd [$i:tt] whole_listings) => {
2446        fn whole_listings(&self) {
2447            $crate::forward_ast_adapter!(@target self $i).whole_listings()
2448        }
2449    };
2450    (@fwd [$i:tt] refresh) => {
2451        fn refresh(&self) {
2452            $crate::forward_ast_adapter!(@target self $i).refresh()
2453        }
2454    };
2455    (@fwd [$i:tt] quantifier_bound) => {
2456        fn quantifier_bound(&self) -> usize {
2457            $crate::forward_ast_adapter!(@target self $i).quantifier_bound()
2458        }
2459    };
2460    (@fwd [$i:tt] frontier_bound) => {
2461        fn frontier_bound(&self) -> usize {
2462            $crate::forward_ast_adapter!(@target self $i).frontier_bound()
2463        }
2464    };
2465    (@fwd [$i:tt] link_property_names) => {
2466        fn link_property_names(
2467            &self,
2468            source: $crate::NodeId,
2469            label: &str,
2470            target: $crate::NodeId,
2471        ) -> Vec<String> {
2472            $crate::forward_ast_adapter!(@target self $i).link_property_names(source, label, target)
2473        }
2474    };
2475    (@fwd [$i:tt] edge_weights) => {
2476        fn edge_weights(
2477            &self,
2478            source: $crate::NodeId,
2479            label: &str,
2480            target: $crate::NodeId,
2481            row: Option<$crate::NodeId>,
2482            forward: bool,
2483        ) -> Vec<$crate::Value> {
2484            $crate::forward_ast_adapter!(@target self $i).edge_weights(source, label, target, row, forward)
2485        }
2486    };
2487    (@fwd [$i:tt] acyclic_link) => {
2488        fn acyclic_link(&self, label: &str) -> Option<String> {
2489            $crate::forward_ast_adapter!(@target self $i).acyclic_link(label)
2490        }
2491    };
2492    (@fwd [$i:tt] provenance) => {
2493        fn provenance(&self, node: $crate::NodeId) -> $crate::Provenance {
2494            $crate::forward_ast_adapter!(@target self $i).provenance(node)
2495        }
2496    };
2497    (@fwd [$i:tt] has_node) => {
2498        fn has_node(&self, node: $crate::NodeId) -> bool {
2499            $crate::forward_ast_adapter!(@target self $i).has_node(node)
2500        }
2501    };
2502    (@fwd [$i:tt] provenance_list) => {
2503        fn provenance_list(&self, node: $crate::NodeId) -> $crate::ProvenanceList {
2504            $crate::forward_ast_adapter!(@target self $i).provenance_list(node)
2505        }
2506    };
2507    (@fwd [$i:tt] declared_notation) => {
2508        fn declared_notation(&self, node: $crate::NodeId) -> Option<String> {
2509            $crate::forward_ast_adapter!(@target self $i).declared_notation(node)
2510        }
2511    };
2512    (@fwd [$i:tt] graft_text) => {
2513        fn graft_text(
2514            &self,
2515            text: &str,
2516            notation: Option<&str>,
2517        ) -> Option<Result<$crate::NodeId, String>> {
2518            $crate::forward_ast_adapter!(@target self $i).graft_text(text, notation)
2519        }
2520    };
2521    (@fwd [$i:tt] grafts_on_demand) => {
2522        fn grafts_on_demand(&self) -> bool {
2523            $crate::forward_ast_adapter!(@target self $i).grafts_on_demand()
2524        }
2525    };
2526    (@fwd [$i:tt] form_of) => {
2527        fn form_of(&self, node: NodeId) -> Option<$crate::Form> {
2528            $crate::forward_ast_adapter!(@target self $i).form_of(node)
2529        }
2530    };
2531    (@fwd [$i:tt] unit_scale) => {
2532        fn unit_scale(&self, expr: &str) -> Option<(f64, String)> {
2533            $crate::forward_ast_adapter!(@target self $i).unit_scale(expr)
2534        }
2535    };
2536    (@fwd [$i:tt] unit_names) => {
2537        fn unit_names(&self) -> Vec<String> {
2538            $crate::forward_ast_adapter!(@target self $i).unit_names()
2539        }
2540    };
2541}
2542
2543impl AstAdapter for Box<dyn AstAdapter> {
2544    crate::forward_ast_adapter!(*);
2545}
2546
2547/// The label a reference declared by `property` gives its edge:
2548/// the property's name without a trailing `_id` or camel-case `Id`
2549/// (`manager_id` → `manager`, `authorId` → `author`; spec: A table
2550/// with foreign keys). A name that is only the suffix (`id`, `_id`)
2551/// or ends otherwise labels the edge as written.
2552pub fn reference_label(property: &str) -> &str {
2553    for suffix in ["_id", "Id"] {
2554        if let Some(stem) = property.strip_suffix(suffix)
2555            && !stem.is_empty()
2556        {
2557            return stem;
2558        }
2559    }
2560    property
2561}
2562
2563/// The labels of one scope's declared references, in declaration
2564/// order: where two would share a name, the later keeps its full
2565/// property name.
2566pub fn reference_labels<'a>(properties: impl IntoIterator<Item = &'a str>) -> Vec<String> {
2567    let mut out: Vec<String> = Vec::new();
2568    for p in properties {
2569        let label = reference_label(p);
2570        if out.iter().any(|o| o == label) {
2571            out.push(p.to_string());
2572        } else {
2573            out.push(label.to_string());
2574        }
2575    }
2576    out
2577}
2578
2579#[cfg(test)]
2580mod forwarding {
2581    use super::*;
2582
2583    /// The names of the `fn` items at `indent` within `block`.
2584    fn fn_names(block: &str, indent: &str) -> Vec<String> {
2585        block
2586            .lines()
2587            .filter_map(|l| l.strip_prefix(indent)?.strip_prefix("fn "))
2588            .map(|rest| {
2589                rest.split(|c: char| !(c.is_alphanumeric() || c == '_'))
2590                    .next()
2591                    .unwrap()
2592                    .to_string()
2593            })
2594            .collect()
2595    }
2596
2597    /// The macro's method table is the trait's method list — a
2598    /// method added to `AstAdapter` without a forwarding arm would
2599    /// otherwise answer with the trait default inside every wrapper.
2600    #[test]
2601    fn the_macro_lists_every_trait_method() {
2602        let src = include_str!("adapter.rs");
2603        let trait_src = &src[src.find("pub trait AstAdapter {").unwrap()..];
2604        let trait_src = &trait_src[..trait_src.find("\n}\n").unwrap()];
2605        let in_trait = fn_names(trait_src, "    ");
2606
2607        let table = &src[src
2608            .find("coverage test reads this list from the source.")
2609            .unwrap()..];
2610        let table = &table[table.find('\n').unwrap()..table.find(");").unwrap()];
2611        let listed: Vec<String> = table.split_whitespace().map(str::to_string).collect();
2612
2613        assert_eq!(
2614            listed, in_trait,
2615            "the forwarding table drifted from the trait"
2616        );
2617
2618        let macro_src = &src[src.find("macro_rules! forward_ast_adapter").unwrap()..];
2619        let macro_src = &macro_src[..macro_src.find("\n}\n").unwrap()];
2620        for m in &in_trait {
2621            assert!(
2622                macro_src.contains(&format!(
2623                    "(@unless [$i:tt] [{m} $($r:ident)*] {m}) => {{}};"
2624                )),
2625                "no except arm for {m}"
2626            );
2627            assert!(
2628                macro_src.contains(&format!("(@fwd [$i:tt] {m}) => {{")),
2629                "no forwarding arm for {m}"
2630            );
2631        }
2632    }
2633
2634    /// Answers every method distinctively, so a wrapper that
2635    /// forwards one method to another (or to the default) is caught.
2636    struct Probe;
2637
2638    fn n(k: u64) -> NodeId {
2639        NodeId(k)
2640    }
2641
2642    fn int(v: &Value) -> u64 {
2643        match v {
2644            Value::Int(i) => *i as u64,
2645            _ => 0,
2646        }
2647    }
2648
2649    impl AstAdapter for Probe {
2650        fn root(&self) -> NodeId {
2651            n(1)
2652        }
2653        fn children(&self, node: NodeId) -> Vec<NodeId> {
2654            vec![n(node.0 * 10)]
2655        }
2656        fn name(&self, node: NodeId) -> Option<String> {
2657            Some(format!("name{}", node.0))
2658        }
2659        fn parent(&self, node: NodeId) -> Option<NodeId> {
2660            Some(n(node.0 + 100))
2661        }
2662        fn traits(&self, node: NodeId) -> Vec<String> {
2663            vec![format!("trait{}", node.0)]
2664        }
2665        fn property(&self, node: NodeId, name: &str) -> Option<Value> {
2666            Some(Value::Str(format!("prop:{}:{name}", node.0)))
2667        }
2668        fn properties(&self, node: NodeId) -> Vec<(String, Value)> {
2669            vec![(format!("p{}", node.0), Value::Int(node.0 as i64))]
2670        }
2671        fn walks_for_references(&self) -> bool {
2672            true
2673        }
2674        fn can_refer_to(&self, source: NodeId, target: NodeId) -> Option<bool> {
2675            Some(source.0 < target.0)
2676        }
2677        fn reference_properties(&self, source: NodeId, target: NodeId) -> Vec<String> {
2678            vec![format!("rp{}-{}", source.0, target.0)]
2679        }
2680        fn resolve_needs_label(&self, node: NodeId, property: &str) -> bool {
2681            node.0 == 7 && property == "x"
2682        }
2683        fn reverse_label(&self, target: NodeId) -> Option<String> {
2684            Some(format!("rl{}", target.0))
2685        }
2686        fn tree_identities(&self) -> Vec<(String, NodeId)> {
2687            vec![("tree".into(), n(42))]
2688        }
2689        fn property_names(&self, node: NodeId) -> Vec<String> {
2690            vec![format!("pn{}", node.0)]
2691        }
2692        fn resolves_references(&self) -> bool {
2693            false
2694        }
2695        fn index_lookup(&self, scope: &str, property: &str, value: &Value) -> Option<Vec<NodeId>> {
2696            Some(vec![
2697                n((scope.len() + property.len()) as u64),
2698                n(int(value)),
2699            ])
2700        }
2701        fn index_referrers(
2702            &self,
2703            scope: &str,
2704            property: &str,
2705            label: Option<&str>,
2706            target: NodeId,
2707        ) -> Option<Vec<NodeId>> {
2708            Some(vec![n(
2709                (scope.len() + property.len() + label.map_or(0, str::len)) as u64 + target.0,
2710            )])
2711        }
2712        fn non_tree_nodes(&self) -> Vec<NodeId> {
2713            vec![n(99)]
2714        }
2715        fn child_host(&self, node: NodeId) -> NodeId {
2716            n(node.0 + 1000)
2717        }
2718        fn children_named(&self, node: NodeId, name: &str) -> Vec<NodeId> {
2719            vec![n(node.0 + name.len() as u64)]
2720        }
2721        fn answers_to(&self, node: NodeId, name: &str) -> bool {
2722            node.0 == 3 && name == "alias"
2723        }
2724        fn has_trait(&self, node: NodeId, name: &str) -> bool {
2725            node.0 == 4 && name == "talias"
2726        }
2727        fn default_value(&self, node: NodeId) -> Option<Value> {
2728            Some(Value::Int(-(node.0 as i64)))
2729        }
2730        fn metadata(&self, node: NodeId, key: &str) -> Option<Value> {
2731            Some(Value::Str(format!("meta:{}:{key}", node.0)))
2732        }
2733        fn metadata_keys(&self, node: NodeId) -> Vec<String> {
2734            vec![format!("k{}", node.0)]
2735        }
2736        fn metadata_catalogue(&self) -> &'static [&'static str] {
2737            &["k"]
2738        }
2739        fn aliased_metadata(&self, node: NodeId) -> &'static [&'static str] {
2740            if node.0 == 5 { &["size"] } else { &["other"] }
2741        }
2742        fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
2743            vec![("link".into(), n(node.0 + 2))]
2744        }
2745        fn backlinks(&self, node: NodeId) -> Vec<(String, NodeId)> {
2746            vec![("back".into(), n(node.0 + 3))]
2747        }
2748        fn backlinks_unsupported(&self, node: NodeId, label: Option<&str>) -> bool {
2749            node.0 == 2 && label == Some("lbl")
2750        }
2751        fn resolve(&self, node: NodeId, property: &str, hint: Option<&str>) -> Option<NodeId> {
2752            Some(n(node.0
2753                + property.len() as u64
2754                + hint.map_or(0, |h| h.len() as u64)))
2755        }
2756        fn external_ref(
2757            &self,
2758            node: NodeId,
2759            property: &str,
2760            hint: Option<&str>,
2761        ) -> Option<ExternalRef> {
2762            Some(ExternalRef {
2763                document: format!("doc{}:{property}", node.0),
2764                within: hint.map(str::to_string),
2765            })
2766        }
2767        fn resolve_fragment(&self, node: NodeId, fragment: &str) -> Option<NodeId> {
2768            Some(n(node.0 + fragment.len() as u64 + 7))
2769        }
2770        fn ref_property(&self, node: NodeId) -> Option<String> {
2771            Some(format!("href{}", node.0))
2772        }
2773        fn ref_label(&self, node: NodeId, property: &str) -> Option<String> {
2774            Some(format!("rel{}:{property}", node.0))
2775        }
2776        fn link_property(
2777            &self,
2778            source: NodeId,
2779            label: &str,
2780            target: NodeId,
2781            name: &str,
2782        ) -> Option<Value> {
2783            Some(Value::Str(format!(
2784                "{}-{label}-{}-{name}",
2785                source.0, target.0
2786            )))
2787        }
2788        fn document_by_ref(&self, id: &str) -> Option<NodeId> {
2789            Some(n(id.len() as u64 + 50))
2790        }
2791        fn reverse_resolve(
2792            &self,
2793            node: NodeId,
2794            property: Option<&str>,
2795            hint: Option<&str>,
2796        ) -> Option<Vec<NodeId>> {
2797            Some(vec![n(node.0
2798                + property.map_or(0, |p| p.len() as u64) * 2
2799                + hint.map_or(0, |h| h.len() as u64) * 3)])
2800        }
2801        fn descendants_named(&self, node: NodeId, name: &str) -> Option<Vec<(NodeId, usize)>> {
2802            Some(vec![(n(node.0 + 9), name.len())])
2803        }
2804        fn descendants_where(
2805            &self,
2806            node: NodeId,
2807            name: &str,
2808            property: &str,
2809            value: &Value,
2810        ) -> Option<Vec<(NodeId, usize)>> {
2811            Some(vec![(n(node.0 + int(value)), name.len() + property.len())])
2812        }
2813        fn select(&self, from: NodeId, plan: &StepPlan<'_>) -> Option<Selection> {
2814            Some(Selection {
2815                nodes: vec![(n(from.0 + plan.conjuncts.len() as u64 + 1), 3)],
2816                applied: vec![true; plan.conjuncts.len()],
2817            })
2818        }
2819        fn select_plan(&self, scope: &[&str], plan: &StepPlan<'_>) -> Option<Vec<bool>> {
2820            Some(vec![scope.len() == 1; plan.conjuncts.len()])
2821        }
2822        fn estimate(&self, scope: &[&str], plan: &StepPlan<'_>) -> Option<Estimate> {
2823            Some(Estimate {
2824                nodes: (scope.len() as u64, plan.conjuncts.len() as u64 + 9),
2825                bytes: None,
2826                requests: Some(1),
2827                latency: Latency::Local,
2828                confidence: Confidence::Bound,
2829            })
2830        }
2831        fn count(&self, from: NodeId, plan: &StepPlan<'_>) -> Option<usize> {
2832            Some(from.0 as usize + plan.conjuncts.len() + 40)
2833        }
2834        fn prefetch_properties(&self, nodes: &[NodeId], names: &[&str]) {
2835            PREFETCHED.with(|p| p.set(nodes.len() * 100 + names.len()));
2836        }
2837        fn prefetch_links(&self, nodes: &[NodeId], dir: LinkDir) {
2838            PREFETCHED.with(|p| p.set(nodes.len() * 10 + matches!(dir, LinkDir::In) as usize));
2839        }
2840        fn prefetch_links_by(&self, nodes: &[NodeId], dir: LinkDir, by: LinkBy<'_>) {
2841            let named = match by {
2842                LinkBy::Label(l) => l.len(),
2843                LinkBy::Property(p) => 100 + p.len(),
2844            };
2845            PREFETCHED.with(|p| {
2846                p.set(nodes.len() * 1000 + named * 2 + matches!(dir, LinkDir::In) as usize)
2847            });
2848        }
2849        fn link_rows_by(&self, node: NodeId, label: &str) -> Vec<(String, NodeId, Option<NodeId>)> {
2850            vec![(format!("out:{label}"), n(node.0 + 31), None)]
2851        }
2852        fn backlink_rows_by(
2853            &self,
2854            node: NodeId,
2855            label: &str,
2856        ) -> Vec<(String, NodeId, Option<NodeId>)> {
2857            vec![(format!("in:{label}"), n(node.0 + 37), Some(n(3)))]
2858        }
2859        fn quantifier_bound(&self) -> usize {
2860            77
2861        }
2862        fn frontier_bound(&self) -> usize {
2863            777
2864        }
2865        fn link_property_names(&self, source: NodeId, _label: &str, target: NodeId) -> Vec<String> {
2866            vec![format!("w{}_{}", source.0, target.0)]
2867        }
2868        fn provenance(&self, node: NodeId) -> Provenance {
2869            Provenance {
2870                source: Some(format!("src{}", node.0)),
2871                ..Default::default()
2872            }
2873        }
2874        fn has_node(&self, node: NodeId) -> bool {
2875            node.0 == 8
2876        }
2877        fn provenance_list(&self, node: NodeId) -> ProvenanceList {
2878            ProvenanceList {
2879                entries: vec![self.provenance(node)],
2880                elided: node.0 as u32,
2881            }
2882        }
2883        fn unit_scale(&self, expr: &str) -> Option<(f64, String)> {
2884            Some((expr.len() as f64, format!("scale:{expr}")))
2885        }
2886        fn unit_names(&self) -> Vec<String> {
2887            vec!["probe".to_string()]
2888        }
2889    }
2890
2891    thread_local! {
2892        static PREFETCHED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2893    }
2894
2895    /// Every method of `w` answers as `Probe` does, except those in
2896    /// `except`, which the wrapper defines itself.
2897    fn assert_forwards(w: &dyn AstAdapter, except: &[&str]) {
2898        let p = Probe;
2899        let v = Value::Int(6);
2900        macro_rules! same {
2901            ($m:ident $(, $a:expr)*) => {
2902                if !except.contains(&stringify!($m)) {
2903                    assert_eq!(w.$m($($a),*), p.$m($($a),*), stringify!($m));
2904                }
2905            };
2906        }
2907        same!(root);
2908        same!(children, n(2));
2909        same!(name, n(2));
2910        same!(parent, n(2));
2911        same!(traits, n(2));
2912        same!(property, n(2), "k");
2913        same!(properties, n(2));
2914        same!(walks_for_references);
2915        same!(can_refer_to, n(2), n(3));
2916        same!(reference_properties, n(2), n(3));
2917        same!(resolve_needs_label, n(7), "x");
2918        same!(reverse_label, n(2));
2919        same!(tree_identities);
2920        same!(property_names, n(2));
2921        same!(resolves_references);
2922        same!(index_lookup, "s", "pp", &v);
2923        same!(index_referrers, "s", "pp", Some("lbl"), n(2));
2924        same!(non_tree_nodes);
2925        same!(child_host, n(2));
2926        same!(children_named, n(2), "abc");
2927        same!(answers_to, n(3), "alias");
2928        same!(has_trait, n(4), "talias");
2929        same!(default_value, n(2));
2930        same!(metadata, n(2), "key");
2931        same!(metadata_keys, n(2));
2932        same!(metadata_catalogue);
2933        same!(aliased_metadata, n(5));
2934        same!(links, n(2));
2935        same!(backlinks, n(2));
2936        same!(backlinks_unsupported, n(2), Some("lbl"));
2937        same!(backlinks_unsupported, n(2), None);
2938        same!(resolve, n(2), "pp", Some("h"));
2939        same!(external_ref, n(2), "pp", Some("frag"));
2940        same!(resolve_fragment, n(2), "frag");
2941        same!(ref_property, n(2));
2942        same!(ref_label, n(2), "pp");
2943        same!(link_property, n(2), "lbl", n(3), "nm");
2944        same!(document_by_ref, "id");
2945        same!(reverse_resolve, n(2), Some("pp"), Some("h"));
2946        same!(descendants_named, n(2), "abc");
2947        same!(descendants_where, n(2), "abc", "pp", &v);
2948        let plan = StepPlan {
2949            traits: Vec::new(),
2950            cap: Default::default(),
2951            axis: PlanAxis::Descendant,
2952            name: Some("abc"),
2953            conjuncts: vec![Conjunct::Equals("pp", &v)],
2954            limit: None,
2955            order: None,
2956        };
2957        if !except.contains(&"select") {
2958            assert_eq!(
2959                w.select(n(2), &plan).map(|s| s.nodes),
2960                p.select(n(2), &plan).map(|s| s.nodes),
2961                "select"
2962            );
2963        }
2964        same!(count, n(2), &plan);
2965        same!(select_plan, &["t"], &plan);
2966        same!(estimate, &["t"], &plan);
2967        if !except.contains(&"prefetch_properties") {
2968            PREFETCHED.with(|p| p.set(0));
2969            w.prefetch_properties(&[n(1), n(2), n(3)], &["a", "b"]);
2970            assert_eq!(PREFETCHED.with(|p| p.get()), 302, "prefetch_properties");
2971        }
2972        if !except.contains(&"prefetch_links") {
2973            PREFETCHED.with(|c| c.set(0));
2974            w.prefetch_links(&[n(1), n(2)], LinkDir::In);
2975            assert_eq!(PREFETCHED.with(|c| c.get()), 21, "prefetch_links");
2976        }
2977        if !except.contains(&"prefetch_links_by") {
2978            PREFETCHED.with(|c| c.set(0));
2979            w.prefetch_links_by(&[n(1), n(2)], LinkDir::In, LinkBy::Label("boss"));
2980            assert_eq!(
2981                PREFETCHED.with(|c| c.get()),
2982                2009,
2983                "prefetch_links_by a label"
2984            );
2985            w.prefetch_links_by(&[n(1)], LinkDir::Out, LinkBy::Property("id"));
2986            assert_eq!(
2987                PREFETCHED.with(|c| c.get()),
2988                1204,
2989                "prefetch_links_by a property"
2990            );
2991        }
2992        same!(link_rows_by, n(2), "lbl");
2993        same!(backlink_rows_by, n(2), "lbl");
2994        same!(quantifier_bound);
2995        same!(frontier_bound);
2996        same!(link_property_names, n(1), "e", n(2));
2997        same!(edge_weights, n(1), "e", n(2), None, true);
2998        same!(provenance, n(2));
2999        same!(has_node, n(8));
3000        same!(has_node, n(9));
3001        same!(provenance_list, n(2));
3002        same!(unit_scale, "km");
3003        same!(unit_names);
3004    }
3005
3006    #[test]
3007    fn every_wrapper_forwards_every_method() {
3008        let p = Probe;
3009        let b: Box<dyn AstAdapter> = Box::new(Probe);
3010        assert_forwards(&b, &[]);
3011
3012        let s = crate::graph::source::Sourced {
3013            inner: Probe,
3014            encoding: "utf-8".into(),
3015            replaced: 0,
3016        };
3017        assert_forwards(&s, &["metadata"]);
3018        assert_eq!(s.metadata(n(2), "key"), p.metadata(n(2), "key"));
3019        assert_eq!(
3020            s.metadata(n(1), "encoding"),
3021            Some(Value::Str("utf-8".into()))
3022        );
3023
3024        // the unit suffix convention: the probe's names carry no
3025        // suffix, so every reading forwards unchanged, except the
3026        // descendant searches by name, which are the engine's walk
3027        // under a renaming layer
3028        let u = crate::graph::autounits::AutoUnits::new(
3029            Probe,
3030            crate::graph::autounits::Suffixes::Known,
3031            "probe",
3032        );
3033        assert_forwards(&u, &["descendants_named", "descendants_where"]);
3034        assert_eq!(u.descendants_named(n(2), "x"), None);
3035    }
3036}