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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
/*******************************************************************************
 * Copyright (c) 2017 Association Cénotélie (cenotelie.fr)
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/

//! Module for Abstract-Syntax Trees

use alloc::fmt::{Display, Error, Formatter};
use core::iter::FusedIterator;

use serde::ser::{Serialize, SerializeSeq, SerializeStruct, Serializer};

use crate::symbols::{SemanticElementTrait, Symbol};
use crate::text::{TextContext, TextPosition, TextSpan};
use crate::tokens::{Token, TokenRepository};
use crate::utils::biglist::BigList;
use crate::utils::EitherMut;

/// Represents a type of symbol table
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum TableType {
    /// Marks as other (used for SPPF nodes)
    None = 0,
    /// Table of tokens
    Token = 1,
    /// Table of variables
    Variable = 2,
    /// Tables of virtuals
    Virtual = 3
}

impl From<usize> for TableType {
    fn from(x: usize) -> Self {
        match x {
            1 => TableType::Token,
            2 => TableType::Variable,
            3 => TableType::Virtual,
            _ => TableType::None
        }
    }
}

/// Represents a compact reference to an element in a table
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
pub struct TableElemRef {
    /// The backend data
    data: usize
}

impl TableElemRef {
    /// Initializes this reference
    #[must_use]
    pub fn new(t: TableType, index: usize) -> TableElemRef {
        TableElemRef {
            data: ((t as usize) << 30) | index
        }
    }

    /// Gets the element's type
    #[must_use]
    pub fn table_type(self) -> TableType {
        TableType::from(self.data >> 30)
    }

    /// Gets the element's index in its respective table
    #[must_use]
    pub fn index(self) -> usize {
        self.data & 0x3FFF_FFFF
    }
}

/// Represents a cell in an AST inner structure
#[derive(Debug, Default, Copy, Clone)]
pub struct AstCell {
    /// The node's label
    pub label: TableElemRef,
    /// The number of children
    pub count: u32,
    /// The index of the first child
    pub first: u32
}

impl AstCell {
    /// Initializes this node
    #[must_use]
    pub fn new_empty(label: TableElemRef) -> AstCell {
        AstCell {
            label,
            count: 0,
            first: 0
        }
    }

    /// Initializes this node
    #[must_use]
    pub fn new(label: TableElemRef, count: u32, first: u32) -> AstCell {
        AstCell {
            label,
            count,
            first
        }
    }
}

/// Implementation of a simple AST with a tree structure
/// The nodes are stored in sequential arrays where the children of a node are an inner sequence.
/// The linkage is represented by each node storing its number of children and the index of its first child.
#[derive(Debug, Default, Clone)]
pub struct AstImpl {
    /// The nodes' labels
    nodes: BigList<AstCell>,
    /// The index of the tree's root node
    root: Option<usize>
}

impl AstImpl {
    /// Gets whether a root has been defined for this AST
    #[must_use]
    pub fn has_root(&self) -> bool {
        self.root.is_some()
    }
}

/// Represents a simple AST with a tree structure
/// The nodes are stored in sequential arrays where the children of a node are an inner sequence.
/// The linkage is represented by each node storing its number of children and the index of its first child.
pub struct Ast<'s, 't, 'a> {
    /// The table of tokens
    tokens: Option<TokenRepository<'s, 't, 'a>>,
    /// The table of variables
    pub variables: &'a [Symbol<'s>],
    /// The table of virtuals
    pub virtuals: &'a [Symbol<'s>],
    /// The data of the implementation
    data: EitherMut<'a, AstImpl>
}

impl<'s, 't, 'a> Ast<'s, 't, 'a> {
    /// Creates a new AST proxy structure
    #[must_use]
    pub fn new(
        tokens: TokenRepository<'s, 't, 'a>,
        variables: &'a [Symbol<'s>],
        virtuals: &'a [Symbol<'s>],
        data: &'a AstImpl
    ) -> Ast<'s, 't, 'a> {
        Ast {
            tokens: Some(tokens),
            variables,
            virtuals,
            data: EitherMut::Immutable(data)
        }
    }

    /// Creates a new AST proxy structure
    pub fn new_mut(
        variables: &'a [Symbol<'s>],
        virtuals: &'a [Symbol<'s>],
        data: &'a mut AstImpl
    ) -> Ast<'s, 't, 'a> {
        Ast {
            tokens: None,
            variables,
            virtuals,
            data: EitherMut::Mutable(data)
        }
    }

    /// Gets the i-th token in the associated repository
    fn get_token(&'a self, index: usize) -> Token<'s, 't, 'a> {
        self.tokens
            .as_ref()
            .expect("Missing token repository")
            .get_token(index)
    }

    /// Gets whether a root has been defined for this AST
    #[must_use]
    pub fn has_root(&self) -> bool {
        self.data.has_root()
    }

    /// Gets the root node of this tree
    ///
    /// # Panics
    ///
    /// Raise a panic when the AST has no root.
    /// This can happen when a `ParseResult` contains some errors,
    /// but the AST `get_ast` is called to get an AST but it will have not root.
    #[must_use]
    pub fn get_root(&self) -> AstNode {
        self.data
            .root
            .map(|x| AstNode {
                tree: self,
                index: x
            })
            .expect("No root defined!")
    }

    /// Gets a specific node in this tree
    #[must_use]
    pub fn get_node(&self, id: usize) -> AstNode {
        AstNode {
            tree: self,
            index: id
        }
    }

    /// Gets the AST node (if any) that has the specified token as label
    #[must_use]
    pub fn find_node_for(&self, token: &Token) -> Option<AstNode> {
        self.data
            .nodes
            .iter()
            .enumerate()
            .find(|(_, node)| {
                node.label.table_type() == TableType::Token && node.label.index() == token.index
            })
            .map(|(index, _)| AstNode { tree: self, index })
    }

    /// Gets the AST node (if any) that has
    /// a token label that contains the specified index in the input text
    #[must_use]
    pub fn find_node_at_index(&self, index: usize) -> Option<AstNode> {
        self.tokens
            .as_ref()?
            .find_token_at(index)
            .and_then(|token| self.find_node_for(&token))
    }

    /// Gets the AST node (if any) that has
    /// a token label that contains the specified index in the input text
    #[must_use]
    pub fn find_node_at_position(&self, position: TextPosition) -> Option<AstNode> {
        let tokens = self.tokens.as_ref()?;
        let index = tokens.text.get_line_index(position.line) + position.column - 1;
        tokens
            .find_token_at(index)
            .and_then(|token| self.find_node_for(&token))
    }

    /// Gets the parent of the specified node, if any
    #[must_use]
    pub fn find_parent_of(&'a self, node: usize) -> Option<AstNode<'s, 't, 'a>> {
        // self.data.root?;
        self.data
            .nodes
            .iter()
            .enumerate()
            .find(|(_, candidate)| {
                candidate.count > 0
                    && node >= candidate.first as usize
                    && node < (candidate.first + candidate.count) as usize
            })
            .map(|(index, _)| AstNode { tree: self, index })
    }

    /// Gets the total span of sub-tree given its root and its position
    #[must_use]
    pub fn get_total_position_and_span(&self, node: usize) -> Option<(TextPosition, TextSpan)> {
        let mut total_span: Option<TextSpan> = None;
        let mut position = TextPosition {
            line: usize::MAX,
            column: usize::MAX
        };
        self.traverse(node, |data, current| {
            if let Some(p) = self.get_position_at(data, current) {
                if p < position {
                    position = p;
                }
            }
            if let Some(total_span) = total_span.as_mut() {
                if let Some(span) = self.get_span_at(data, current) {
                    if span.index + span.length > total_span.index + total_span.length {
                        let margin =
                            (span.index + span.length) - (total_span.index + total_span.length);
                        total_span.length += margin;
                    }
                    if span.index < total_span.index {
                        let margin = total_span.index - span.index;
                        total_span.length += margin;
                        total_span.index -= margin;
                    }
                }
            } else {
                total_span = self.get_span_at(data, current);
            }
        });
        total_span.map(|span| (position, span))
    }

    /// Gets the total span of sub-tree given its root
    #[must_use]
    pub fn get_total_span(&self, node: usize) -> Option<TextSpan> {
        self.get_total_position_and_span(node).map(|(_, span)| span)
    }

    /// Traverses the AST from the specified node
    fn traverse<F: FnMut(&AstImpl, usize)>(&self, from: usize, mut action: F) {
        let mut stack = alloc::vec![from];
        while let Some(current) = stack.pop() {
            let cell = self.data.nodes[current];
            for i in (0..cell.count).rev() {
                stack.push((cell.first + i) as usize);
            }
            action(&self.data, current);
        }
    }

    /// Get the span of the symbol on a node
    #[must_use]
    fn get_span_at(&self, data: &AstImpl, node: usize) -> Option<TextSpan> {
        let cell = data.nodes[node];
        match cell.label.table_type() {
            TableType::Token => {
                let token = self.get_token(cell.label.index());
                token.get_span()
            }
            _ => None
        }
    }

    /// Get the position of the symbol on a node
    #[must_use]
    fn get_position_at(&self, data: &AstImpl, node: usize) -> Option<TextPosition> {
        let cell = data.nodes[node];
        match cell.label.table_type() {
            TableType::Token => {
                let token = self.get_token(cell.label.index());
                token.get_position()
            }
            _ => None
        }
    }

    /// Stores some children nodes in this AST
    pub fn store(&mut self, nodes: &[AstCell], index: usize, count: usize) -> usize {
        if count == 0 {
            0
        } else {
            let result = self.data.nodes.push(nodes[index]);
            for i in 1..count {
                self.data.nodes.push(nodes[index + i]);
            }
            result
        }
    }

    /// Stores the root of this tree
    pub fn store_root(&mut self, node: AstCell) {
        self.data.root = Some(self.data.nodes.push(node));
    }
}

/// Represents a node in an Abstract Syntax Tree
#[derive(Copy, Clone)]
pub struct AstNode<'s, 't, 'a> {
    /// The original parse tree
    tree: &'a Ast<'s, 't, 'a>,
    /// The index of this node in the parse tree
    index: usize
}

impl<'s, 't, 'a> AstNode<'s, 't, 'a> {
    /// Gets the identifier of this node
    #[must_use]
    pub fn id(&self) -> usize {
        self.index
    }

    /// Gets the index of the token born by this node, if any
    #[must_use]
    pub fn get_token_index(&self) -> Option<usize> {
        let cell = self.tree.data.nodes[self.index];
        match cell.label.table_type() {
            TableType::Token => Some(cell.label.index()),
            _ => None
        }
    }

    /// Gets the parent of this node, if any
    #[must_use]
    pub fn parent(&self) -> Option<AstNode<'s, 't, 'a>> {
        self.tree.find_parent_of(self.index)
    }

    /// Gets the children of this node
    #[must_use]
    pub fn children(&self) -> AstFamily<'s, 't, 'a> {
        AstFamily {
            tree: self.tree,
            parent: self.index
        }
    }

    /// Gets the i-th child
    #[must_use]
    pub fn child(&self, index: usize) -> AstNode<'s, 't, 'a> {
        let cell = self.tree.data.nodes[self.index];
        AstNode {
            tree: self.tree,
            index: cell.first as usize + index
        }
    }

    /// Gets the number of children
    #[must_use]
    pub fn children_count(&self) -> usize {
        self.tree.data.nodes[self.index].count as usize
    }

    /// Gets the total span for the sub-tree at this node
    #[must_use]
    pub fn get_total_span(&self) -> Option<TextSpan> {
        self.tree.get_total_span(self.index)
    }

    /// Gets the total position and span for the sub-tree at this node
    #[must_use]
    pub fn get_total_position_and_span(&self) -> Option<(TextPosition, TextSpan)> {
        self.tree.get_total_position_and_span(self.index)
    }
}

impl<'s, 't, 'a> SemanticElementTrait<'s, 'a> for AstNode<'s, 't, 'a> {
    /// Gets the position in the input text of this element
    fn get_position(&self) -> Option<TextPosition> {
        self.tree.get_position_at(&self.tree.data, self.index)
    }

    /// Gets the span in the input text of this element
    fn get_span(&self) -> Option<TextSpan> {
        self.tree.get_span_at(&self.tree.data, self.index)
    }

    /// Gets the context of this element in the input
    fn get_context(&self) -> Option<TextContext<'a>> {
        let cell = self.tree.data.nodes[self.index];
        match cell.label.table_type() {
            TableType::Token => {
                let token = self.tree.get_token(cell.label.index());
                token.get_context()
            }
            _ => None
        }
    }

    /// Gets the grammar symbol associated to this element
    fn get_symbol(&self) -> Symbol<'s> {
        let cell = self.tree.data.nodes[self.index];
        match cell.label.table_type() {
            TableType::Token => {
                let token = self.tree.get_token(cell.label.index());
                token.get_symbol()
            }
            TableType::Variable => self.tree.variables[cell.label.index()],
            TableType::Virtual => self.tree.virtuals[cell.label.index()],
            TableType::None => {
                match &self.tree.tokens {
                    None => panic!("Missing token repository"),
                    Some(repository) => repository.terminals[0] // terminal epsilon
                }
            }
        }
    }

    /// Gets the value of this element, if any
    fn get_value(&self) -> Option<&'a str> {
        let cell = self.tree.data.nodes[self.index];
        match cell.label.table_type() {
            TableType::Token => {
                let token = self.tree.get_token(cell.label.index());
                token.get_value()
            }
            _ => None
        }
    }
}

impl<'s, 't, 'a> PartialEq<AstNode<'s, 't, 'a>> for AstNode<'s, 't, 'a> {
    fn eq(&self, other: &AstNode<'s, 't, 'a>) -> bool {
        self.index == other.index
    }
}

impl<'s, 't, 'a> Eq for AstNode<'s, 't, 'a> {}

impl<'s, 't, 'a> IntoIterator for AstNode<'s, 't, 'a> {
    type Item = AstNode<'s, 't, 'a>;
    type IntoIter = AstFamilyIterator<'s, 't, 'a>;

    fn into_iter(self) -> Self::IntoIter {
        let cell = self.tree.data.nodes[self.index];
        AstFamilyIterator {
            tree: self.tree,
            current: cell.first as usize,
            end: (cell.first + cell.count) as usize
        }
    }
}

impl<'s, 't, 'a> Display for AstNode<'s, 't, 'a> {
    fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
        let cell = self.tree.data.nodes[self.index];
        match cell.label.table_type() {
            TableType::Token => {
                let token = self.tree.get_token(cell.label.index());
                let symbol = token.get_symbol();
                let value = token.get_value();
                write!(f, "{} = {}", symbol.name, value.unwrap())
            }
            TableType::Variable => {
                let symbol = self.tree.variables[cell.label.index()];
                write!(f, "{}", symbol.name)
            }
            TableType::Virtual => {
                let symbol = self.tree.virtuals[cell.label.index()];
                write!(f, "{}", symbol.name)
            }
            TableType::None => match &self.tree.tokens {
                None => panic!("Missing token repository"),
                Some(repository) => {
                    let symbol = repository.terminals[0];
                    write!(f, "{}", symbol.name)
                }
            }
        }
    }
}

impl<'s, 't, 'a> Serialize for AstNode<'s, 't, 'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer
    {
        let mut state = serializer.serialize_struct("AstNode", 5)?;
        state.serialize_field("symbol", &self.get_symbol())?;
        state.serialize_field("position", &self.get_position())?;
        state.serialize_field("span", &self.get_span())?;
        state.serialize_field("value", &self.get_value())?;
        state.serialize_field("children", &self.children())?;
        state.end()
    }
}

/// Represents a family of children for an `ASTNode`
#[derive(Clone)]
pub struct AstFamily<'s, 't, 'a> {
    /// The original parse tree
    tree: &'a Ast<'s, 't, 'a>,
    /// The index of the parent node in the parse tree
    parent: usize
}

/// Represents and iterator for adjacents in this graph
pub struct AstFamilyIterator<'s, 't, 'a> {
    /// The original parse tree
    tree: &'a Ast<'s, 't, 'a>,
    /// The index of the current child in the parse tree
    current: usize,
    /// the index of the last child (excluded) in the parse tree
    end: usize
}

/// Implementation of the `Iterator` trait for `AstFamilyIterator`
impl<'s, 't, 'a> Iterator for AstFamilyIterator<'s, 't, 'a> {
    type Item = AstNode<'s, 't, 'a>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.current >= self.end {
            None
        } else {
            let result = AstNode {
                tree: self.tree,
                index: self.current
            };
            self.current += 1;
            Some(result)
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let c = self.end - self.current;
        (c, Some(c))
    }
}

impl<'s, 't, 'a> DoubleEndedIterator for AstFamilyIterator<'s, 't, 'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.current >= self.end {
            None
        } else {
            let result = AstNode {
                tree: self.tree,
                index: self.end - 1
            };
            self.end -= 1;
            Some(result)
        }
    }
}

impl<'s, 't, 'a> ExactSizeIterator for AstFamilyIterator<'s, 't, 'a> {}
impl<'s, 't, 'a> FusedIterator for AstFamilyIterator<'s, 't, 'a> {}

impl<'s, 't, 'a> IntoIterator for AstFamily<'s, 't, 'a> {
    type Item = AstNode<'s, 't, 'a>;
    type IntoIter = AstFamilyIterator<'s, 't, 'a>;

    fn into_iter(self) -> Self::IntoIter {
        let cell = self.tree.data.nodes[self.parent];
        AstFamilyIterator {
            tree: self.tree,
            current: cell.first as usize,
            end: (cell.first + cell.count) as usize
        }
    }
}

impl<'s, 't, 'a> AstFamily<'s, 't, 'a> {
    /// Gets whether the family is empty
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.tree.data.nodes[self.parent].count == 0
    }

    /// Gets the number of children in this family
    #[must_use]
    pub fn len(&self) -> usize {
        self.tree.data.nodes[self.parent].count as usize
    }

    /// Gets the i-th child
    #[must_use]
    pub fn at(&self, index: usize) -> AstNode<'s, 't, 'a> {
        let cell = self.tree.data.nodes[self.parent];
        AstNode {
            tree: self.tree,
            index: cell.first as usize + index
        }
    }

    /// Gets an iterator over this family
    #[must_use]
    pub fn iter(&self) -> AstFamilyIterator<'s, 't, 'a> {
        let cell = self.tree.data.nodes[self.parent];
        AstFamilyIterator {
            tree: self.tree,
            current: cell.first as usize,
            end: (cell.first + cell.count) as usize
        }
    }
}

impl<'s, 't, 'a> Serialize for AstFamily<'s, 't, 'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer
    {
        let mut seq = serializer.serialize_seq(Some(self.len()))?;
        for node in self.iter() {
            seq.serialize_element(&node)?;
        }
        seq.end()
    }
}