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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
|
//! This file defines some traits and basic implementations for
//! matching pattern vertices against target vertices.
use crate::{bytes::BytesForest, ForestLabel};
#[allow(unused_imports)]
use graph::{
error::Error as GError, ELabelGraph, Graph, GraphLabel, LabelGraph, PLGraph, SLGBuilder,
SLGraph, VLabelGraph,
};
use graph_macro::Graph;
use grammar::GrammarLabel;
/// An aggregate struct that holds information about a parent as well
/// as its vertex label and the corresponding edge label.
#[derive(Debug, Clone, Copy)]
pub struct EVLabelParent<T: GraphLabel> {
parent: usize,
// edge_index: usize,
parent_label: T,
edge_label: EdgeType,
}
impl<T: GraphLabel> EVLabelParent<T> {
/// Construct a new instance.
pub fn new(parent: usize, parent_label: T, edge_label: EdgeType) -> Self {
Self {
parent,
parent_label,
edge_label,
}
}
/// Retrieve the `parent` field.
pub fn parent(&self) -> usize {
self.parent
}
// /// Retrieve the `edge_index` field.
// pub fn edge_index(&self) -> usize {
// self.edge_index
// }
/// Retrieve the `parent_label` field.
pub fn parent_label(&self) -> T {
self.parent_label
}
/// Retrieve the `edge_label` field.
pub fn edge_label(&self) -> EdgeType {
self.edge_label
}
}
/// A trait for pattern graphs.
pub trait Pattern<T: GraphLabel>: VLabelGraph<T> + ELabelGraph<EdgeType> {
/// An iterator delegation for parents and vertex and edge labels.
type ParentIter<'a>: Iterator<Item = EVLabelParent<T>> + 'a
where
Self: 'a,
T: 'a;
/// Return an iterator that goes through the parents and edge
/// labels.
fn parents(&self, node: usize) -> Result<Self::ParentIter<'_>, GError>;
}
/// A trait for target graphs.
pub trait Target<T: GraphLabel>: VLabelGraph<T> {
/// Return an array of node indices whose labels match the given
/// label.
fn filter_label(&self, label: T) -> Box<[usize]> {
let _label = label;
(0..self.nodes_len()).collect::<Vec<_>>().into_boxed_slice()
}
}
/// A custom pattern type with a fixed edge label and a generic vertex
/// label.
///
/// This type contains two graphs, with the extra one containing
/// parentship information.
#[derive(Debug, Clone, Graph)]
pub struct SimplePattern<T: GraphLabel> {
graph: SLGBuilder<T, EdgeType>,
parents_graph: SLGBuilder<T, EdgeType>,
}
impl<T: GraphLabel> Default for SimplePattern<T> {
fn default() -> Self {
let graph = SLGBuilder::default();
let parents_graph = SLGBuilder::default();
Self {
graph,
parents_graph,
}
}
}
impl<T: GraphLabel> SimplePattern<T> {
/// Return a new pattern from an underlying graph builder.
pub fn new(graph: SLGBuilder<T, EdgeType>) -> Result<Self, GError> {
let nodes_len = graph.nodes_len();
let mut parents_graph: SLGBuilder<T, EdgeType> = SLGBuilder::with_capacity(nodes_len);
for node in 0..nodes_len {
// Nodes must have labels.
let label = VLabelGraph::vertex_label(&graph, node)?.unwrap();
parents_graph.add_vertex(label);
}
for node in 0..nodes_len {
for (label, child) in ELabelGraph::edlabren_of(&graph, node)? {
parents_graph.add_edge(node, child, label)?;
}
}
Ok(Self {
graph,
parents_graph,
})
}
}
impl<T: GraphLabel> VLabelGraph<T> for SimplePattern<T> {
type TupleIter<'a> = <SLGBuilder::<T, EdgeType> as VLabelGraph<T>>::TupleIter<'a>
where
Self: 'a,
T: 'a;
fn verlabren_of(&self, node_id: usize) -> Result<Self::TupleIter<'_>, GError> {
self.graph.verlabren_of(node_id)
}
}
impl<T: GraphLabel> LabelGraph<EdgeType> for SimplePattern<T> {
type Iter<'a> = std::iter::Empty<usize>
where
Self: 'a;
type TupleIter<'a> = <SLGBuilder::<T, EdgeType> as LabelGraph<EdgeType>>::TupleIter<'a>
where
Self: 'a,
T: 'a;
type LabelIter<'a> = std::iter::Empty<(&'a EdgeType, std::iter::Empty<usize>)>
where
Self: 'a,
T: 'a;
type EdgeLabelIter<'a> = std::option::IntoIter<EdgeType>
where
Self: 'a,
T: 'a;
fn edge_label(&self, source: usize, target: usize) -> Result<Self::EdgeLabelIter<'_>, GError> {
LabelGraph::edge_label(&self.graph, source, target)
}
fn find_children_with_label(
&self,
node_id: usize,
label: &EdgeType,
) -> Result<<Self as LabelGraph<EdgeType>>::Iter<'_>, GError> {
self.graph.find_children_with_label(node_id, label)
}
fn labels_of(&self, _node_id: usize) -> Result<Self::LabelIter<'_>, GError> {
unimplemented!("Unsupported operation!")
}
fn tuples_of(&self, node_id: usize) -> Result<Self::TupleIter<'_>, GError> {
self.graph.tuples_of(node_id)
}
fn has_edge_label(
&self,
node_id: usize,
label: &EdgeType,
target: usize,
) -> Result<bool, GError> {
self.graph.has_edge_label(node_id, label, target)
}
}
/// Iterator delegator for parents.
#[derive(Debug, Clone)]
pub struct PatternParents<'a, T>
where
T: GraphLabel + 'a,
{
vertex_iter: <SLGBuilder<T, EdgeType> as VLabelGraph<T>>::TupleIter<'a>,
edge_iter: <SLGBuilder<T, EdgeType> as ELabelGraph<EdgeType>>::TupleIter<'a>,
}
impl<'a, T> PatternParents<'a, T>
where
T: GraphLabel + 'a,
{
/// Construct a new iterator.
pub fn new(
vertex_iter: <SLGBuilder<T, EdgeType> as VLabelGraph<T>>::TupleIter<'a>,
edge_iter: <SLGBuilder<T, EdgeType> as ELabelGraph<EdgeType>>::TupleIter<'a>,
) -> Self {
Self {
vertex_iter,
edge_iter,
}
}
}
impl<'a, T: 'a + GraphLabel> Iterator for PatternParents<'a, T> {
type Item = EVLabelParent<T>;
fn next(&mut self) -> Option<Self::Item> {
self.vertex_iter.next().and_then(|(vlabel, target)| {
self.edge_iter
.next()
.map(|(elabel, _)| EVLabelParent::new(target, vlabel, elabel))
})
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.vertex_iter.size_hint()
}
}
impl<'a, T: 'a + GraphLabel> ExactSizeIterator for PatternParents<'a, T> {
#[inline]
fn len(&self) -> usize {
self.vertex_iter.len()
}
}
impl<T: GraphLabel> Pattern<T> for SimplePattern<T> {
type ParentIter<'a> = PatternParents<'a, T> where T:'a;
fn parents(&self, node: usize) -> Result<Self::ParentIter<'_>, GError> {
let vertex_iter = self.parents_graph.verlabren_of(node)?;
let edge_iter = self.parents_graph.edlabren_of(node)?;
Ok(PatternParents::new(vertex_iter, edge_iter))
}
}
// Implement Target for three types. Another type "DefaultForest"
// should implement this trait on its own when the need arises.
//
// Note that SimplePattern also implements the Target trait.
impl<T: GraphLabel> Target<T> for SimplePattern<T> {
fn filter_label(&self, label: T) -> Box<[usize]> {
(0..self.nodes_len())
.filter(|node| VLabelGraph::vertex_label(self, *node) == Ok(Some(label)))
.collect::<Vec<_>>()
.into_boxed_slice()
}
}
impl<T: GraphLabel> Target<T> for PLGraph<T> {
fn filter_label(&self, label: T) -> Box<[usize]> {
(0..self.nodes_len())
.filter(|node| VLabelGraph::vertex_label(self, *node) == Ok(Some(label)))
.collect::<Vec<_>>()
.into_boxed_slice()
}
}
impl Target<ForestLabel<GrammarLabel>> for BytesForest {
fn filter_label(&self, label: ForestLabel<GrammarLabel>) -> Box<[usize]> {
(0..self.nodes_len())
.filter(|node| VLabelGraph::vertex_label(self, *node) == Ok(Some(label)))
.collect::<Vec<_>>()
.into_boxed_slice()
}
}
// Edge-filtering types
/// The type of edges that this edge can match against.
///
/// For the time being, we can only match either a direct child
/// (i.e. no extra condition) or a sibling of another node.
///
/// In the future, we shall be able to use supplemental graphs to
/// match edges.
///
/// This can be used as [`Graphlabel`][graph::GraphLabel].
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum EdgeType {
/// Matches a direct child.
#[default]
Direct,
/// Match a sibling of another node.
Sibling(usize),
}
impl std::fmt::Display for EdgeType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EdgeType::Direct => write!(f, "direct edge"),
EdgeType::Sibling(node) => write!(f, "sibling of {node}"),
}
}
}
impl EdgeType {
/// Return a Sibling-type edge.
pub fn sibling(node: usize) -> Self {
Self::Sibling(node)
}
/// Return whether this edge matches.
pub fn matches<G: Graph>(&self, g: &G, from: usize, to: usize) -> Result<bool, GError> {
match self {
EdgeType::Direct => g.has_edge(from, to),
EdgeType::Sibling(sibling) => {
let mut iter = g.children_of(from)?;
while let Some(child) = iter.next() {
if child == *sibling {
return Ok(iter.next() == Some(to));
}
}
// sibling not found
Ok(false)
}
}
}
}
|