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
//! Filesystem based glsl-lang-pp preprocessing lexer

use std::path::{Path, PathBuf};

use lang_util::position::LexerPosition;

use glsl_lang_pp::{
    exts::{Registry, DEFAULT_REGISTRY},
    last::{self, Event},
    processor::{
        fs::{ExpandStack, ParsedFile, Processor},
        ProcessorState,
    },
};

use crate::{HasLexerError, LangLexer, LangLexerIterator, ParseContext, ParseOptions, Token};

use super::{
    core::{self, HandleTokenResult, LexerCore},
    Directives, LexicalError,
};

pub use glsl_lang_pp::processor::fs::FileSystem;

/// glsl-lang-pp filesystem lexer
pub struct Lexer<'r, 'p, F: FileSystem> {
    inner: last::Tokenizer<'r, ExpandStack<'p, F>>,
    current_file: PathBuf,
    handle_token: HandleTokenResult<F::Error>,
    opts: ParseOptions,
}

impl<'r, 'p, F: FileSystem> Lexer<'r, 'p, F> {
    fn new(inner: ExpandStack<'p, F>, registry: &'r Registry, opts: &ParseOptions) -> Self {
        Self {
            inner: inner.tokenize(opts.default_version, opts.target_vulkan, registry),
            current_file: Default::default(),
            handle_token: Default::default(),
            opts: *opts,
        }
    }

    fn with_context(self, ctx: ParseContext) -> LexerIterator<'r, 'p, F> {
        LexerIterator {
            inner: self.inner,
            core: LexerCore::new(&self.opts, ctx),
            current_file: self.current_file,
            handle_token: self.handle_token,
        }
    }
}

/// glsl-lang-pp filesystem lexer iterator
pub struct LexerIterator<'r, 'p, F: FileSystem> {
    inner: last::Tokenizer<'r, ExpandStack<'p, F>>,
    core: LexerCore,
    current_file: PathBuf,
    handle_token: HandleTokenResult<F::Error>,
}

impl<F: FileSystem> LexerIterator<'_, '_, F> {
    pub fn into_directives(self) -> Directives {
        self.core.into_directives()
    }
}

impl<'r, 'p, F: FileSystem> Iterator for LexerIterator<'r, 'p, F> {
    type Item = core::Item<F::Error>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            // Pop pending events
            if let Some(item) = self.handle_token.pop_item() {
                return Some(item);
            }

            if let Some(result) = self.handle_token.pop_event().or_else(|| self.inner.next()) {
                match result {
                    Ok(event) => match event {
                        Event::Error { error, masked } => {
                            if !masked {
                                return Some(Err(error.into()));
                            }
                        }

                        Event::Token {
                            source_token,
                            token_kind,
                            state,
                        } => {
                            self.core.handle_token(
                                source_token,
                                token_kind,
                                state,
                                &mut self.inner,
                                &mut self.handle_token,
                            );
                        }

                        Event::Directive { directive, masked } => {
                            if let Err(errors) = self.core.handle_directive(directive, masked) {
                                self.handle_token.push_errors(errors);
                            }
                        }

                        Event::EnterFile {
                            file_id,
                            path,
                            canonical_path: _,
                        } => {
                            self.current_file = path;
                            self.core.handle_file_id(file_id);
                        }
                    },

                    Err(err) => {
                        return Some(Err(LexicalError::Io(err)));
                    }
                }
            } else {
                return None;
            }
        }
    }
}

impl<F: FileSystem> HasLexerError for Lexer<'_, '_, F> {
    type Error = LexicalError<F::Error>;
}

impl<'r, 'p, F: FileSystem> LangLexer<'p> for Lexer<'r, 'p, F>
where
    File<'r, 'p, F>: 'p,
{
    type Input = File<'r, 'p, F>;
    type Iter = LexerIterator<'r, 'p, F>;

    fn new(source: Self::Input, opts: &ParseOptions) -> Self {
        Lexer::new(
            source.inner.process(source.state.unwrap_or_default()),
            source.registry.unwrap_or(&DEFAULT_REGISTRY),
            opts,
        )
    }

    fn run(self, ctx: ParseContext) -> Self::Iter {
        self.with_context(ctx)
    }
}

impl<F: FileSystem> HasLexerError for LexerIterator<'_, '_, F> {
    type Error = LexicalError<F::Error>;
}

impl<'r, 'p, F: FileSystem> LangLexerIterator for LexerIterator<'r, 'p, F> {
    fn resolve_err(
        &self,
        err: lalrpop_util::ParseError<LexerPosition, Token, Self::Error>,
    ) -> lang_util::error::ParseError<Self::Error> {
        let location = self.inner.location();
        let (file_id, lexer) = lang_util::error::error_location(&err);

        lang_util::error::ParseError::<Self::Error>::builder()
            .pos(lexer)
            .current_file(file_id)
            .resolve(location)
            .resolve_path(&self.inner)
            .finish(err.into())
    }
}

/// glsl-lang-pp preprocessor extensions
pub trait PreprocessorExt<F: FileSystem> {
    /// Open the given file for lexing
    ///
    /// # Parameters
    ///
    /// * `path`: path to the file to open
    fn open(&mut self, path: impl AsRef<Path>) -> Result<File<'_, '_, F>, F::Error>;

    /// Open the given source block for lexing
    ///
    /// # Parameters
    ///
    /// * `source`: source string to parse
    /// * `path`: path to the directory that contains this source
    fn open_source(&mut self, source: &str, path: impl AsRef<Path>) -> File<'_, '_, F>;
}

impl<F: FileSystem> PreprocessorExt<F> for Processor<F> {
    fn open(&mut self, path: impl AsRef<Path>) -> Result<File<'_, '_, F>, F::Error> {
        self.parse(path.as_ref()).map(|parsed_file| File {
            inner: parsed_file,
            state: None,
            registry: None,
        })
    }

    fn open_source(&mut self, source: &str, path: impl AsRef<Path>) -> File<'_, '_, F> {
        File {
            inner: self.parse_source(source, path.as_ref()),
            state: None,
            registry: None,
        }
    }
}

/// A preprocessor parsed file ready for lexing
pub struct File<'r, 'p, F: FileSystem> {
    inner: ParsedFile<'p, F>,
    state: Option<ProcessorState>,
    registry: Option<&'r Registry>,
}

impl<'r, 'p, F: FileSystem> File<'r, 'p, F> {
    /// Set the default processor state for processing this file
    pub fn with_state(self, state: impl Into<ProcessorState>) -> Self {
        Self {
            state: Some(state.into()),
            ..self
        }
    }

    /// Set the extension registry to use for this file
    pub fn with_registry(self, registry: impl Into<&'r Registry>) -> Self {
        Self {
            registry: Some(registry.into()),
            ..self
        }
    }
}