Debian Codegraph @

src/graph/mod.rs

raw symbols SCIP
1 use std::cmp::Ordering;
2 use std::collections::btree_map::Entry;
3 use std::collections::BTreeMap as Map;
4 use std::hash::{Hash, Hasher};
5 use std::num::NonZeroU32;
6 use std::ops::Index;
7
8 use fnv::FnvHasher;
9
10 #[cfg(feature = "debug")]
11 mod export;
12 mod fork;
13 mod impls;
14 mod meta;
15 mod range;
16 mod regex;
17 mod rope;
18
19 pub use self::fork::Fork;
20 pub use self::meta::Meta;
21 pub use self::range::Range;
22 pub use self::rope::Rope;
23
24 /// Disambiguation error during the attempt to merge two leaf
25 /// nodes with the same priority
26 #[derive(Debug)]
27 pub struct DisambiguationError(pub NodeId, pub NodeId);
28
29 pub struct Graph<Leaf> {
30 /// Internal storage of all allocated nodes. Once a node is
31 /// put here, it should never be mutated.
32 nodes: Vec<Option<Node<Leaf>>>,
33 /// When merging two nodes into a new node, we store the two
34 /// entry keys and the result, so that we don't merge the same
35 /// two nodes multiple times.
36 ///
37 /// Most of the time the entry we want to find will be the last
38 /// one that has been inserted, so we can use a vec with reverse
39 /// order search to get O(1) searches much faster than any *Map.
40 merges: Map<Merge, NodeId>,
41 /// Another map used for accounting. Before `.push`ing a new node
42 /// onto the graph (inserts are exempt), we hash it and find if
43 /// an identical(!) node has been created before.
44 hashes: Map<u64, NodeId>,
45 /// Instead of handling errors over return types, opt to collect
46 /// them internally.
47 errors: Vec<DisambiguationError>,
48 /// Deferred merges. When when attempting to merge a node with an
49 /// empty reserved slot, the merging operation is deferred until
50 /// the reserved slot is populated. This is a stack that keeps track
51 /// of all such deferred merges
52 deferred: Vec<DeferredMerge>,
53 }
54
55 /// Trait to be implemented on `Leaf` nodes in order to disambiguate
56 /// between them.
57 pub trait Disambiguate {
58 fn cmp(left: &Self, right: &Self) -> Ordering;
59 }
60
61 /// Id of a Node in the graph. `NodeId` can be referencing an empty
62 /// slot that is going to be populated later in time.
63 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
64 pub struct NodeId(NonZeroU32);
65
66 impl Hash for NodeId {
67 fn hash<H: Hasher>(&self, state: &mut H) {
68 // Always use little-endian byte order for hashing to avoid
69 // different code generation on big-endian platforms due to
70 // iteration over a HashMap,
71 // see https://github.com/maciejhirsz/logos/issues/427.
72 state.write(&self.0.get().to_le_bytes())
73 }
74 }
75
76 impl NodeId {
77 fn get(self) -> usize {
78 self.0.get() as usize
79 }
80
81 fn new(n: usize) -> NodeId {
82 NodeId(NonZeroU32::new(n as u32).expect("Invalid NodeId"))
83 }
84 }
85
86 /// Unique reserved `NodeId` that is guaranteed to point to an
87 /// empty allocated slot in the graph. It's safe to create multiple
88 /// `NodeId` copies of `ReservedId`, however API users should never
89 /// be able to clone a `ReservedId`, or create a new one from `NodeId`.
90 ///
91 /// `ReservedId` is consumed once passed into `Graph::insert`.
92 #[derive(Debug)]
93 pub struct ReservedId(NodeId);
94
95 impl ReservedId {
96 pub fn get(&self) -> NodeId {
97 self.0
98 }
99 }
100
101 /// Merge key used to lookup whether two nodes have been previously
102 /// mered, so we can avoid duplicating merges, potentially running into
103 /// loops that blow out the stack.
104 ///
105 /// `Merge::new(a, b)` should always equal to `Merge::new(b, a)` to ensure
106 /// that node merges are symmetric.
107 #[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
108 struct Merge(NodeId, NodeId);
109
110 impl Merge {
111 fn new(a: NodeId, b: NodeId) -> Self {
112 if a < b {
113 Merge(a, b)
114 } else {
115 Merge(b, a)
116 }
117 }
118 }
119
120 /// When attempting to merge two nodes, one of which was not yet created,
121 /// we can record such attempt, and execute the merge later on when the
122 /// `awaiting` has been `insert`ed into the graph.
123 #[derive(Debug)]
124 pub struct DeferredMerge {
125 awaiting: NodeId,
126 with: NodeId,
127 into: ReservedId,
128 }
129
130 impl<Leaf> Graph<Leaf> {
131 pub fn new() -> Self {
132 Graph {
133 // Start with an empty slot so we can start
134 // counting NodeIds from 1 and use NonZero
135 // optimizations
136 nodes: vec![None],
137 merges: Map::new(),
138 hashes: Map::new(),
139 errors: Vec::new(),
140 deferred: Vec::new(),
141 }
142 }
143
144 pub fn errors(&self) -> &[DisambiguationError] {
145 &self.errors
146 }
147
148 fn next_id(&self) -> NodeId {
149 NodeId::new(self.nodes.len())
150 }
151
152 /// Reserve an empty slot for a node on the graph and return an
153 /// id for it. `ReservedId` cannot be cloned, and must be consumed
154 /// by calling `insert` on the graph.
155 pub fn reserve(&mut self) -> ReservedId {
156 let id = self.next_id();
157
158 self.nodes.push(None);
159
160 ReservedId(id)
161 }
162
163 /// Insert a node at a given, previously reserved id. Returns the
164 /// inserted `NodeId`.
165 pub fn insert<N>(&mut self, reserved: ReservedId, node: N) -> NodeId
166 where
167 N: Into<Node<Leaf>>,
168 Leaf: Disambiguate,
169 {
170 let id = reserved.get();
171
172 self.nodes[id.get()] = Some(node.into());
173
174 let mut awaiting = Vec::new();
175
176 // Partition out all `DeferredMerge`s that can be completed
177 // now that this `ReservedId` has a `Node` inserted into it.
178 for idx in (0..self.deferred.len()).rev() {
179 if self.deferred[idx].awaiting == id {
180 awaiting.push(self.deferred.remove(idx));
181 }
182 }
183
184 // Complete deferred merges. We've collected them from the back,
185 // so we must iterate through them from the back as well to restore
186 // proper order of merges in case there is some cascading going on.
187 for DeferredMerge {
188 awaiting,
189 with,
190 into,
191 } in awaiting.into_iter().rev()
192 {
193 self.merge_unchecked(awaiting, with, into);
194 }
195
196 id
197 }
198
199 /// Push a node onto the graph and get an id to it. If an identical
200 /// node has already been pushed on the graph, it will return the id
201 /// of that node instead.
202 pub fn push<B>(&mut self, node: B) -> NodeId
203 where
204 B: Into<Node<Leaf>>,
205 {
206 let node = node.into();
207
208 if let Node::Leaf(_) = node {
209 return self.push_unchecked(node);
210 }
211
212 let mut hasher = FnvHasher::default();
213 node.hash(&mut hasher);
214
215 let next_id = self.next_id();
216
217 match self.hashes.entry(hasher.finish()) {
218 Entry::Occupied(occupied) => {
219 let id = *occupied.get();
220
221 if self[id].eq(&node) {
222 return id;
223 }
224 }
225 Entry::Vacant(vacant) => {
226 vacant.insert(next_id);
227 }
228 }
229
230 self.push_unchecked(node)
231 }
232
233 fn push_unchecked(&mut self, node: Node<Leaf>) -> NodeId {
234 let id = self.next_id();
235
236 self.nodes.push(Some(node));
237
238 id
239 }
240
241 /// If nodes `a` and `b` have been already merged, return the
242 /// `NodeId` of the node they have been merged into.
243 fn find_merged(&self, a: NodeId, b: NodeId) -> Option<NodeId> {
244 let probe = Merge::new(a, b);
245
246 self.merges.get(&probe).copied()
247 }
248
249 /// Mark that nodes `a` and `b` have been merged into `product`.
250 ///
251 /// This will also mark merging `a` and `product`, as well as
252 /// `b` and `product` into `product`, since those are symmetric
253 /// operations.
254 ///
255 /// This is necessary to break out asymmetric merge loops.
256 fn set_merged(&mut self, a: NodeId, b: NodeId, product: NodeId) {
257 self.merges.insert(Merge::new(a, b), product);
258 self.merges.insert(Merge::new(a, product), product);
259 self.merges.insert(Merge::new(b, product), product);
260 }
261
262 /// Merge the nodes at id `a` and `b`, returning a new id.
263 pub fn merge(&mut self, a: NodeId, b: NodeId) -> NodeId
264 where
265 Leaf: Disambiguate,
266 {
267 if a == b {
268 return a;
269 }
270
271 // If the id pair is already merged (or is being merged), just return the id
272 if let Some(id) = self.find_merged(a, b) {
273 return id;
274 }
275
276 match (self.get(a), self.get(b)) {
277 (None, None) => {
278 panic!(
279 "Merging two reserved nodes! This is a bug, please report it:\n\
280 \n\
281 https://github.com/maciejhirsz/logos/issues"
282 );
283 }
284 (None, Some(_)) => {
285 let reserved = self.reserve();
286 let id = reserved.get();
287 self.deferred.push(DeferredMerge {
288 awaiting: a,
289 with: b,
290 into: reserved,
291 });
292 self.set_merged(a, b, id);
293
294 return id;
295 }
296 (Some(_), None) => {
297 let reserved = self.reserve();
298 let id = reserved.get();
299 self.deferred.push(DeferredMerge {
300 awaiting: b,
301 with: a,
302 into: reserved,
303 });
304 self.set_merged(a, b, id);
305
306 return id;
307 }
308 (Some(Node::Leaf(left)), Some(Node::Leaf(right))) => {
309 return match Disambiguate::cmp(left, right) {
310 Ordering::Less => b,
311 Ordering::Greater => a,
312 Ordering::Equal => {
313 self.errors.push(DisambiguationError(a, b));
314
315 a
316 }
317 };
318 }
319 _ => (),
320 }
321
322 // Reserve the id for the merge and save it. Since the graph can contain loops,
323 // this prevents us from trying to merge the same id pair in a loop, blowing up
324 // the stack.
325 let reserved = self.reserve();
326 self.set_merged(a, b, reserved.get());
327
328 self.merge_unchecked(a, b, reserved)
329 }
330
331 /// Unchecked merge of `a` and `b`. This fn assumes that `a` and `b` are
332 /// not pointing to empty slots.
333 fn merge_unchecked(&mut self, a: NodeId, b: NodeId, reserved: ReservedId) -> NodeId
334 where
335 Leaf: Disambiguate,
336 {
337 let merged_rope = match (self.get(a), self.get(b)) {
338 (Some(Node::Rope(rope)), _) => {
339 let rope = rope.clone();
340
341 self.merge_rope(rope, b)
342 }
343 (_, Some(Node::Rope(rope))) => {
344 let rope = rope.clone();
345
346 self.merge_rope(rope, a)
347 }
348 _ => None,
349 };
350
351 if let Some(rope) = merged_rope {
352 return self.insert(reserved, rope);
353 }
354
355 let mut fork = self.fork_off(a);
356 fork.merge(self.fork_off(b), self);
357
358 let mut stack = vec![reserved.get()];
359
360 // Flatten the fork
361 while let Some(miss) = fork.miss {
362 if stack.contains(&miss) {
363 break;
364 }
365 stack.push(miss);
366
367 let other = match self.get(miss) {
368 Some(Node::Fork(other)) => other.clone(),
369 Some(Node::Rope(other)) => other.clone().into_fork(self),
370 _ => break,
371 };
372 match other.miss {
373 Some(id) if self.get(id).is_none() => break,
374 _ => (),
375 }
376 fork.miss = None;
377 fork.merge(other, self);
378 }
379
380 self.insert(reserved, fork)
381 }
382
383 fn merge_rope(&mut self, rope: Rope, other: NodeId) -> Option<Rope>
384 where
385 Leaf: Disambiguate,
386 {
387 match self.get(other) {
388 Some(Node::Fork(fork)) if rope.miss.is_none() => {
389 // Count how many consecutive ranges in this rope would
390 // branch into the fork that results in a loop.
391 //
392 // e.g.: for rope "foobar" and a looping fork [a-z]: 6
393 let count = rope
394 .pattern
395 .iter()
396 .take_while(|range| fork.contains(**range) == Some(other))
397 .count();
398
399 let mut rope = rope.split_at(count, self)?.miss_any(other);
400
401 rope.then = self.merge(rope.then, other);
402
403 Some(rope)
404 }
405 Some(Node::Rope(other)) => {
406 let (prefix, miss) = rope.prefix(other)?;
407
408 let (a, b) = (rope, other.clone());
409
410 let a = a.remainder(prefix.len(), self);
411 let b = b.remainder(prefix.len(), self);
412
413 let rope = Rope::new(prefix, self.merge(a, b)).miss(miss);
414
415 Some(rope)
416 }
417 Some(Node::Leaf(_)) | None => {
418 if rope.miss.is_none() {
419 Some(rope.miss(other))
420 } else {
421 None
422 }
423 }
424 _ => None,
425 }
426 }
427
428 pub fn fork_off(&mut self, id: NodeId) -> Fork
429 where
430 Leaf: Disambiguate,
431 {
432 match self.get(id) {
433 Some(Node::Fork(fork)) => fork.clone(),
434 Some(Node::Rope(rope)) => rope.clone().into_fork(self),
435 Some(Node::Leaf(_)) | None => Fork::new().miss(id),
436 }
437 }
438
439 pub fn nodes(&self) -> &[Option<Node<Leaf>>] {
440 &self.nodes
441 }
442
443 /// Find all nodes that have no references and remove them.
444 pub fn shake(&mut self, root: NodeId) {
445 let mut filter = vec![false; self.nodes.len()];
446
447 filter[root.get()] = true;
448
449 self[root].shake(self, &mut filter);
450
451 for (id, referenced) in filter.into_iter().enumerate() {
452 if !referenced {
453 self.nodes[id] = None;
454 }
455 }
456 }
457
458 pub fn get(&self, id: NodeId) -> Option<&Node<Leaf>> {
459 self.nodes.get(id.get())?.as_ref()
460 }
461 }
462
463 impl<Leaf> Index<NodeId> for Graph<Leaf> {
464 type Output = Node<Leaf>;
465
466 fn index(&self, id: NodeId) -> &Node<Leaf> {
467 self.get(id).expect(
468 "Indexing into an empty node. This is a bug, please report it at:\n\
469 \n\
470 https://github.com/maciejhirsz/logos/issues",
471 )
472 }
473 }
474
475 impl std::fmt::Display for NodeId {
476 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
477 std::fmt::Display::fmt(&self.0, f)
478 }
479 }
480
481 #[cfg_attr(test, derive(PartialEq))]
482 pub enum Node<Leaf> {
483 /// Fork node, can lead to more than one state
484 Fork(Fork),
485 /// Rope node, can lead to one state on match, one state on miss
486 Rope(Rope),
487 /// Leaf node, terminal state
488 Leaf(Leaf),
489 }
490
491 impl<Leaf> Node<Leaf> {
492 pub fn miss(&self) -> Option<NodeId> {
493 match self {
494 Node::Rope(rope) => rope.miss.first(),
495 Node::Fork(fork) => fork.miss,
496 Node::Leaf(_) => None,
497 }
498 }
499
500 fn eq(&self, other: &Node<Leaf>) -> bool {
501 match (self, other) {
502 (Node::Fork(a), Node::Fork(b)) => a == b,
503 (Node::Rope(a), Node::Rope(b)) => a == b,
504 _ => false,
505 }
506 }
507
508 fn shake(&self, graph: &Graph<Leaf>, filter: &mut [bool]) {
509 match self {
510 Node::Fork(fork) => fork.shake(graph, filter),
511 Node::Rope(rope) => rope.shake(graph, filter),
512 Node::Leaf(_) => (),
513 }
514 }
515
516 pub fn unwrap_leaf(&self) -> &Leaf {
517 match self {
518 Node::Fork(_) => panic!("Internal Error: called unwrap_leaf on a fork"),
519 Node::Rope(_) => panic!("Internal Error: called unwrap_leaf on a rope"),
520 Node::Leaf(leaf) => leaf,
521 }
522 }
523 }
524
525 #[cfg(test)]
526 mod tests {
527 use super::*;
528 use pretty_assertions::assert_eq;
529
530 #[test]
531 fn leaf_stack_size() {
532 use std::mem::size_of;
533
534 const WORD: usize = size_of::<usize>();
535 const NODE: usize = size_of::<Node<()>>();
536
537 assert!(NODE <= 6 * WORD, "Size of Node<()> is {} bytes!", NODE);
538 }
539
540 #[test]
541 fn create_a_loop() {
542 let mut graph = Graph::new();
543
544 let token = graph.push(Node::Leaf("IDENT"));
545 let id = graph.reserve();
546 let fork = Fork::new().branch('a'..='z', id.get()).miss(token);
547 let root = graph.insert(id, fork);
548
549 assert_eq!(graph[token], Node::Leaf("IDENT"));
550 assert_eq!(graph[root], Fork::new().branch('a'..='z', root).miss(token),);
551 }
552
553 #[test]
554 fn fork_off() {
555 let mut graph = Graph::new();
556
557 let leaf = graph.push(Node::Leaf("LEAF"));
558 let rope = graph.push(Rope::new("rope", leaf));
559 let fork = graph.push(Fork::new().branch(b'!', leaf));
560
561 assert_eq!(graph.fork_off(leaf), Fork::new().miss(leaf));
562 assert_eq!(
563 graph.fork_off(rope),
564 Fork::new().branch(b'r', NodeId::new(graph.nodes.len() - 1))
565 );
566 assert_eq!(graph.fork_off(fork), Fork::new().branch(b'!', leaf));
567 }
568 }