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

use glsl_lang_pp::processor::{
    event::{DirectiveKind, EventDirective},
    nodes::VersionProfile,
};
use glsl_lang_types::ast::{
    self, PreprocessorExtensionBehaviorData, PreprocessorExtensionNameData,
    PreprocessorVersionProfileData,
};
use lang_util::NodeContent;

#[derive(Default, Debug, Clone)]
pub struct Directives {
    directives: Vec<EventDirective>,
}

impl Directives {
    pub fn directives(&self) -> &[EventDirective] {
        &self.directives
    }

    fn get_declaration(
        directive: &EventDirective,
        highest_version: &mut Option<(u16, Option<VersionProfile>)>,
    ) -> Option<ast::ExternalDeclaration> {
        let start = directive.text_range().start();
        let end = directive.text_range().end();

        match directive.kind() {
            DirectiveKind::Version(version) => {
                let version_number = version.number;
                let profile = version.parsed_profile;

                let had_highest_version;
                let (highest_version_number, highest_profile) = match highest_version {
                    Some(version_data) => {
                        had_highest_version = true;
                        version_data
                    }
                    None => {
                        had_highest_version = false;
                        highest_version.insert((version_number, profile))
                    }
                };

                *highest_version_number = cmp::max(version_number, *highest_version_number);
                *highest_profile = cmp::max(
                    // Wrap in Some to avoid OpenGL ES being considered higher than no profile (i.e., core profile)
                    Some(profile.unwrap_or(VersionProfile::None)),
                    *highest_profile,
                );

                (!had_highest_version).then_some(
                    ast::ExternalDeclarationData::Preprocessor(
                        ast::PreprocessorData::Version(
                            ast::PreprocessorVersionData {
                                version: version_number,
                                profile: match profile {
                                    None | Some(VersionProfile::None) => None,
                                    Some(VersionProfile::Core) => {
                                        Some(PreprocessorVersionProfileData::Core.into())
                                    }
                                    Some(VersionProfile::Compatibility) => {
                                        Some(PreprocessorVersionProfileData::Compatibility.into())
                                    }
                                    Some(VersionProfile::Es) => {
                                        Some(PreprocessorVersionProfileData::Es.into())
                                    }
                                },
                            }
                            .into(),
                        )
                        .spanned(start, end),
                    )
                    .spanned(start, end),
                )
            }

            DirectiveKind::Pragma(pragma) => Some(
                ast::ExternalDeclarationData::Preprocessor(
                    ast::PreprocessorData::Pragma(
                        ast::PreprocessorPragmaData {
                            command: pragma.raw().to_owned(),
                        }
                        .into(),
                    )
                    .spanned(start, end),
                )
                .spanned(start, end),
            ),

            DirectiveKind::Extension(extension) => Some(
                ast::ExternalDeclarationData::Preprocessor(
                    ast::PreprocessorData::Extension(
                        ast::PreprocessorExtensionData {
                            name: match extension.name {
                                glsl_lang_pp::processor::nodes::ExtensionName::All => {
                                    PreprocessorExtensionNameData::All
                                }
                                glsl_lang_pp::processor::nodes::ExtensionName::Specific(
                                    ref name,
                                ) => PreprocessorExtensionNameData::Specific(name.as_ref().into()),
                            }
                            .into(),
                            behavior: Some(
                                match extension.behavior {
                                    glsl_lang_pp::processor::nodes::ExtensionBehavior::Require => {
                                        PreprocessorExtensionBehaviorData::Require
                                    }
                                    glsl_lang_pp::processor::nodes::ExtensionBehavior::Enable => {
                                        PreprocessorExtensionBehaviorData::Enable
                                    }
                                    glsl_lang_pp::processor::nodes::ExtensionBehavior::Warn => {
                                        PreprocessorExtensionBehaviorData::Warn
                                    }
                                    glsl_lang_pp::processor::nodes::ExtensionBehavior::Disable => {
                                        PreprocessorExtensionBehaviorData::Disable
                                    }
                                }
                                .into(),
                            ),
                        }
                        .into(),
                    )
                    .spanned(start, end),
                )
                .spanned(start, end),
            ),

            _ => None,
        }
    }

    pub fn inject(mut self, root: &mut ast::TranslationUnit) -> Directives {
        let mut directive_idx = 0;
        let mut declaration_idx = 0;
        let mut highest_version = None;
        let mut version_directive_declaration_idx = None;

        // Insert directives
        let mut start = None;
        while declaration_idx < root.0.len() && directive_idx < self.directives.len() {
            // The current declaration. We want to insert directives before this declaration.
            let current_declaration = &root.0[declaration_idx];

            // Find where the range starts
            let actual_start =
                if let Some(current_start) = current_declaration.span.map(|span| span.start()) {
                    current_start
                } else if let Some(start) = start {
                    // This is the end of the previous declaration
                    start
                } else {
                    // No span information, keep looking
                    declaration_idx += 1;
                    continue;
                };

            // Find where the current declaration ends
            let end = if let Some(current_end) = current_declaration.span.map(|span| span.end()) {
                current_end
            } else {
                // The current node has no span information, so use the current start
                actual_start
            };

            // Are there any directives to insert before the current declaration_idx?
            while directive_idx < self.directives.len() {
                // The current directive
                let current_directive = &self.directives[directive_idx];
                let span = current_directive.text_range();

                // For directives in #include'd files, a previous #include directive event prevents
                // inserting them too soon in the top-level file
                if span.end().offset <= actual_start.offset
                    || actual_start.source_id != span.source_id()
                {
                    if let Some(declaration) =
                        Self::get_declaration(current_directive, &mut highest_version)
                    {
                        // Add to ast
                        root.0.insert(declaration_idx, declaration);

                        if matches!(current_directive.kind(), DirectiveKind::Version(_)) {
                            version_directive_declaration_idx.get_or_insert(declaration_idx);
                        }

                        declaration_idx += 1;

                        // Processed, remove from directive list
                        self.directives.remove(directive_idx);
                    } else {
                        // Can't/shouldn't be processed, skip it
                        directive_idx += 1;
                    }
                } else {
                    // This directive comes later
                    break;
                }
            }

            // Advance the current declaration
            declaration_idx += 1;

            // Advance the directive range
            start = Some(end);
        }

        // Append any remaining directives
        while directive_idx < self.directives.len() {
            let current_directive = &self.directives[directive_idx];

            if let Some(declaration) =
                Self::get_declaration(current_directive, &mut highest_version)
            {
                root.0.push(declaration);

                if matches!(current_directive.kind(), DirectiveKind::Version(_)) {
                    version_directive_declaration_idx.get_or_insert(root.0.len() - 1);
                }

                self.directives.remove(directive_idx);
            } else {
                directive_idx += 1;
            }
        }

        // Set the version directive value to the highest (i.e., the one that requires the most
        // OpenGL features) that was found
        if let (
            Some(version_directive_declaration_idx),
            Some((highest_version_number, highest_profile)),
        ) = (version_directive_declaration_idx, highest_version)
        {
            if let ast::ExternalDeclarationData::Preprocessor(preprocessor_data) =
                &mut root.0[version_directive_declaration_idx].content
            {
                if let ast::PreprocessorData::Version(preprocessor_version) =
                    &mut preprocessor_data.content
                {
                    preprocessor_version.version = highest_version_number;
                    preprocessor_version.profile = match highest_profile {
                        None | Some(VersionProfile::None) => None,
                        Some(VersionProfile::Core) => {
                            Some(PreprocessorVersionProfileData::Core.into())
                        }
                        Some(VersionProfile::Compatibility) => {
                            Some(PreprocessorVersionProfileData::Compatibility.into())
                        }
                        Some(VersionProfile::Es) => Some(PreprocessorVersionProfileData::Es.into()),
                    };
                }
            }
        }

        self
    }
}

impl From<Vec<EventDirective>> for Directives {
    fn from(directives: Vec<EventDirective>) -> Self {
        Self { directives }
    }
}

impl From<Directives> for Vec<EventDirective> {
    fn from(directives: Directives) -> Self {
        directives.directives
    }
}