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
//! Main [`Recorder`] implementation collecting the bytes of all matches.
//!
//! This is the heaviest recorder. It will copy all bytes of all matches into [`Vecs`](`Vec`).
//!
// There is number of invariants that are hard to enforce on the type level,
// and handling of Depth that should be properly error-handled by the engine, not here.
// Using `expect` here is idiomatic.
#![allow(clippy::expect_used)]

use super::*;
use crate::{debug, depth::Depth};
use std::{
    cell::RefCell,
    fmt::{self, Debug, Display},
    str::{self, Utf8Error},
};

/// Recorder that collects all byte spans of matched values
/// and feeds [`Match`es](`super::Match`) to the [`Sink`].
#[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodesResult {
    spans: Vec<Vec<u8>>,
}

impl NodesResult {
    /// Get slices of raw bytes of all matched nodes.
    #[must_use]
    #[inline(always)]
    pub fn get(&self) -> &[impl AsRef<[u8]>] {
        &self.spans
    }

    /// Iterate over all slices interpreted as valid UTF8.
    #[must_use]
    #[inline(always)]
    pub fn iter_as_utf8(&self) -> impl IntoIterator<Item = Result<&str, Utf8Error>> {
        self.spans.iter().map(|x| str::from_utf8(x))
    }

    /// Return the inner buffers consuming the result.
    #[must_use]
    #[inline(always)]
    pub fn into_inner(self) -> Vec<Vec<u8>> {
        self.spans
    }
}

impl From<NodesResult> for Vec<Vec<u8>> {
    #[inline(always)]
    fn from(result: NodesResult) -> Self {
        result.spans
    }
}

impl Display for NodesResult {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for span in &self.spans {
            let display = String::from_utf8_lossy(span);
            writeln!(f, "{display}")?;
        }

        Ok(())
    }
}

/// Recorder for [`NodesResult`].
pub struct NodesRecorder<'s, B, S> {
    internal: RefCell<InternalRecorder<'s, B, S>>,
}

impl<'s, B, S> NodesRecorder<'s, B, S>
where
    B: Deref<Target = [u8]>,
    S: Sink<Match>,
{
    pub(crate) fn build_recorder(sink: &'s mut S) -> Self {
        Self {
            internal: RefCell::new(InternalRecorder::new(sink)),
        }
    }
}

impl<'s, B, S> InputRecorder<B> for NodesRecorder<'s, B, S>
where
    B: Deref<Target = [u8]>,
    S: Sink<Match>,
{
    #[inline(always)]
    fn record_block_start(&self, new_block: B) {
        self.internal.borrow_mut().record_block(new_block)
    }
}

impl<'s, B, S> Recorder<B> for NodesRecorder<'s, B, S>
where
    B: Deref<Target = [u8]>,
    S: Sink<Match>,
{
    #[inline]
    fn record_match(&self, idx: usize, depth: Depth, ty: MatchedNodeType) -> Result<(), EngineError> {
        debug!("Recording match at {idx}");
        self.internal.borrow_mut().record_match(idx, depth, ty);
        Ok(())
    }

    #[inline]
    fn record_value_terminator(&self, idx: usize, depth: Depth) -> Result<(), EngineError> {
        self.internal
            .borrow_mut()
            .record_value_terminator(idx, depth)
            .map_err(|err| EngineError::SinkError(Box::new(err)))
    }
}

/*
{
    [
        1,
        2,
        [
            3,
            4
        ]
    ],
    [
        5
    ]
}

// Required order:
// [1,2,[3,4]], 1, 2, [3,4], 3, 4, [5], 5

// Finalization order:
// 1, 2, 3, 4, [3,4], [1,2,[3,4]], 5, [5]

1. By default, we assume the common case of no overlapping matches.
In that case we don't have to maintain any stack, the state is simply
a buffer for the current match and information on when to end it.
2. If a new match is registered when there is a match active, it means
they are overlapping and we switch to the second algorithm.

Matches are pushed onto a stack. Every time we finish a match we need to find
the node that is finalized. If we keep all matches on the stack it would take
potentially linear time. In the above example, when [3,4] is finalized,
there is 3 and 4 already finalized *above* on the stack. This leads to a quadratic
blowup if implemented naively (just consider a long list of atoms).

Instead we keep only the active matches on the stack, annotated with the output number
of the match. In a secondary array we keep the finished nodes in the output order.
When popping we can write the node into the array with random-access. Because
the order is maintained, outputting the nodes is easy since we can just look at the
node with the number that should be output next and iterate from there.

This would be potentially wasteful on its own, since we'd always have the secondary array
grow to the total number of matches. We can instead compress the array when it becomes
empty and keep a map between output number and array indices. For example, here's
the state of this algorithm on the above example after the match of "2" is completed.

STACK             | DONE (off. 0) |
                  | Some(2)       |
                  | Some(1)       |
(0, [1,2...)      | None          |

After "4":

STACK             | DONE (off. 0) |
                  | Some(4)       |
                  | Some(3)       |
                  | None          |
                  | Some(2)       |
(3, [3,4])        | Some(1)       |
(0, [1,2,[3,4...) | None          |

Now after the first list gets finalized we can output everything in the array starting from
index 0. Now that the stack is empty we can compress.

STACK             | DONE (off. 5)

Now we push the second list and the 5, finalize the 5.
We write it to array at index 1, since its output order is 6 and the offset from compression
is 5.

STACK             | DONE (off. 5)
                  | Some(5)
(6, [5...)        | None
*/

enum InternalRecorder<'s, B, S> {
    Simple(SimpleRecorder<'s, B, S>),
    Stack(StackRecorder<'s, B, S>),
    Transition,
}

impl<'s, B, S> InternalRecorder<'s, B, S>
where
    B: Deref<Target = [u8]>,
    S: Sink<Match>,
{
    fn new(sink: &'s mut S) -> Self {
        Self::Simple(SimpleRecorder::new(sink))
    }

    #[inline(always)]
    fn record_block(&mut self, block: B) {
        match self {
            Self::Simple(r) => r.record_block(block),
            Self::Stack(r) => r.record_block(block),
            Self::Transition => unreachable!(),
        }
    }

    #[inline(always)]
    fn record_match(&mut self, idx: usize, depth: Depth, ty: MatchedNodeType) {
        match self {
            Self::Simple(simple) => {
                if !simple.try_record_match(idx, depth, ty) {
                    let simple = match std::mem::replace(self, Self::Transition) {
                        Self::Simple(s) => s,
                        Self::Stack(_) | Self::Transition => unreachable!(),
                    };
                    let mut stack = simple.transform_to_stack();
                    stack.record_match(idx, depth, ty);
                    *self = Self::Stack(stack);
                }
            }
            Self::Stack(stack) => stack.record_match(idx, depth, ty),
            Self::Transition => unreachable!(),
        }
    }

    #[allow(clippy::panic_in_result_fn)] // Reaching unreachable is an unrecoverable bug.
    #[inline(always)]
    fn record_value_terminator(&mut self, idx: usize, depth: Depth) -> Result<(), EngineError> {
        match self {
            Self::Simple(r) => r.record_value_terminator(idx, depth),
            Self::Stack(r) => r.record_value_terminator(idx, depth),
            Self::Transition => unreachable!(),
        }
    }
}

struct SimpleRecorder<'s, B, S> {
    idx: usize,
    current_block: Option<B>,
    node: Option<SimplePartialNode>,
    sink: &'s mut S,
}

struct SimplePartialNode {
    start_idx: usize,
    start_depth: Depth,
    buf: Vec<u8>,
    ty: MatchedNodeType,
}

impl<'s, B, S> SimpleRecorder<'s, B, S>
where
    B: Deref<Target = [u8]>,
    S: Sink<Match>,
{
    fn new(sink: &'s mut S) -> Self {
        Self {
            idx: 0,
            current_block: None,
            node: None,
            sink,
        }
    }

    fn record_block(&mut self, block: B) {
        if let Some(finished) = self.current_block.as_ref() {
            if let Some(node) = self.node.as_mut() {
                debug!("Continuing node, idx is {}", self.idx);
                append_block(&mut node.buf, finished, self.idx, node.start_idx)
            }

            self.idx += finished.len();
        }

        self.current_block = Some(block);
        debug!("New block, idx = {}", self.idx);
    }

    fn record_value_terminator(&mut self, idx: usize, depth: Depth) -> Result<(), EngineError> {
        debug!("Value terminator at {idx}, depth {depth}");
        if let Some(node) = self.node.as_ref() {
            if node.start_depth >= depth {
                let mut node = self.node.take().expect("node is Some");
                debug!("Mark node as ended at {}", idx + 1);
                append_final_block(
                    &mut node.buf,
                    self.current_block
                        .as_ref()
                        .ok_or(EngineError::MissingOpeningCharacter())?,
                    self.idx,
                    node.start_idx,
                    idx + 1,
                );
                finalize_node(&mut node.buf, node.ty);

                debug!("Committing and outputting node");
                self.sink
                    .add_match(Match {
                        bytes: node.buf,
                        span: MatchSpan {
                            start_idx: node.start_idx,
                            end_idx: idx + 1,
                        },
                    })
                    .map_err(|err| EngineError::SinkError(Box::new(err)))?;
            }
        }

        Ok(())
    }

    fn try_record_match(&mut self, idx: usize, depth: Depth, ty: MatchedNodeType) -> bool {
        if self.node.is_some() {
            debug!("nested match detected, switching to stack");
            return false;
        }

        let node = SimplePartialNode {
            start_idx: idx,
            start_depth: depth,
            buf: vec![],
            ty,
        };
        self.node = Some(node);

        true
    }

    fn transform_to_stack(self) -> StackRecorder<'s, B, S> {
        match self.node {
            Some(node) => StackRecorder {
                idx: self.idx,
                match_count: 1,
                current_block: self.current_block,
                stack: vec![PartialNode {
                    id: 0,
                    start_idx: node.start_idx,
                    start_depth: node.start_depth,
                    buf: node.buf,
                    ty: node.ty,
                }],
                output_queue: OutputQueue::new(),
                sink: self.sink,
            },
            None => StackRecorder {
                idx: self.idx,
                match_count: 0,
                current_block: self.current_block,
                stack: vec![],
                output_queue: OutputQueue::new(),
                sink: self.sink,
            },
        }
    }
}

struct StackRecorder<'s, B, S> {
    idx: usize,
    match_count: usize,
    current_block: Option<B>,
    stack: Vec<PartialNode>,
    output_queue: OutputQueue,
    sink: &'s mut S,
}

struct PartialNode {
    id: usize,
    start_idx: usize,
    start_depth: Depth,
    buf: Vec<u8>,
    ty: MatchedNodeType,
}

struct OutputQueue {
    offset: usize,
    nodes: Vec<Option<Match>>,
}

impl OutputQueue {
    fn new() -> Self {
        Self {
            offset: 0,
            nodes: vec![],
        }
    }

    fn insert(&mut self, id: usize, node: Match) {
        let actual_idx = id - self.offset;

        while self.nodes.len() <= actual_idx {
            self.nodes.push(None);
        }

        self.nodes[actual_idx] = Some(node);
    }

    fn output_to<S>(&mut self, sink: &mut S) -> Result<(), S::Error>
    where
        S: Sink<Match>,
    {
        self.offset += self.nodes.len();

        for node in self.nodes.drain(..) {
            sink.add_match(node.expect("output_to called only after all matches are complete"))?;
        }

        Ok(())
    }
}

impl<'s, B, S> StackRecorder<'s, B, S>
where
    B: Deref<Target = [u8]>,
    S: Sink<Match>,
{
    fn record_block(&mut self, block: B) {
        if let Some(finished) = self.current_block.as_ref() {
            for node in &mut self.stack {
                debug!("Continuing node: {node:?}, idx is {}", self.idx);
                append_block(&mut node.buf, finished, self.idx, node.start_idx)
            }

            self.idx += finished.len();
        }

        self.current_block = Some(block);
        debug!("New block, idx = {}", self.idx);
    }

    fn record_match(&mut self, idx: usize, depth: Depth, ty: MatchedNodeType) {
        let node = PartialNode {
            id: self.match_count,
            start_idx: idx,
            start_depth: depth,
            buf: vec![],
            ty,
        };

        debug!("New node {node:?}");
        self.match_count += 1;
        self.stack.push(node);
    }

    #[inline]
    fn record_value_terminator(&mut self, idx: usize, depth: Depth) -> Result<(), EngineError> {
        debug!("Value terminator at {idx}, depth {depth}");
        while let Some(node) = self.stack.last() {
            if node.start_depth >= depth {
                debug!("Mark node {node:?} as ended at {}", idx + 1);
                let mut node = self.stack.pop().expect("last was Some, pop must succeed");
                append_final_block(
                    &mut node.buf,
                    self.current_block
                        .as_ref()
                        .ok_or(EngineError::MissingOpeningCharacter())?,
                    self.idx,
                    node.start_idx,
                    idx + 1,
                );
                finalize_node(&mut node.buf, node.ty);

                debug!("Committing node: {node:?}");
                self.output_queue.insert(
                    node.id,
                    Match {
                        bytes: node.buf,
                        span: MatchSpan {
                            start_idx: node.start_idx,
                            end_idx: idx + 1,
                        },
                    },
                );
            } else {
                break;
            }
        }

        if self.stack.is_empty() {
            debug!("Outputting batch of nodes.");
            self.output_queue
                .output_to(self.sink)
                .map_err(|err| EngineError::SinkError(Box::new(err)))?;
        }

        Ok(())
    }
}

#[inline(always)]
fn append_block(dest: &mut Vec<u8>, src: &[u8], src_start: usize, read_start: usize) {
    if read_start >= src_start + src.len() {
        return;
    }

    let to_extend = if read_start > src_start {
        let in_block_start = read_start - src_start;
        &src[in_block_start..]
    } else {
        src
    };

    dest.extend(to_extend);
}

#[inline(always)]
fn append_final_block(dest: &mut Vec<u8>, src: &[u8], src_start: usize, read_start: usize, read_end: usize) {
    debug_assert!(read_end >= src_start);
    let in_block_start = if read_start > src_start {
        read_start - src_start
    } else {
        0
    };
    let in_block_end = read_end - src_start;

    dest.extend(&src[in_block_start..in_block_end]);
}

#[inline(always)]
fn finalize_node(buf: &mut Vec<u8>, ty: MatchedNodeType) {
    debug!("Finalizing node");

    if ty == MatchedNodeType::Atomic {
        // Atomic nodes are finished when the next structural character is matched.
        // The buffer includes that character and all preceding whitespace.
        // We need to remove it before saving the result.
        let mut i = buf.len() - 2;
        while buf[i] == b' ' || buf[i] == b'\t' || buf[i] == b'\n' || buf[i] == b'\r' {
            i -= 1;
        }

        buf.truncate(i + 1);
    }
}

impl Debug for PartialNode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PartialNode")
            .field("start_idx", &self.start_idx)
            .field("start_depth", &self.start_depth)
            .field("ty", &self.ty)
            .field("buf", &str::from_utf8(&self.buf).unwrap_or("[invalid utf8]"))
            .finish()
    }
}