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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
use std::cmp::Ordering;
use std::collections::btree_map::Entry;
use std::collections::BTreeMap as Map;
use std::hash::{Hash, Hasher};
use std::num::NonZeroU32;
use std::ops::Index;
use fnv::FnvHasher;
mod fork;
mod impls;
mod meta;
mod range;
mod regex;
mod rope;
pub use self::fork::Fork;
pub use self::meta::Meta;
pub use self::range::Range;
pub use self::rope::Rope;
#[derive(Debug)]
pub struct DisambiguationError(pub NodeId, pub NodeId);
pub struct Graph<Leaf> {
nodes: Vec<Option<Node<Leaf>>>,
merges: Map<Merge, NodeId>,
hashes: Map<u64, NodeId>,
errors: Vec<DisambiguationError>,
deferred: Vec<DeferredMerge>,
}
pub trait Disambiguate {
fn cmp(left: &Self, right: &Self) -> Ordering;
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodeId(NonZeroU32);
impl NodeId {
fn get(self) -> usize {
self.0.get() as usize
}
fn new(n: usize) -> NodeId {
NodeId(NonZeroU32::new(n as u32).expect("Invalid NodeId"))
}
}
#[derive(Debug)]
pub struct ReservedId(NodeId);
impl ReservedId {
pub fn get(&self) -> NodeId {
self.0
}
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
struct Merge(NodeId, NodeId);
impl Merge {
fn new(a: NodeId, b: NodeId) -> Self {
if a < b {
Merge(a, b)
} else {
Merge(b, a)
}
}
}
#[derive(Debug)]
pub struct DeferredMerge {
awaiting: NodeId,
with: NodeId,
into: ReservedId,
}
impl<Leaf> Graph<Leaf> {
pub fn new() -> Self {
Graph {
nodes: vec![None],
merges: Map::new(),
hashes: Map::new(),
errors: Vec::new(),
deferred: Vec::new(),
}
}
pub fn errors(&self) -> &[DisambiguationError] {
&self.errors
}
fn next_id(&self) -> NodeId {
NodeId::new(self.nodes.len())
}
pub fn reserve(&mut self) -> ReservedId {
let id = self.next_id();
self.nodes.push(None);
ReservedId(id)
}
pub fn insert<N>(&mut self, reserved: ReservedId, node: N) -> NodeId
where
N: Into<Node<Leaf>>,
Leaf: Disambiguate,
{
let id = reserved.get();
self.nodes[id.get()] = Some(node.into());
let mut awaiting = Vec::new();
for idx in (0..self.deferred.len()).rev() {
if self.deferred[idx].awaiting == id {
awaiting.push(self.deferred.remove(idx));
}
}
for DeferredMerge {
awaiting,
with,
into,
} in awaiting.into_iter().rev()
{
self.merge_unchecked(awaiting, with, into);
}
id
}
pub fn push<B>(&mut self, node: B) -> NodeId
where
B: Into<Node<Leaf>>,
{
let node = node.into();
if let Node::Leaf(_) = node {
return self.push_unchecked(node);
}
let mut hasher = FnvHasher::default();
node.hash(&mut hasher);
let next_id = self.next_id();
match self.hashes.entry(hasher.finish()) {
Entry::Occupied(occupied) => {
let id = *occupied.get();
if self[id].eq(&node) {
return id;
}
}
Entry::Vacant(vacant) => {
vacant.insert(next_id);
}
}
self.push_unchecked(node)
}
fn push_unchecked(&mut self, node: Node<Leaf>) -> NodeId {
let id = self.next_id();
self.nodes.push(Some(node));
id
}
fn find_merged(&self, a: NodeId, b: NodeId) -> Option<NodeId> {
let probe = Merge::new(a, b);
self.merges.get(&probe).copied()
}
fn set_merged(&mut self, a: NodeId, b: NodeId, product: NodeId) {
self.merges.insert(Merge::new(a, b), product);
self.merges.insert(Merge::new(a, product), product);
self.merges.insert(Merge::new(b, product), product);
}
pub fn merge(&mut self, a: NodeId, b: NodeId) -> NodeId
where
Leaf: Disambiguate,
{
if a == b {
return a;
}
if let Some(id) = self.find_merged(a, b) {
return id;
}
match (self.get(a), self.get(b)) {
(None, None) => {
panic!(
"Merging two reserved nodes! This is a bug, please report it:\n\
\n\
https://github.com/maciejhirsz/logos/issues"
);
}
(None, Some(_)) => {
let reserved = self.reserve();
let id = reserved.get();
self.deferred.push(DeferredMerge {
awaiting: a,
with: b,
into: reserved,
});
self.set_merged(a, b, id);
return id;
}
(Some(_), None) => {
let reserved = self.reserve();
let id = reserved.get();
self.deferred.push(DeferredMerge {
awaiting: b,
with: a,
into: reserved,
});
self.set_merged(a, b, id);
return id;
}
(Some(Node::Leaf(left)), Some(Node::Leaf(right))) => {
return match Disambiguate::cmp(left, right) {
Ordering::Less => b,
Ordering::Greater => a,
Ordering::Equal => {
self.errors.push(DisambiguationError(a, b));
a
}
};
}
_ => (),
}
let reserved = self.reserve();
self.set_merged(a, b, reserved.get());
self.merge_unchecked(a, b, reserved)
}
fn merge_unchecked(&mut self, a: NodeId, b: NodeId, reserved: ReservedId) -> NodeId
where
Leaf: Disambiguate,
{
let merged_rope = match (self.get(a), self.get(b)) {
(Some(Node::Rope(rope)), _) => {
let rope = rope.clone();
self.merge_rope(rope, b)
}
(_, Some(Node::Rope(rope))) => {
let rope = rope.clone();
self.merge_rope(rope, a)
}
_ => None,
};
if let Some(rope) = merged_rope {
return self.insert(reserved, rope);
}
let mut fork = self.fork_off(a);
fork.merge(self.fork_off(b), self);
let mut stack = vec![reserved.get()];
while let Some(miss) = fork.miss {
if stack.contains(&miss) {
break;
}
stack.push(miss);
let other = match self.get(miss) {
Some(Node::Fork(other)) => other.clone(),
Some(Node::Rope(other)) => other.clone().into_fork(self),
_ => break,
};
match other.miss {
Some(id) if self.get(id).is_none() => break,
_ => (),
}
fork.miss = None;
fork.merge(other, self);
}
self.insert(reserved, fork)
}
fn merge_rope(&mut self, rope: Rope, other: NodeId) -> Option<Rope>
where
Leaf: Disambiguate,
{
match self.get(other) {
Some(Node::Fork(fork)) if rope.miss.is_none() => {
let count = rope
.pattern
.iter()
.take_while(|range| fork.contains(**range) == Some(other))
.count();
let mut rope = rope.split_at(count, self)?.miss_any(other);
rope.then = self.merge(rope.then, other);
Some(rope)
}
Some(Node::Rope(other)) => {
let (prefix, miss) = rope.prefix(other)?;
let (a, b) = (rope, other.clone());
let a = a.remainder(prefix.len(), self);
let b = b.remainder(prefix.len(), self);
let rope = Rope::new(prefix, self.merge(a, b)).miss(miss);
Some(rope)
}
Some(Node::Leaf(_)) | None => {
if rope.miss.is_none() {
Some(rope.miss(other))
} else {
None
}
}
_ => None,
}
}
pub fn fork_off(&mut self, id: NodeId) -> Fork
where
Leaf: Disambiguate,
{
match self.get(id) {
Some(Node::Fork(fork)) => fork.clone(),
Some(Node::Rope(rope)) => rope.clone().into_fork(self),
Some(Node::Leaf(_)) | None => Fork::new().miss(id),
}
}
pub fn nodes(&self) -> &[Option<Node<Leaf>>] {
&self.nodes
}
pub fn shake(&mut self, root: NodeId) {
let mut filter = vec![false; self.nodes.len()];
filter[root.get()] = true;
self[root].shake(self, &mut filter);
for (id, referenced) in filter.into_iter().enumerate() {
if !referenced {
self.nodes[id] = None;
}
}
}
pub fn get(&self, id: NodeId) -> Option<&Node<Leaf>> {
self.nodes.get(id.get())?.as_ref()
}
}
impl<Leaf> Index<NodeId> for Graph<Leaf> {
type Output = Node<Leaf>;
fn index(&self, id: NodeId) -> &Node<Leaf> {
self.get(id).expect(
"Indexing into an empty node. This is a bug, please report it at:\n\
\n\
https://github.com/maciejhirsz/logos/issues",
)
}
}
impl std::fmt::Display for NodeId {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
std::fmt::Display::fmt(&self.0, f)
}
}
#[cfg_attr(test, derive(PartialEq))]
pub enum Node<Leaf> {
Fork(Fork),
Rope(Rope),
Leaf(Leaf),
}
impl<Leaf> Node<Leaf> {
pub fn miss(&self) -> Option<NodeId> {
match self {
Node::Rope(rope) => rope.miss.first(),
Node::Fork(fork) => fork.miss,
Node::Leaf(_) => None,
}
}
fn eq(&self, other: &Node<Leaf>) -> bool {
match (self, other) {
(Node::Fork(a), Node::Fork(b)) => a == b,
(Node::Rope(a), Node::Rope(b)) => a == b,
_ => false,
}
}
fn shake(&self, graph: &Graph<Leaf>, filter: &mut [bool]) {
match self {
Node::Fork(fork) => fork.shake(graph, filter),
Node::Rope(rope) => rope.shake(graph, filter),
Node::Leaf(_) => (),
}
}
pub fn unwrap_leaf(&self) -> &Leaf {
match self {
Node::Fork(_) => panic!("Internal Error: called unwrap_leaf on a fork"),
Node::Rope(_) => panic!("Internal Error: called unwrap_leaf on a rope"),
Node::Leaf(leaf) => leaf,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn leaf_stack_size() {
use std::mem::size_of;
const WORD: usize = size_of::<usize>();
const NODE: usize = size_of::<Node<()>>();
assert!(NODE <= 6 * WORD, "Size of Node<()> is {} bytes!", NODE);
}
#[test]
fn create_a_loop() {
let mut graph = Graph::new();
let token = graph.push(Node::Leaf("IDENT"));
let id = graph.reserve();
let fork = Fork::new().branch('a'..='z', id.get()).miss(token);
let root = graph.insert(id, fork);
assert_eq!(graph[token], Node::Leaf("IDENT"));
assert_eq!(graph[root], Fork::new().branch('a'..='z', root).miss(token),);
}
#[test]
fn fork_off() {
let mut graph = Graph::new();
let leaf = graph.push(Node::Leaf("LEAF"));
let rope = graph.push(Rope::new("rope", leaf));
let fork = graph.push(Fork::new().branch(b'!', leaf));
assert_eq!(graph.fork_off(leaf), Fork::new().miss(leaf));
assert_eq!(
graph.fork_off(rope),
Fork::new().branch(b'r', NodeId::new(graph.nodes.len() - 1))
);
assert_eq!(graph.fork_off(fork), Fork::new().branch(b'!', leaf));
}
}