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
557
558
559
560
561
562
pub mod parser;

// use std::hash::Hash;

use std::fmt::Debug;

use crate::{
    hashed::NodeHashs,
    // hashed::{inner_node_hash, SyntaxNodeHashs},
    nodes::Space,
    // utils::{self, clamp_u64_to_u32},
};
// use crate::nodes::SimpleNode1;

use self::parser::{Node as _, TreeCursor as _};

pub type Spaces = Vec<Space>;

/// Builder of a node for the hyperAST
pub trait Accumulator {
    type Node;
    fn push(&mut self, full_node: Self::Node);
}

pub struct BasicAccumulator<T, Id> {
    pub kind: T,
    pub children: Vec<Id>,
}

impl<T, Id> BasicAccumulator<T, Id> {
    pub fn new(kind: T) -> Self {
        Self {
            kind,
            children: vec![],
        }
    }
}

impl<T, Id> Accumulator for BasicAccumulator<T, Id> {
    type Node = Id;
    fn push(&mut self, node: Self::Node) {
        self.children.push(node);
    }
}

/// Builder of a node aware of its indentation for the hyperAST
pub trait AccIndentation: Accumulator {
    fn indentation<'a>(&'a self) -> &'a Spaces;
}

#[derive(Default, Debug, Clone, Copy)]
pub struct SubTreeMetrics<U: NodeHashs> {
    pub hashs: U,
    /// WIP make it space independent
    pub size: u32,
    /// WIP make it space independent, I believe is already is
    pub height: u32,

    pub size_no_spaces: u32,
}

impl<U: NodeHashs> SubTreeMetrics<U> {
    pub fn acc(&mut self, other: Self) {
        self.height = self.height.max(other.height);
        self.size += other.size;
        self.size_no_spaces += other.size_no_spaces;
        self.hashs.acc(&other.hashs);
    }
}

pub trait GlobalData {
    fn up(&mut self);
    fn right(&mut self);
    fn down(&mut self);
}

#[derive(Debug, Clone, Copy)]
pub struct BasicGlobalData {
    depth: usize,
    /// preorder position
    position: usize,
}

impl Default for BasicGlobalData {
    fn default() -> Self {
        Self {
            depth: 1,
            position: 0,
        }
    }
}

impl GlobalData for BasicGlobalData {
    fn up(&mut self) {
        self.depth -= 0;
    }

    fn right(&mut self) {
        self.position += 1;
    }

    /// goto the first children
    fn down(&mut self) {
        self.position += 1;
        self.depth += 1;
    }
}
pub trait TotalBytesGlobalData {
    fn set_sum_byte_length(&mut self, sum_byte_length: usize);
}

#[derive(Debug, Clone, Copy)]
pub struct TextedGlobalData<'a> {
    text: &'a [u8],
    inner: BasicGlobalData,
}

impl<'a> TextedGlobalData<'a> {
    pub fn new(inner: BasicGlobalData, text: &'a [u8]) -> Self {
        Self { text, inner }
    }
    pub fn text(self) -> &'a [u8] {
        self.text
    }
}

impl<'a> GlobalData for TextedGlobalData<'a> {
    fn up(&mut self) {
        self.inner.up();
    }

    fn right(&mut self) {
        self.inner.right();
    }

    /// goto the first children
    fn down(&mut self) {
        self.inner.down();
    }
}

#[derive(Debug, Clone, Copy)]
pub struct SpacedGlobalData<'a> {
    sum_byte_length: usize,
    inner: TextedGlobalData<'a>,
}
impl<'a> From<TextedGlobalData<'a>> for SpacedGlobalData<'a> {
    fn from(inner: TextedGlobalData<'a>) -> Self {
        Self {
            sum_byte_length: 0,
            inner,
        }
    }
}
impl<'a> From<SpacedGlobalData<'a>> for BasicGlobalData {
    fn from(x: SpacedGlobalData<'a>) -> Self {
        BasicGlobalData::from(x.inner)
    }
}
impl<'a> From<TextedGlobalData<'a>> for BasicGlobalData {
    fn from(x: TextedGlobalData<'a>) -> Self {
        BasicGlobalData::from(x.inner)
    }
}
impl<'a> From<&mut SpacedGlobalData<'a>> for BasicGlobalData {
    fn from(x: &mut SpacedGlobalData<'a>) -> Self {
        BasicGlobalData::from(x.inner)
    }
}
impl<'a> From<&mut TextedGlobalData<'a>> for BasicGlobalData {
    fn from(x: &mut TextedGlobalData<'a>) -> Self {
        BasicGlobalData::from(x.inner)
    }
}
impl<'a> SpacedGlobalData<'a> {
    pub fn sum_byte_length(self) -> usize {
        self.sum_byte_length
    }
}
impl<'a> TotalBytesGlobalData for SpacedGlobalData<'a> {
    fn set_sum_byte_length(&mut self, sum_byte_length: usize) {
        assert!(self.sum_byte_length <= sum_byte_length);
        self.sum_byte_length = sum_byte_length;
    }
}

impl<'a> GlobalData for SpacedGlobalData<'a> {
    fn up(&mut self) {
        self.inner.up();
    }

    fn right(&mut self) {
        self.inner.right();
    }

    /// goto the first children
    fn down(&mut self) {
        self.inner.down();
    }
}

pub trait TreeGen {
    type Acc: AccIndentation;
    type Global: GlobalData;
    fn make(
        &mut self,
        global: &mut Self::Global,
        acc: <Self as TreeGen>::Acc,
        label: Option<String>,
    ) -> <<Self as TreeGen>::Acc as Accumulator>::Node;
}

pub struct Parents<Acc>(Vec<Option<Acc>>);
impl<Acc> From<Acc> for Parents<Acc> {
    fn from(value: Acc) -> Self {
        Self::new(value)
    }
}
impl<Acc> Parents<Acc> {
    pub fn new(value: Acc) -> Self {
        Self(vec![Some(value)])
    }
    pub fn finalize(mut self) -> Acc {
        assert_eq!(self.0.len(), 1);
        self.0.pop().unwrap().unwrap()
    }
    fn push(&mut self, value: Option<Acc>) {
        self.0.push(value)
    }
    fn pop(&mut self) -> Option<Option<Acc>> {
        self.0.pop()
    }
    pub fn parent(&self) -> Option<&Acc> {
        self.0.iter().rev().find_map(|x| x.as_ref())
    }
    fn parent_mut(&mut self) -> Option<&mut Acc> {
        self.0.iter_mut().rev().find_map(|x| x.as_mut())
    }
}

pub trait ZippedTreeGen: TreeGen
where
    Self::Global: TotalBytesGlobalData,
{
    // # results
    // type Node1;
    type Stores;
    // # source
    type Text: ?Sized;
    type Node<'a>: parser::Node<'a>;
    type TreeCursor<'a>: parser::TreeCursor<'a, Self::Node<'a>> + Debug;

    fn init_val(&mut self, text: &Self::Text, node: &Self::Node<'_>) -> Self::Acc;

    fn pre_skippable(
        &mut self,
        text: &Self::Text,
        node: &Self::Node<'_>,
        stack: &Parents<Self::Acc>,
        global: &mut Self::Global,
        skip: &mut bool,
    ) -> Option<<Self as TreeGen>::Acc> {
        let _ = skip;
        Some(self.pre(text, node, stack, global))
    }

    fn pre(
        &mut self,
        text: &Self::Text,
        node: &Self::Node<'_>,
        // TODO make a special wrapper for the Vec<Option<_>>
        stack: &Parents<Self::Acc>,
        global: &mut Self::Global,
    ) -> <Self as TreeGen>::Acc;

    fn post(
        &mut self,
        parent: &mut <Self as TreeGen>::Acc,
        global: &mut Self::Global,
        text: &Self::Text,
        acc: <Self as TreeGen>::Acc,
    ) -> <<Self as TreeGen>::Acc as Accumulator>::Node;

    fn stores(&mut self) -> &mut Self::Stores;

    fn gen(
        &mut self,
        text: &Self::Text,
        stack: &mut Parents<Self::Acc>,
        cursor: &mut Self::TreeCursor<'_>,
        global: &mut Self::Global,
    ) {
        let mut has = Has::Down;
        loop {
            // dbg!(&cursor, stack.0.len());
            let sbl = cursor.node().start_byte();
            if has != Has::Up && cursor.goto_first_child() {
                global.set_sum_byte_length(sbl);
                has = Has::Down;
                global.down();
                let mut skip = false;
                let n = self.pre_skippable(text, &cursor.node(), &stack, global, &mut skip);
                if skip {
                    assert!(n.is_some());
                    has = Has::Up;
                }

                stack.push(n);
            } else {
                let acc = stack.pop().unwrap();
                let is_visible = acc.is_some();
                if is_visible {
                    global.up();
                }
                let full_node: Option<_> = if let Some(parent) = stack.parent_mut() {
                    acc.map(|acc| self.post(parent, global, text, acc))
                } else {
                    stack.push(acc);
                    None
                };

                // TODO opt out of using end_byte other than on leafs,
                // it should help with trailing spaces,
                // something like `cursor.node().child_count().ne(0).then(||cursor.node().end_byte())` then just call set_sum_byte_length if some
                let sbl = cursor.node().end_byte();
                if cursor.goto_next_sibling() {
                    global.set_sum_byte_length(sbl);
                    has = Has::Right;
                    let parent = stack.parent_mut().unwrap();
                    if let Some(full_node) = full_node {
                        parent.push(full_node);
                    }
                    global.down();
                    let mut skip = false;
                    let n = self.pre_skippable(text, &cursor.node(), &stack, global, &mut skip);
                    if skip {
                        has = Has::Up;
                    }
                    stack.push(n);
                } else {
                    has = Has::Up;
                    if cursor.goto_parent() {
                        if let Some(full_node) = full_node {
                            global.set_sum_byte_length(sbl);
                            let parent = stack.parent_mut().unwrap();
                            parent.push(full_node);
                        } else if is_visible {
                            if has == Has::Down {
                                global.set_sum_byte_length(sbl);
                            }
                            return;
                        }
                    } else {
                        if has == Has::Down {
                            global.set_sum_byte_length(sbl);
                        }
                        return;
                    }
                }
            }
        }
    }
}

#[derive(PartialEq, Eq)]
enum Has {
    Down,
    Up,
    Right,
}

pub(crate) fn things_after_last_lb<'b>(lb: &[u8], spaces: &'b [u8]) -> Option<&'b [u8]> {
    spaces
        .windows(lb.len())
        .rev()
        .position(|window| window == lb)
        .and_then(|i| Some(&spaces[spaces.len() - i - 1..]))
}

// pub fn hash_for_node<T: Hash, U>(
//     hashs: &SyntaxNodeHashs<u32>,
//     size: u32,
//     node: &SimpleNode1<U, T>,
// ) -> SyntaxNodeHashs<u32> {
//     let hashed_kind = clamp_u64_to_u32(&utils::hash(&node.kind));
//     let hashed_label = clamp_u64_to_u32(&utils::hash(&node.label));
//     SyntaxNodeHashs {
//         structt: inner_node_hash(hashed_kind, 0, size, hashs.structt),
//         label: inner_node_hash(hashed_kind, hashed_label, size, hashs.label),
//         syntax: inner_node_hash(hashed_kind, hashed_label, size, hashs.syntax),
//     }
// }

pub fn compute_indentation<'a>(
    line_break: &Vec<u8>,
    text: &'a [u8],
    pos: usize,
    padding_start: usize,
    parent_indentation: &'a [Space],
) -> Vec<Space> {
    let spaces = { &text[padding_start..pos] };
    let spaces_after_lb = things_after_last_lb(&*line_break, spaces);
    match spaces_after_lb {
        Some(s) => Space::format_indentation(s),
        None => parent_indentation.to_vec(),
    }
}

pub fn try_compute_indentation<'a>(
    line_break: &Vec<u8>,
    text: &'a [u8],
    pos: usize,
    padding_start: usize,
    parent_indentation: &'a [Space],
) -> Vec<Space> {
    let spaces = { &text[padding_start..pos] };
    let spaces_after_lb = things_after_last_lb(&*line_break, spaces);
    match spaces_after_lb {
        Some(s) => Space::try_format_indentation(s).unwrap_or(parent_indentation.to_vec()),
        None => parent_indentation.to_vec(),
    }
}

// pub fn handle_spacing<
//     NS: NodeStore<HashedCompressedNode<SyntaxNodeHashs<u32>>>,
//     Acc: AccIndentation<Node = FullNode<Global, Local>>,
// >(
//     padding_start: usize,
//     pos: usize,
//     text: &[u8],
//     node_store: &mut NS,
//     depth: &usize,
//     position: usize,
//     parent: &mut Acc,
// ) {
//     let tmp = get_spacing(padding_start, pos, text, parent.indentation());
//     if let Some(relativized) = tmp {
//         let hashs = SyntaxNodeHashs {
//             structt: 0,
//             label: 0,
//             syntax: clamp_u64_to_u32(&utils::hash(&relativized)),
//         };
//         let node = CompressedNode::Spaces(relativized.into_boxed_slice());
//         let spaces_leaf = HashedCompressedNode::new(hashs, node);
//         let compressed_node = node_store.get_id_or_insert_node(spaces_leaf);
//         let full_spaces_node = FullNode {
//             global: Global {
//                 depth: *depth,
//                 position,
//             },
//             local: Local {
//                 compressed_node,
//                 metrics: SubTreeMetrics {
//                     size: 1,
//                     height: 1,
//                     hashs,
//                 },
//             },
//         };
//         parent.push(full_spaces_node);
//     };
// }

pub fn get_spacing(
    padding_start: usize,
    pos: usize,
    text: &[u8],
    _parent_indentation: &Spaces,
) -> Option<Vec<u8>> {
    // TODO change debug assert to assert if you want to strictly enforce spaces, issues with other char leaking is often caused by "bad" grammar.
    if padding_start != pos {
        let spaces = &text[padding_start..pos];
        // let spaces = Space::format_indentation(spaces);
        let mut bslash = false;
        spaces.iter().for_each(|x| {
            if bslash && (*x == b'\n' || *x == b'\r') {
                bslash = false
            } else if *x == b'\\' {
                debug_assert!(!bslash);
                bslash = true
            } else {
                debug_assert!(
                    *x == b' ' || *x == b'\n' || *x == b'\t' || *x == b'\r',
                    "{} {} {:?}",
                    x,
                    padding_start,
                    std::str::from_utf8(&spaces).unwrap()
                )
            }
        });
        debug_assert!(
            !bslash,
            "{}",
            std::str::from_utf8(&&text[padding_start.saturating_sub(100)..pos + 50]).unwrap()
        );
        let spaces = spaces.to_vec();
        // let spaces = Space::replace_indentation(parent_indentation, &spaces);
        // TODO put back the relativisation later, can pose issues when computing len of a subtree (contextually if we make the optimisation)
        Some(spaces)
    } else {
        None
    }
}

pub fn try_get_spacing(
    padding_start: usize,
    pos: usize,
    text: &[u8],
    _parent_indentation: &Spaces,
) -> Option<Vec<u8>> {
    // ) -> Option<Spaces> {
    if padding_start != pos {
        let spaces = &text[padding_start..pos];
        // println!("{:?}",std::str::from_utf8(spaces).unwrap());
        if spaces
            .iter()
            .find(|&x| *x != b' ' && *x != b'\n' && *x != b'\t' && *x != b'\r')
            .is_some()
        {
            return None;
        }
        let spaces = spaces.to_vec();

        // let spaces = Space::try_format_indentation(spaces)?;
        // let spaces = Space::replace_indentation(parent_indentation, &spaces);
        // TODO put back the relativisation later, can pose issues when computing len of a subtree (contextually if we make the optimisation)
        Some(spaces)
    } else {
        None
    }
}

pub fn has_final_space(depth: &usize, sum_byte_length: usize, text: &[u8]) -> bool {
    // TODO not sure about depth
    *depth == 0 && sum_byte_length < text.len()
}

// /// end of tree but not end of file,
// /// thus to be a bijection, we need to get the last spaces
// pub fn handle_final_space<
//     NS: NodeStore<HashedCompressedNode<SyntaxNodeHashs<u32>>>,
//     Acc: AccIndentation<Node = FullNode<Global, Local>>,
// >(
//     depth: &usize,
//     sum_byte_length: usize,
//     text: &[u8],
//     node_store: &mut NS,
//     position: usize,
//     parent: &mut Acc,
// ) {
//     if has_final_space(depth, sum_byte_length, text) {
//         handle_spacing(
//             sum_byte_length,
//             text.len(),
//             text,
//             node_store,
//             depth,
//             position,
//             parent,
//         )
//     }
// }