summaryrefslogtreecommitdiff
path: root/grammar/src/label.rs
blob: fd626cdbc497325c45ac3e37edd94f341a622265 (plain)
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
//! This file implements a type of labels that could be used as the
//! labels of a parse forest.

use super::*;

/// The actual label of a grammar label.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum GrammarLabelType {
    /// A terminal or a non-terminal.
    TNT(TNT),
    /// A rule position.
    Rule(usize),
}

impl Display for GrammarLabelType {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::TNT(tnt) => write!(f, "{tnt}"),
            Self::Rule(pos) => write!(f, "R({pos})"),
        }
    }
}

// Some convenient conversions

impl From<usize> for GrammarLabelType {
    #[inline]
    fn from(r: usize) -> Self {
        Self::Rule(r)
    }
}

impl From<TNT> for GrammarLabelType {
    #[inline]
    fn from(tnt: TNT) -> Self {
        Self::TNT(tnt)
    }
}

impl GrammarLabelType {
    /// Return the name of this label with the help of the associated
    /// grammar.
    #[inline]
    pub fn name(&self, grammar: &Grammar) -> Result<String, Error> {
        match self {
            Self::TNT(tnt) => grammar.name_of_tnt(*tnt),
            Self::Rule(pos) => grammar.rule_pos_to_string(*pos),
        }
    }

    /// Return the contained TNT, if any.
    #[inline]
    pub fn tnt(&self) -> Option<TNT> {
        match self {
            Self::TNT(tnt) => Some(*tnt),
            Self::Rule(_) => None,
        }
    }

    /// Return the contained rule position, if any.
    #[inline]
    pub fn rule(&self) -> Option<usize> {
        match self {
            Self::TNT(_) => None,
            Self::Rule(pos) => Some(*pos),
        }
    }
}

/// The label to be used in a forest.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct GrammarLabel {
    /// The actual label.
    label: GrammarLabelType,
    /// The start in the input that this label correponds to.
    start: usize,
    /// The end in the input that this label correponds to.
    end: Option<usize>,
}

impl core::fmt::Display for GrammarLabel {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{}, {}, {}",
            self.label,
            self.start,
            if let Some(end) = self.end {
                format!("{end}")
            } else {
                "ε".to_owned()
            }
        )
    }
}

impl GrammarLabel {
    /// Construct a new label.
    #[inline]
    pub fn new(label: impl Into<GrammarLabelType>, start: usize) -> Self {
        let label = label.into();
        let end = None;

        Self { label, start, end }
    }

    /// Construct a new label with an ending position.
    #[inline]
    pub fn new_closed(label: impl Into<GrammarLabelType>, start: usize, end: usize) -> Self {
        let label = label.into();
        let end = Some(end);

        Self { label, start, end }
    }

    /// Return the end in the input.
    #[inline]
    pub fn end(&self) -> Option<usize> {
        self.end
    }

    /// Set the start.
    #[inline]
    pub fn set_start(&mut self, pos: usize) {
        self.start = pos;
    }

    /// Return the start in the input.
    #[inline]
    pub fn start(&self) -> usize {
        self.start
    }

    /// Return the actual label.
    #[inline]
    pub fn label(&self) -> GrammarLabelType {
        self.label
    }

    /// Update the end.
    #[inline]
    pub fn set_end(&mut self, end: usize) {
        self.end = Some(end);
    }

    /// Set the end according to an option directly.
    #[inline]
    pub fn set_end_option(&mut self, end: Option<usize>) {
        self.end = end;
    }

    /// Return a string description with the help of the associated
    /// grammar.
    pub fn to_string(&self, grammar: &Grammar) -> Result<String, Error> {
        // First calculate the length of the resulting string.

        let mut num = 16 + 6;

        num += self.label().name(grammar)?.len();

        num += format!("{} ", self.start()).len();

        if let Some(end) = self.end() {
            num += format!("to {end}").len();
        } else {
            num += 7;
        }

        let num = num;

        let mut s = String::with_capacity(num);

        s.push_str("a node labelled ");

        s.push_str(&self.label().name(grammar)?);

        s.push_str(" from ");

        s.push_str(&format!("{} ", self.start()));

        if let Some(end) = self.end() {
            s.push_str(&format!("to {end}"));
        } else {
            s.push_str("onwards");
        }

        Ok(s)
    }
}