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
//! Last stage lexer declaration

use arrayvec::ArrayVec;

use crate::{
    lexer::{PreLexer, PreTextToken, PreToken as InputToken},
    util::LineMap,
};

mod token;
use lang_util::TextRange;
pub use token::Token;

pub type TextToken = crate::util::TextToken<token::Token>;

/// Final stage lexer.
///
/// This lexer wraps earlier stages and glues punctuation together to form (longest)
/// multi-character operator tokens. This is the entry point for lexing a pre-processor token
/// stream for the GLSL language.
#[derive(Debug, Clone)]
pub struct Lexer<'i> {
    input: PreLexer<'i>,
    /// Unglued token buffer. Since we're pasting at most 3 tokens together, and we always return
    /// one, we only need space for storing 2 pending tokens.
    buffer: ArrayVec<PreTextToken, 2>,
}

impl<'i> Lexer<'i> {
    pub fn new(input: &'i str) -> Self {
        Self {
            input: PreLexer::new(input),
            buffer: ArrayVec::new(),
        }
    }

    /// Get a reference to the input slice
    pub fn input(&self) -> &'i str {
        self.input.input()
    }

    /// Get a reference to the line map
    pub fn line_map(&self) -> &LineMap {
        self.input.line_map()
    }

    /// Consume this lexer and return the line map
    pub fn into_line_map(self) -> LineMap {
        self.input.into_line_map()
    }

    /// Notify the lexer we are parsing an #include directive, and it should expect the next `<`
    /// token to start an angle-quoted string.
    ///
    /// # Parameters
    ///
    /// * `expect_angle_string`: true if the lexer should expect a string, false otherwise
    pub fn set_expect_angle_string(&mut self, expect_angle_string: bool) {
        self.input.set_expect_angle_string(expect_angle_string)
    }

    fn next(&mut self) -> Option<PreTextToken> {
        self.buffer.pop().or_else(|| self.input.next())
    }

    fn maybe_concat(
        &mut self,
        token: PreTextToken,
        next: impl FnOnce(InputToken) -> Option<Token>,
    ) -> Option<TextToken> {
        if let Some(next_token) = self.next() {
            let result = next(*next_token);

            if let Some(result) = result {
                return Some(TextToken::new(
                    result,
                    TextRange::new(token.range.start(), next_token.range.end()),
                ));
            } else {
                // Put the token back into the buffer, it couldn't be combined
                self.buffer.push(next_token);
            }
        }

        Some(token.transmute())
    }

    fn maybe_concat2(
        &mut self,
        token: PreTextToken,
        next: impl FnOnce(InputToken) -> Option<Token>,
        after: impl FnOnce((InputToken, InputToken)) -> Option<Token>,
    ) -> Option<TextToken> {
        if let Some(next_token) = self.next() {
            // We have a 2nd token

            if let Some(after_token) = self.next() {
                // We have a 3rd token, try to combine the 3
                let result = after((*next_token, *after_token));

                if let Some(result) = result {
                    // We combined three tokens
                    return Some(TextToken::new(
                        result,
                        TextRange::new(token.range.start(), after_token.range.end()),
                    ));
                } else {
                    // We failed to combine three tokens, try to combine two and buffer the rest
                    self.buffer.push(after_token);
                    self.buffer.push(next_token);

                    return self.maybe_concat(token, next);
                }
            } else {
                // End of input, only 2 tokens
                // Push the token back into the buffer so maybe_concat can use it
                self.buffer.push(next_token);
                return self.maybe_concat(token, next);
            }
        }

        Some(token.transmute())
    }
}

impl<'i> Iterator for Lexer<'i> {
    type Item = TextToken;

    fn next(&mut self) -> Option<Self::Item> {
        use Token::*;

        let token = self.next();
        match token {
            Some(token) => match *token {
                InputToken::PLUS => self.maybe_concat(token, |input| match input {
                    InputToken::PLUS => Some(INC_OP),
                    InputToken::EQUAL => Some(ADD_ASSIGN),
                    _ => None,
                }),
                InputToken::DASH => self.maybe_concat(token, |input| match input {
                    InputToken::DASH => Some(DEC_OP),
                    InputToken::EQUAL => Some(SUB_ASSIGN),
                    _ => None,
                }),
                InputToken::SLASH => self.maybe_concat(token, |input| match input {
                    InputToken::EQUAL => Some(DIV_ASSIGN),
                    _ => None,
                }),
                InputToken::ASTERISK => self.maybe_concat(token, |input| match input {
                    InputToken::EQUAL => Some(MUL_ASSIGN),
                    _ => None,
                }),
                InputToken::PERCENT => self.maybe_concat(token, |input| match input {
                    InputToken::EQUAL => Some(MOD_ASSIGN),
                    _ => None,
                }),
                InputToken::LANGLE => self.maybe_concat2(
                    token,
                    |input| match input {
                        InputToken::LANGLE => Some(LEFT_OP),
                        InputToken::EQUAL => Some(LE_OP),
                        _ => None,
                    },
                    |input| match input {
                        (InputToken::LANGLE, InputToken::EQUAL) => Some(LEFT_ASSIGN),
                        _ => None,
                    },
                ),
                InputToken::RANGLE => self.maybe_concat2(
                    token,
                    |input| match input {
                        InputToken::RANGLE => Some(RIGHT_OP),
                        InputToken::EQUAL => Some(GE_OP),
                        _ => None,
                    },
                    |input| match input {
                        (InputToken::RANGLE, InputToken::EQUAL) => Some(RIGHT_ASSIGN),
                        _ => None,
                    },
                ),
                InputToken::CARET => self.maybe_concat(token, |input| match input {
                    InputToken::CARET => Some(XOR_OP),
                    InputToken::EQUAL => Some(XOR_ASSIGN),
                    _ => None,
                }),
                InputToken::BAR => self.maybe_concat(token, |input| match input {
                    InputToken::BAR => Some(OR_OP),
                    InputToken::EQUAL => Some(OR_ASSIGN),
                    _ => None,
                }),
                InputToken::AMPERSAND => self.maybe_concat(token, |input| match input {
                    InputToken::AMPERSAND => Some(AND_OP),
                    InputToken::EQUAL => Some(AND_ASSIGN),
                    _ => None,
                }),
                InputToken::EQUAL => self.maybe_concat(token, |input| match input {
                    InputToken::EQUAL => Some(EQ_OP),
                    _ => None,
                }),
                InputToken::BANG => self.maybe_concat(token, |input| match input {
                    InputToken::EQUAL => Some(NE_OP),
                    _ => None,
                }),
                InputToken::HASH => self.maybe_concat(token, |input| match input {
                    InputToken::HASH => Some(PP_CONCAT),
                    _ => None,
                }),
                InputToken::PERIOD => self.maybe_concat(token, |input| match input {
                    InputToken::DIGITS => Some(DIGITS),
                    _ => None,
                }),
                _ => Some(token.transmute()),
            },
            None => None,
        }
    }
}