1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
use dcbor::prelude::*;
use crate::pattern::{Matcher, Path, Pattern, vm::Instr};
/// A pattern that searches the entire dCBOR tree for matches.
///
/// This pattern recursively traverses the dCBOR tree and applies the inner
/// pattern at each node, returning all matching paths.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchPattern(Box<Pattern>);
impl SearchPattern {
/// Creates a new `SearchPattern` that searches for the given pattern.
pub fn new(pattern: Pattern) -> Self { SearchPattern(Box::new(pattern)) }
/// Returns a reference to the inner pattern.
pub fn pattern(&self) -> &Pattern { &self.0 }
// Helper method to recursively search through CBOR tree
fn search_recursive(
&self,
cbor: &CBOR,
path: Vec<CBOR>,
results: &mut Vec<Path>,
) {
// Test the pattern against this node
let pattern_paths = self.0.paths(cbor);
// If the pattern matches, add the current path to results
if !pattern_paths.is_empty() {
results.push(path.clone());
}
// Recursively search children based on CBOR type
match cbor.as_case() {
CBORCase::Array(arr) => {
for child in arr.iter() {
let mut new_path = path.clone();
new_path.push(child.clone());
self.search_recursive(child, new_path, results);
}
}
CBORCase::Map(map) => {
for (key, value) in map.iter() {
// Search both keys and values
let mut key_path = path.clone();
key_path.push(key.clone());
self.search_recursive(key, key_path, results);
let mut value_path = path.clone();
value_path.push(value.clone());
self.search_recursive(value, value_path, results);
}
}
CBORCase::Tagged(_, content) => {
let mut new_path = path.clone();
new_path.push(content.clone());
self.search_recursive(content, new_path, results);
}
_ => {
// Leaf nodes (primitives) - no children to search
}
}
}
// Helper method to recursively search through CBOR tree with capture
// support
fn search_recursive_with_captures(
&self,
cbor: &CBOR,
path: Vec<CBOR>,
results: &mut Vec<Path>,
all_captures: &mut std::collections::HashMap<String, Vec<Path>>,
) {
// Test the pattern against this node with captures
let (pattern_paths, captures) = self.0.paths_with_captures(cbor);
// If the pattern matches, add the current path to results and handle
// captures
if !pattern_paths.is_empty() {
results.push(path.clone());
// Handle captures based on the pattern type:
// - For array element captures like [@a(*), @b(*), @c(*)], preserve
// the original paths so that @a points to element 1, @b to
// element 2, etc.
// - For complex/nested patterns, captures point to the search
// location where the pattern was found, which provides the
// context for the match.
for (name, capture_paths) in captures {
if capture_paths.len() > 1
|| (capture_paths.len() == 1
&& capture_paths[0].len() > path.len())
{
// This appears to be an array pattern with element-level
// captures or a nested pattern where we
// want to preserve the original paths
for capture_path in capture_paths {
// Transform the capture path to include the search
// context
let mut transformed_path = path.clone();
// Add the relative path from the matched location to
// the captured value
if capture_path.len() > 1 {
transformed_path
.extend_from_slice(&capture_path[1..]);
}
all_captures
.entry(name.clone())
.or_default()
.push(transformed_path);
}
} else {
// For simple captures or when unclear, use the search
// location
all_captures.entry(name).or_default().push(path.clone());
}
}
}
// Recursively search children based on CBOR type
match cbor.as_case() {
CBORCase::Array(arr) => {
for child in arr.iter() {
let mut new_path = path.clone();
new_path.push(child.clone());
self.search_recursive_with_captures(
child,
new_path,
results,
all_captures,
);
}
}
CBORCase::Map(map) => {
for (key, value) in map.iter() {
// Search both keys and values
let mut key_path = path.clone();
key_path.push(key.clone());
self.search_recursive_with_captures(
key,
key_path,
results,
all_captures,
);
let mut value_path = path.clone();
value_path.push(value.clone());
self.search_recursive_with_captures(
value,
value_path,
results,
all_captures,
);
}
}
CBORCase::Tagged(_, content) => {
let mut tagged_path = path.clone();
tagged_path.push(content.clone());
self.search_recursive_with_captures(
content,
tagged_path,
results,
all_captures,
);
}
_ => {
// For primitive types, no further recursion
}
}
}
}
impl Default for SearchPattern {
fn default() -> Self {
// Create a default search pattern that matches any value
Self::new(Pattern::any())
}
}
impl Matcher for SearchPattern {
fn paths(&self, haystack: &CBOR) -> Vec<Path> {
let mut result_paths = Vec::new();
self.search_recursive(
haystack,
vec![haystack.clone()],
&mut result_paths,
);
// Remove duplicates based on CBOR values in the path
let mut seen = std::collections::HashSet::new();
let mut unique = Vec::new();
for path in result_paths {
// Create a unique key based on the path's CBOR values
let path_key: Vec<_> = path
.iter()
.map(|cbor| cbor.to_cbor_data()) // Use serialized form as key
.collect();
if seen.insert(path_key) {
unique.push(path);
}
}
unique
}
fn paths_with_captures(
&self,
haystack: &CBOR,
) -> (Vec<Path>, std::collections::HashMap<String, Vec<Path>>) {
let mut result_paths = Vec::new();
let mut all_captures = std::collections::HashMap::new();
self.search_recursive_with_captures(
haystack,
vec![haystack.clone()],
&mut result_paths,
&mut all_captures,
);
// Remove duplicates from result paths
let mut seen = std::collections::HashSet::new();
let mut unique_paths = Vec::new();
for path in result_paths {
let path_key: Vec<_> =
path.iter().map(|cbor| cbor.to_cbor_data()).collect();
if seen.insert(path_key) {
unique_paths.push(path);
}
}
(unique_paths, all_captures)
}
fn collect_capture_names(&self, names: &mut Vec<String>) {
// Delegate to the inner pattern to collect its capture names
self.0.collect_capture_names(names);
}
fn compile(
&self,
code: &mut Vec<Instr>,
literals: &mut Vec<Pattern>,
captures: &mut Vec<String>,
) {
let idx = literals.len();
literals.push((*self.0).clone());
// Collect capture names from the inner pattern
let mut inner_names = Vec::new();
self.0.collect_capture_names(&mut inner_names);
let mut capture_map = Vec::new();
for name in inner_names {
let pos = if let Some(i) = captures.iter().position(|n| n == &name)
{
i
} else {
let i = captures.len();
captures.push(name.clone());
i
};
capture_map.push((name, pos));
}
code.push(Instr::Search { pat_idx: idx, capture_map });
}
}
impl std::fmt::Display for SearchPattern {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "search({})", self.pattern())
}
}