dcbor_pattern/pattern/
matcher.rs

1use std::collections::HashMap;
2
3use dcbor::prelude::*;
4
5use crate::pattern::{Pattern, vm::Instr};
6
7/// A sequence of `CBOR` that match a pattern, starting from the root of the
8/// dCBOR item.
9pub type Path = Vec<CBOR>;
10
11#[doc(hidden)]
12pub trait Matcher: std::fmt::Debug + std::fmt::Display + Clone {
13    /// Return all matching paths along with any named captures.
14    fn paths_with_captures(
15        &self,
16        _haystack: &CBOR,
17    ) -> (Vec<Path>, HashMap<String, Vec<Path>>) {
18        unimplemented!(
19            "Matcher::paths_with_captures not implemented for {:?}",
20            self
21        )
22    }
23
24    /// Return only the matching paths, discarding any captures.
25    fn paths(&self, haystack: &CBOR) -> Vec<Path> {
26        self.paths_with_captures(haystack).0
27    }
28
29    fn matches(&self, haystack: &CBOR) -> bool { !self.paths(haystack).is_empty() }
30
31    fn compile(
32        &self,
33        _code: &mut Vec<Instr>,
34        _literals: &mut Vec<Pattern>,
35        _captures: &mut Vec<String>,
36    ) {
37        unimplemented!("Matcher::compile not implemented for {:?}", self);
38    }
39
40    /// Recursively collect all capture names from this pattern.
41    fn collect_capture_names(&self, _names: &mut Vec<String>) {
42        // Default implementation does nothing - only capture patterns
43        // and patterns containing them need to override this
44    }
45
46    /// Should return true if the Display of the matcher is *complex*,
47    /// i.e. contains nested patterns or other complex structures
48    /// that require its text rendering to be surrounded by grouping
49    /// parentheses.
50    fn is_complex(&self) -> bool { false }
51}