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
use std::collections::HashMap;

use lang_util::{FileId, SmolStr};

mod definition;
use definition::Definition;

pub mod event;

pub mod expand;

mod expr;

pub mod fs;

pub mod nodes;
use nodes::{Define, DefineObject, Version};

use crate::{
    exts::Registry,
    processor::nodes::{ExtensionBehavior, ExtensionName},
};

pub mod str;

/// Operating mode for #include directives
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IncludeMode {
    /// No #include directives are allowed
    None,
    /// GL_ARB_shading_language_include runtime includes
    ArbInclude { warn: bool },
    /// GL_GOOGLE_include_directive compile-time includes
    GoogleInclude { warn: bool },
}

impl IncludeMode {
    pub fn warn(self) -> bool {
        match self {
            IncludeMode::None => false,
            IncludeMode::ArbInclude { warn } | IncludeMode::GoogleInclude { warn } => warn,
        }
    }
}

impl Default for IncludeMode {
    fn default() -> Self {
        Self::None
    }
}

/// Current state of the preprocessor
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcessorState {
    include_mode: IncludeMode,
    definitions: HashMap<SmolStr, Definition>,
    version: Version,
    cpp_style_line: bool,
}

impl ProcessorState {
    pub fn builder() -> ProcessorStateBuilder<'static> {
        ProcessorStateBuilder::default()
    }

    fn get_definition(&self, name: &str) -> Option<&Definition> {
        self.definitions.get(name)
    }

    // TODO: Return a proper error type?
    pub fn definition(&mut self, definition: Define, file_id: FileId) -> bool {
        let entry = self.definitions.entry(definition.name().into());

        match entry {
            std::collections::hash_map::Entry::Occupied(mut occupied) => {
                if occupied.get().protected() {
                    false
                } else {
                    occupied.insert(Definition::Regular(definition.into(), file_id));
                    true
                }
            }
            std::collections::hash_map::Entry::Vacant(vacant) => {
                vacant.insert(Definition::Regular(definition.into(), file_id));
                true
            }
        }
    }

    fn add_extension(&mut self, name: &ExtensionName, behavior: ExtensionBehavior) {
        // Process include extensions
        let target_include_mode = if *name == ext_name!("GL_ARB_shading_language_include") {
            Some(IncludeMode::ArbInclude {
                warn: behavior == ExtensionBehavior::Warn,
            })
        } else if *name == ext_name!("GL_GOOGLE_include_directive") {
            Some(IncludeMode::GoogleInclude {
                warn: behavior == ExtensionBehavior::Warn,
            })
        } else {
            None
        };

        if let Some(target) = target_include_mode {
            if behavior.is_active() {
                self.include_mode = target;

                // GL_GOOGLE_include_directive enable GL_GOOGLE_cpp_style_line
                if let IncludeMode::GoogleInclude { .. } = target {
                    self.cpp_style_line = true;
                }
            } else {
                // TODO: Implement current mode as a stack?
                self.include_mode = IncludeMode::None;
            }
        }

        // Process others
        if *name == ext_name!("GL_GOOGLE_cpp_style_line_directive") {
            if behavior.is_active() {
                self.cpp_style_line = true;
            } else {
                // TODO: Notify instead of silently ignoring?
                if !matches!(self.include_mode, IncludeMode::GoogleInclude { .. }) {
                    self.cpp_style_line = false;
                }
            }
        }
    }

    fn extension(&mut self, extension: &nodes::Extension) {
        self.add_extension(&extension.name, extension.behavior);
    }

    fn cpp_style_line(&self) -> bool {
        self.cpp_style_line
    }
}

impl Default for ProcessorState {
    fn default() -> Self {
        ProcessorStateBuilder::default().finish()
    }
}

#[derive(Clone)]
pub struct ProcessorStateBuilder<'r> {
    core_profile: bool,
    compatibility_profile: bool,
    es_profile: bool,
    extensions: Vec<(ExtensionName, ExtensionBehavior)>,
    definitions: Vec<Define>,
    registry: &'r Registry,
}

impl<'r> ProcessorStateBuilder<'r> {
    pub fn new(registry: &'r Registry) -> Self {
        let default = ProcessorStateBuilder::default();
        Self {
            registry,
            ..default
        }
    }

    pub fn registry<'s>(self, registry: &'s Registry) -> ProcessorStateBuilder<'s> {
        ProcessorStateBuilder::<'s> {
            registry,
            core_profile: self.core_profile,
            compatibility_profile: self.compatibility_profile,
            es_profile: self.es_profile,
            extensions: self.extensions,
            definitions: self.definitions,
        }
    }

    pub fn core_profile(self, core_profile: bool) -> Self {
        Self {
            core_profile,
            ..self
        }
    }

    pub fn compatibility_profile(self, compatibility_profile: bool) -> Self {
        Self {
            compatibility_profile,
            ..self
        }
    }

    pub fn es_profile(self, es_profile: bool) -> Self {
        Self { es_profile, ..self }
    }

    pub fn extension(
        mut self,
        name: impl Into<ExtensionName>,
        behavior: impl Into<ExtensionBehavior>,
    ) -> Self {
        self.extensions.push((name.into(), behavior.into()));
        self
    }

    pub fn definition(mut self, definition: impl Into<Define>) -> Self {
        self.definitions.push(definition.into());
        self
    }

    pub fn finish(self) -> ProcessorState {
        let one = DefineObject::one();

        let mut state =
            ProcessorState {
                // No #include extensions enabled
                include_mode: IncludeMode::None,
                // Spec 3.3, "There is a built-in macro definition for each profile the implementation
                // supports. All implementations provide the following macro:
                // `#define GL_core_profile 1`
                definitions: self
                    .core_profile
                    .then(|| Define::object("GL_core_profile".into(), one.clone(), true))
                    .into_iter()
                    .chain(self.compatibility_profile.then(|| {
                        Define::object("GL_compatibility_profile".into(), one.clone(), true)
                    }))
                    .chain(
                        self.es_profile
                            .then(|| Define::object("GL_es_profile".into(), one.clone(), true)),
                    )
                    .chain(self.definitions)
                    .map(|definition| Definition::Regular(definition.into(), FileId::default()))
                    .chain([Definition::Line, Definition::File, Definition::Version])
                    .chain(self.registry.all().map(|spec| {
                        Definition::Regular(
                            Define::object(spec.name().as_ref().into(), one.clone(), true).into(),
                            FileId::default(),
                        )
                    }))
                    .map(|definition| (definition.name().into(), definition))
                    .collect(),
                version: Version::default(),
                cpp_style_line: false,
            };

        for (name, behavior) in self.extensions {
            state.add_extension(&name, behavior);
        }

        state
    }
}

impl From<ProcessorStateBuilder<'_>> for ProcessorState {
    fn from(builder: ProcessorStateBuilder<'_>) -> Self {
        builder.finish()
    }
}

impl Default for ProcessorStateBuilder<'static> {
    fn default() -> Self {
        Self {
            core_profile: true,
            compatibility_profile: false,
            es_profile: false,
            extensions: Default::default(),
            definitions: Default::default(),
            registry: &*crate::exts::DEFAULT_REGISTRY,
        }
    }
}