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
use std::cell::RefCell;
use std::collections::{BTreeMap, HashSet};
use std::rc::Rc;

use crate::ast;

/// Parsing options
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct ParseOptions {
    /// `true` if the GLSL target should be Vulkan instead of OpenGL
    pub target_vulkan: bool,
    /// Unique source identifier for token positions
    pub source_id: usize,
    /// Allow Rust quoting identifiers (`#(ident)`) in the source
    pub allow_rs_ident: bool,
}

impl ParseOptions {
    /// Create new parsing options using default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new parsing context from this options object
    pub fn build(self) -> ParseContext {
        ParseContext {
            opts: self,
            ..Default::default()
        }
    }

    /// Create a new parsing context from this options object, with comment parsing enabled
    pub fn with_comments(self) -> ParseContext {
        ParseContext {
            opts: self,
            data: Rc::new(RefCell::new(ParseContextData::with_comments())),
        }
    }

    /// Create a new parsing context from this options object, with a custom type table policy
    pub fn with_policy(self, policy: impl TypeTablePolicy + 'static) -> ParseContext {
        ParseContext {
            opts: self,
            data: Rc::new(RefCell::new(ParseContextData::with_policy(policy))),
        }
    }

    /// Create a new parsing context from this options object, with a custom type table policy and
    /// comment parsing enabled
    pub fn with_comments_and_policy(self, policy: impl TypeTablePolicy + 'static) -> ParseContext {
        ParseContext {
            opts: self,
            data: Rc::new(RefCell::new(ParseContextData::with_comments_and_policy(
                policy,
            ))),
        }
    }

    /// Create a new parsing context from this options object and pre-existing context data
    pub fn with_context(self, context: ParseContextData) -> ParseContext {
        ParseContext {
            opts: self,
            data: Rc::new(RefCell::new(context)),
        }
    }
}

/// Parsing context
#[derive(Default, Debug, Clone, PartialEq)]
pub struct ParseContext {
    /// Parsing options
    pub opts: ParseOptions,
    /// Parsing data
    pub data: Rc<RefCell<ParseContextData>>,
}

impl ParseContext {
    /// Clone the parsing data and return the cloned context
    pub fn clone_inner(&self) -> Self {
        Self {
            opts: self.opts,
            data: Rc::new(RefCell::new(self.data.borrow().clone())),
        }
    }

    /// Consume this [ParseContext] and return its data. Will fail if there are multiple references
    /// to this context's data.
    pub fn into_data(self) -> Option<ParseContextData> {
        Rc::try_unwrap(self.data).ok().map(RefCell::into_inner)
    }

    /// Obtain a reference to the context's data
    pub fn data(&self) -> std::cell::Ref<'_, ParseContextData> {
        self.data.borrow()
    }

    /// Obtain an exclusive reference to the context's data
    pub fn data_mut(&self) -> std::cell::RefMut<'_, ParseContextData> {
        self.data.borrow_mut()
    }

    /// Create a new parse context cloning the given one's data, but applies the given policy
    pub fn with_policy(&self, policy: impl TypeTablePolicy + 'static) -> ParseContext {
        Self {
            opts: self.opts,
            data: {
                let mut data = self.data().clone();
                data.policy = Rc::new(policy);
                Rc::new(RefCell::new(data))
            },
        }
    }
}

impl From<ParseOptions> for ParseContext {
    fn from(opts: ParseOptions) -> Self {
        Self {
            opts,
            data: Default::default(),
        }
    }
}

/// Parsing context data
#[derive(Debug, Clone)]
pub struct ParseContextData {
    /// List of known type names
    pub names: HashSet<String>,
    /// List of parsed comments (or `None` to disable comment parsing)
    pub comments: Option<CommentList>,

    policy: Rc<dyn TypeTablePolicy>,
}

impl ParseContextData {
    /// Create a new [ParseContextData] object
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new [ParseContextData] object with the given type table policy
    ///
    /// # Parameters
    ///
    /// * `policy`: policy object managing the type table
    pub fn with_policy(policy: impl TypeTablePolicy + 'static) -> Self {
        Self {
            policy: Rc::new(policy),
            ..Default::default()
        }
    }

    /// Create a new [ParseContextData] object with comments parsing enabled
    pub fn with_comments() -> Self {
        Self {
            comments: Some(Default::default()),
            ..Default::default()
        }
    }

    /// Create a new [ParseContextData] object with comments parsing enabled and the given type
    /// table policy
    ///
    /// # Parameters
    ///
    /// * `policy`: policy object managing the type table
    pub fn with_comments_and_policy(policy: impl TypeTablePolicy + 'static) -> Self {
        Self {
            comments: Some(Default::default()),
            policy: Rc::new(policy),
            ..Default::default()
        }
    }
}

impl Default for ParseContextData {
    fn default() -> Self {
        Self {
            names: Default::default(),
            comments: Default::default(),
            policy: Rc::new(GlslTypeTablePolicy),
        }
    }
}

impl PartialEq for ParseContextData {
    fn eq(&self, other: &Self) -> bool {
        self.names.eq(&other.names)
    }
}

// Begin type name stuff

/// Context in which an identifier is seen for the first time
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IdentifierContext {
    /// The identifier is a function declaration name
    FunctionPrototype,
}

/// A policy to dictate which identifiers should be seen as type names or not
pub trait TypeTablePolicy: std::fmt::Debug {
    /// Return `true` if the given identifier (in its context) should now be considered a type name
    /// or not.
    fn promote_to_type_name(&self, name: &ast::Identifier, ctx: IdentifierContext) -> bool;
}

/// Default GLSL type table policy: only struct declarations create new type names
#[derive(Debug, Clone, Copy)]
pub struct GlslTypeTablePolicy;

impl TypeTablePolicy for GlslTypeTablePolicy {
    fn promote_to_type_name(&self, _: &ast::Identifier, _: IdentifierContext) -> bool {
        false
    }
}

impl ParseContext {
    /// Return `true` if the given name is a type name
    pub fn is_type_name(&self, name: &str) -> bool {
        self.data.borrow().is_type_name(name)
    }

    /// Register `name` as a new type name
    pub fn add_type_name(&self, name: ast::Identifier) -> ast::TypeName {
        self.data.borrow_mut().add_type_name(name)
    }

    /// Update the context data with a new identifier in a given context
    pub fn new_identifier(&self, name: &ast::Identifier, ctx: IdentifierContext) {
        self.data.borrow_mut().new_identifier(name, ctx)
    }
}

impl ParseContextData {
    /// Return `true` if the given name is a type name
    pub fn is_type_name(&self, name: &str) -> bool {
        self.names.contains(name)
    }

    /// Register `name` as a new type name
    pub fn add_type_name(&mut self, name: ast::Identifier) -> ast::TypeName {
        let name_string = name.0.to_string();
        self.names.insert(name_string);
        name.map(ast::TypeNameData::from)
    }

    /// Update the context data with a new identifier in a given context
    pub fn new_identifier(&mut self, name: &ast::Identifier, ctx: IdentifierContext) {
        if self.policy.promote_to_type_name(name, ctx) {
            self.add_type_name(name.clone());
        }
    }
}

// End type name stuff

// Begin comment stuff

/// A list of comments indexed by their position
pub type CommentList = BTreeMap<ast::NodeSpan, ast::Comment>;

impl ParseContext {
    /// Return `true` if this parsing context supports comments
    pub fn has_comments(&self) -> bool {
        self.data.borrow().comments.is_some()
    }

    /// Add a new comment to the parsed comments list
    pub fn add_comment(&self, comment: ast::Comment) {
        self.data.borrow_mut().add_comment(comment)
    }
}

impl ParseContextData {
    /// Add a new comment to the parsed comments list
    pub fn add_comment(&mut self, comment: ast::Comment) {
        if let Some(comments) = self.comments.as_mut() {
            let span = comment.span;
            comments.insert(span.unwrap(), comment);
        }
    }
}