gloam 0.4.7

Loader generator for Vulkan, OpenGL, OpenGL ES, EGL, GLX, and WGL
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Command-line interface definitions.

use std::collections::HashSet;

use anyhow::{Result, bail};
use clap::{Args, Parser, Subcommand};

use crate::ir::Version;

// ---------------------------------------------------------------------------
// Top-level CLI
// ---------------------------------------------------------------------------

#[derive(Parser, Debug)]
#[command(
    name = "gloam",
    version = crate::build_info::VERSION,
    about = "Vulkan/OpenGL/GLES/EGL/GLX/WGL loader generator"
)]
pub struct Cli {
    /// Automatically include any extension whose commands or enums were
    /// promoted into the requested core version, even if not listed in
    /// --extensions.
    #[arg(long)]
    pub promoted: bool,

    /// Automatically include any extension that is a predecessor of an
    /// explicitly selected extension (i.e. its commands are aliases of commands
    /// in the selected set).  For example, if GL_KHR_parallel_shader_compile is
    /// selected, GL_ARB_parallel_shader_compile is included automatically.
    #[arg(long)]
    pub predecessors: bool,

    /// API specifiers: comma-separated name[:profile]=version pairs.  Profile
    /// is required for GL (core|compat). Version is optional (latest if
    /// omitted).  Example: gl:core=3.3,gles2=3.0
    #[arg(long, required = true)]
    pub api: String,

    /// Extension filter: path to a file (one per line), a comma-separated
    /// list of extension names, or "all" (the default if omitted).  Prefix a
    /// name with `-` to exclude it.  Examples:
    ///   --extensions all,-GL_EXT_direct_state_access
    ///   --extensions GL_KHR_debug,GL_ARB_sync
    ///   --extensions ""              (include no extensions)
    #[arg(long)]
    pub extensions: Option<String>,

    /// Baseline API versions.  Extensions that are fully promoted into these
    /// versions or earlier are excluded — they're guaranteed to be present
    /// in a context of at least the baseline version.  Format matches --api:
    ///   --baseline gl:core=3.3,gles2=3.0
    #[arg(long)]
    pub baseline: Option<String>,

    /// Merge multiple APIs of the same spec into a single output file.
    /// Required when combining gl and gles2; behaviour is undefined otherwise.
    #[arg(long)]
    pub merge: bool,

    /// Directory for generated output files.
    #[arg(long, default_value = ".")]
    pub out_path: String,

    /// Suppress informational messages on stderr.
    #[arg(long)]
    pub quiet: bool,

    /// Fetch XML specs from Khronos remote URLs instead of bundled copies.
    #[cfg(feature = "fetch")]
    #[arg(long)]
    pub fetch: bool,

    #[command(subcommand)]
    pub generator: Generator,
}

#[derive(Subcommand, Debug)]
pub enum Generator {
    /// Generate a C loader.
    C(CArgs),
}

#[derive(Args, Debug)]
pub struct CArgs {
    /// Enable bijective function-pointer alias resolution.
    #[arg(long)]
    pub alias: bool,

    /// Include a built-in dlopen/LoadLibrary convenience loader layer.
    #[arg(long)]
    pub loader: bool,

    /// Use upstream Vulkan-Headers instead of embedding type definitions.
    /// When set, the generated header includes <vulkan/vulkan_core.h> and
    /// platform-specific headers rather than emitting its own types, enums,
    /// and PFN typedefs.  Only meaningful for Vulkan builds.
    #[arg(long)]
    pub external_headers: bool,
}

impl Cli {
    pub fn api_requests(&self) -> Result<Vec<ApiRequest>> {
        self.api
            .split(',')
            .map(|s| ApiRequest::parse(s.trim()))
            .collect()
    }

    pub fn use_fetch(&self) -> bool {
        #[cfg(feature = "fetch")]
        {
            self.fetch
        }
        #[cfg(not(feature = "fetch"))]
        {
            false
        }
    }

    /// Parse the --extensions argument into an `ExtensionFilter`.
    pub fn extension_filter(&self) -> Result<ExtensionFilter> {
        let Some(ref spec) = self.extensions else {
            return Ok(ExtensionFilter::all());
        };

        // Read names from a file or inline comma-separated list.
        let raw_names: Vec<String> = if std::path::Path::new(spec).exists() {
            let text = std::fs::read_to_string(spec)?;
            text.lines()
                .map(str::trim)
                .filter(|l| !l.is_empty() && !l.starts_with('#'))
                .map(str::to_string)
                .collect()
        } else {
            spec.split(',')
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_string)
                .collect()
        };

        // Split into includes and excludes based on `-` prefix.
        let mut include_all = false;
        let mut includes: Vec<String> = Vec::new();
        let mut excludes: HashSet<String> = HashSet::new();

        for name in raw_names {
            if name.eq_ignore_ascii_case("all") {
                include_all = true;
            } else if let Some(stripped) = name.strip_prefix('-') {
                if !stripped.is_empty() {
                    excludes.insert(stripped.to_string());
                }
            } else {
                includes.push(name);
            }
        }

        // When "all" is combined with explicit names, the explicit names act as
        // baseline-override pins — they survive --baseline exclusion even though
        // "all" means we don't use them for initial inclusion filtering.
        let (include, keep) = if include_all {
            (None, includes.into_iter().collect())
        } else {
            (Some(includes), HashSet::new())
        };
        Ok(ExtensionFilter {
            include,
            exclude: excludes,
            keep,
        })
    }

    /// Parse the --baseline argument into API requests (same format as --api).
    pub fn baseline_requests(&self) -> Result<Vec<ApiRequest>> {
        let Some(ref spec) = self.baseline else {
            return Ok(Vec::new());
        };
        spec.split(',')
            .map(|s| ApiRequest::parse(s.trim()))
            .collect()
    }
}

// ---------------------------------------------------------------------------
// ExtensionFilter
// ---------------------------------------------------------------------------

/// Parsed extension filter from --extensions.
///
/// `include` is `None` for "all extensions" or `Some(list)` for an explicit set.
/// `exclude` is always a set of names to unconditionally remove — applied as a
/// final veto after all selection passes (explicit, dependency, promoted,
/// predecessor, baseline).
/// `keep` is a set of names that override baseline exclusion — used when the
/// user writes `--extensions all,GL_ARB_foo` to pin specific extensions even
/// if they'd otherwise be excluded by --baseline.
#[derive(Debug)]
pub struct ExtensionFilter {
    pub include: Option<Vec<String>>,
    pub exclude: HashSet<String>,
    pub keep: HashSet<String>,
}

impl ExtensionFilter {
    /// No filter — include everything, exclude nothing.
    pub fn all() -> Self {
        Self {
            include: None,
            exclude: HashSet::new(),
            keep: HashSet::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// ApiRequest
// ---------------------------------------------------------------------------

/// Normalize an API name to its canonical short form.
///
/// The Khronos XML uses `"vulkan"` in feature and extension `api=` / `supported=`
/// attributes, but the CLI convention (and GLAD's convention) is `"vk"`.  This
/// function maps the long form to the short form so the rest of the codebase
/// can use a single canonical name.  All other API names pass through unchanged.
pub fn canonical_api_name(name: &str) -> &str {
    match name {
        "vulkan" => "vk",
        other => other,
    }
}

/// Map a canonical short API name back to the XML-canonical form.
///
/// Used when the name will appear in generated symbol names (e.g.
/// `kExtIdx_vulkan`, `gloam_vk_find_extensions_vulkan`), where the XML
/// convention is the appropriate one.  `spec_name` ("vk") controls file
/// stems; this controls symbol suffixes.
pub fn xml_api_name(name: &str) -> &str {
    match name {
        "vk" => "vulkan",
        other => other,
    }
}

/// One parsed entry from the `--api` argument.
#[derive(Debug, Clone)]
pub struct ApiRequest {
    /// Canonical API name: "gl", "gles1", "gles2", "egl", "glx", "wgl", "vk".
    pub name: String,
    /// Only meaningful for GL: "core" or "compat".
    pub profile: Option<String>,
    /// Maximum version to include. None means "latest available".
    pub version: Option<Version>,
}

impl ApiRequest {
    /// Parse a single `name[:profile][=major.minor]` token.
    pub fn parse(s: &str) -> Result<Self> {
        let (name_profile, ver_str) = match s.find('=') {
            Some(i) => (&s[..i], Some(&s[i + 1..])),
            None => (s, None),
        };

        let (name, profile) = match name_profile.find(':') {
            Some(i) => (&name_profile[..i], Some(&name_profile[i + 1..])),
            None => (name_profile, None),
        };

        if name.is_empty() {
            bail!("empty API name in --api argument");
        }

        let version = ver_str
            .map(|v| {
                let (maj, min) = v.split_once('.').ok_or_else(|| {
                    anyhow::anyhow!("invalid version '{}', expected major.minor", v)
                })?;
                Ok::<_, anyhow::Error>(Version::new(maj.parse()?, min.parse()?))
            })
            .transpose()?;

        Ok(Self {
            name: canonical_api_name(name).to_string(),
            profile: profile.map(str::to_string),
            version,
        })
    }

    /// Maps the API name to its spec family: "gl", "egl", "glx", "wgl", "vk".
    pub fn spec_name(&self) -> &str {
        match self.name.as_str() {
            "gl" | "gles1" | "gles2" | "glcore" => "gl",
            "egl" => "egl",
            "glx" => "glx",
            "wgl" => "wgl",
            "vk" | "vulkan" => "vk",
            other => other,
        }
    }

    /// True if this request targets GL (desktop or ES).
    #[allow(dead_code)]
    pub fn is_gl_family(&self) -> bool {
        matches!(self.name.as_str(), "gl" | "gles1" | "gles2" | "glcore")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ---- ApiRequest::parse ----

    #[test]
    fn parse_gl_core_versioned() {
        let r = ApiRequest::parse("gl:core=3.3").unwrap();
        assert_eq!(r.name, "gl");
        assert_eq!(r.profile.as_deref(), Some("core"));
        assert_eq!(r.version, Some(Version::new(3, 3)));
    }

    #[test]
    fn parse_gl_compat_no_version() {
        let r = ApiRequest::parse("gl:compat").unwrap();
        assert_eq!(r.name, "gl");
        assert_eq!(r.profile.as_deref(), Some("compat"));
        assert!(r.version.is_none());
    }

    #[test]
    fn parse_gles2_versioned() {
        let r = ApiRequest::parse("gles2=3.0").unwrap();
        assert_eq!(r.name, "gles2");
        assert!(r.profile.is_none());
        assert_eq!(r.version, Some(Version::new(3, 0)));
    }

    #[test]
    fn parse_vk_versioned() {
        let r = ApiRequest::parse("vk=1.3").unwrap();
        assert_eq!(r.name, "vk");
        assert_eq!(r.version, Some(Version::new(1, 3)));
    }

    #[test]
    fn parse_vulkan_normalizes_to_vk() {
        // "vulkan" is the XML-canonical name; "vk" is the CLI-canonical name.
        // Both must produce the same ApiRequest.
        let r = ApiRequest::parse("vulkan=1.3").unwrap();
        assert_eq!(r.name, "vk", "vulkan should normalize to vk");
        assert_eq!(r.version, Some(Version::new(1, 3)));
    }

    #[test]
    fn parse_vulkan_bare_normalizes_to_vk() {
        let r = ApiRequest::parse("vulkan").unwrap();
        assert_eq!(r.name, "vk");
        assert!(r.version.is_none());
    }

    #[test]
    fn parse_bare_name_no_version() {
        let r = ApiRequest::parse("egl").unwrap();
        assert_eq!(r.name, "egl");
        assert!(r.profile.is_none());
        assert!(r.version.is_none());
    }

    #[test]
    fn parse_empty_name_errors() {
        assert!(ApiRequest::parse("=1.0").is_err());
    }

    #[test]
    fn parse_version_missing_minor_errors() {
        assert!(ApiRequest::parse("gl:core=3").is_err());
    }

    #[test]
    fn parse_version_non_numeric_errors() {
        assert!(ApiRequest::parse("gl:core=three.three").is_err());
    }

    // ---- spec_name() mapping ----

    #[test]
    fn spec_name_gl_family_maps_to_gl() {
        for name in &["gl", "gles1", "gles2", "glcore"] {
            let r = ApiRequest::parse(name).unwrap();
            assert_eq!(r.spec_name(), "gl", "failed for api name '{name}'");
        }
    }

    #[test]
    fn spec_name_passthrough() {
        for name in &["egl", "glx", "wgl"] {
            let r = ApiRequest::parse(name).unwrap();
            assert_eq!(r.spec_name(), *name);
        }
    }

    #[test]
    fn spec_name_vulkan_alias() {
        // Both "vk" and "vulkan" should map to "vk".
        assert_eq!(ApiRequest::parse("vk").unwrap().spec_name(), "vk");
        assert_eq!(ApiRequest::parse("vulkan").unwrap().spec_name(), "vk");
    }
}