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
use std::ops::Range;

use crate::{
    context::Context, input::Input, lexer::Token, location::Location,
    parser::State,
};

/// [`Context`] implementation for LR parsing
#[derive(Debug)]
pub struct LRContext<'i, I: Input + ?Sized, S, TK> {
    position: usize,

    /// The range of token/non-terminal during shift/reduce operation.
    range: Range<usize>,

    /// Similar to position but has line/column format for text based inputs.
    ///
    /// If this prove to be pricey overhead we might make tracking of this info
    /// configurable.
    location: Location,

    /// Layout before the lookahead token (e.g. whitespaces, comments...)
    layout_ahead: Option<&'i I>,

    token_ahead: Option<Token<'i, I, TK>>,

    state: S,
}

impl<'i, I: Input + ?Sized, S: Default, TK> Default
    for LRContext<'i, I, S, TK>
{
    fn default() -> Self {
        Self::new(0)
    }
}

impl<'i, I: Input + ?Sized, S: Default, TK> LRContext<'i, I, S, TK> {
    pub fn new(position: usize) -> Self {
        Self {
            position,
            location: I::start_location(),
            layout_ahead: None,
            range: 0..0,
            token_ahead: None,
            state: S::default(),
        }
    }
}

impl<'i, I, S, TK> Context<'i, I, S, TK> for LRContext<'i, I, S, TK>
where
    I: Input + ?Sized,
    S: State,
{
    #[inline]
    fn state(&self) -> S {
        self.state
    }

    #[inline]
    fn set_state(&mut self, state: S) {
        self.state = state
    }

    #[inline]
    fn position(&self) -> usize {
        self.position
    }

    #[inline]
    fn set_position(&mut self, position: usize) {
        self.position = position
    }

    #[inline]
    fn location(&self) -> Location {
        self.location
    }

    #[inline]
    fn set_location(&mut self, location: Location) {
        self.location = location
    }

    #[inline]
    fn range(&self) -> Range<usize> {
        self.range.clone()
    }

    #[inline]
    fn set_range(&mut self, range: Range<usize>) {
        self.range = range
    }

    #[inline]
    fn token_ahead(&self) -> Option<&Token<'i, I, TK>> {
        self.token_ahead.as_ref()
    }

    #[inline]
    fn set_token_ahead(&mut self, token: Token<'i, I, TK>) {
        self.token_ahead = Some(token)
    }

    #[inline]
    fn layout_ahead(&self) -> Option<&'i I> {
        self.layout_ahead
    }

    #[inline]
    fn set_layout_ahead(&mut self, layout: Option<&'i I>) {
        self.layout_ahead = layout
    }
}