glslint 0.5.0

A luma.gl/deck.gl-aware GLSL checker and language server
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! Drive glslangValidator — the Khronos GLSL reference compiler — over an
//! assembled unit and translate its `0:LINE` diagnostics back to the original
//! files via the line map.
//!
//! glslangValidator validates GLSL ES natively: `#version 300 es`, the combined
//! `sampler2D` type, and combined-sampler *function parameters* like
//! `windAt(sampler2D, vec2)` — none of which naga's Vulkan-GLSL frontend accepts.
//! So the assembler ships ES source through it verbatim, with no source rewrites.

use crate::assemble::{self, Assembled};
use crate::config::Config;
use crate::diagnostics::{Diag, Severity};
use crate::embed::{self, Embedded};
use crate::lints;
use std::io::{ErrorKind, Write};
use std::path::Path;
use std::process::{Command, Stdio};

pub fn check_file(path: &Path) -> anyhow::Result<Vec<Diag>> {
    let source = std::fs::read_to_string(path)?;
    Ok(check_source(path, &source))
}

pub fn check_source(path: &Path, source: &str) -> Vec<Diag> {
    // A JS/TS host: lint the GLSL embedded in its `glsl`…`` tagged templates,
    // rather than treat the whole file as one shader.
    if embed::is_js_ts(path) {
        return check_embedded(path, source);
    }

    let config = Config::resolve_for(path);
    let assembled = assemble::assemble(path, source, &config);

    let mut diags = check_assembled(&assembled);
    diags.extend(lints::run_lints(path, source));
    // If this file is a module with a JS `uniformTypes` mirror, cross-check them.
    if let Some((module, types_path)) = crate::config::drift_for(path) {
        diags.extend(crate::drift::check(path, source, &module, &types_path));
    }
    diags.sort_by(|a, b| (a.path.as_path(), a.line, a.col).cmp(&(b.path.as_path(), b.line, b.col)));
    diags
}

/// Lint every shader embedded in a JS/TS file, mapping each diagnostic from the
/// shader's own line/col into the host file's template span.
fn check_embedded(host: &Path, source: &str) -> Vec<Diag> {
    let mut diags = Vec::new();
    for emb in embed::extract(source) {
        diags.extend(check_one_embedded(host, source, &emb));
    }
    diags.sort_by(|a, b| (a.path.as_path(), a.line, a.col).cmp(&(b.path.as_path(), b.line, b.col)));
    diags
}

fn check_one_embedded(host: &Path, source: &str, emb: &Embedded) -> Vec<Diag> {
    let mut out = Vec::new();

    // The source-level lints match the author's own tokens, so they're valid even
    // when the shader is incomplete (an interpolation we couldn't resolve).
    for d in lints::run_lints(host, &emb.source) {
        out.push(remap(d, host, emb));
    }

    if emb.has_interp {
        // A `${…}` interpolation makes this an incomplete translation unit — the
        // injected value can define or use symbols we can't see. Skip the
        // validator rather than report errors that might be our own doing, and
        // leave a note so the partial coverage is visible, not silent.
        out.push(interp_note(host, emb));
        return out;
    }

    let config = config_for_embedded(host, source, emb);
    let assembled =
        assemble::assemble_embedded(host, &emb.source, &config, emb.stage, emb.has_entry);
    for d in check_assembled(&assembled) {
        out.push(remap(d, host, emb));
    }
    out
}

/// Resolve the embedded shader's luma modules from a `new Model({ modules })` call
/// that references its binding, when discoverable; otherwise fall back to the
/// host file's directory config (a `glsl-lsp.toml` or sibling `*Uniforms.glsl`).
fn config_for_embedded(host: &Path, source: &str, emb: &Embedded) -> Config {
    if let Some(name) = &emb.name
        && let Some(d) = crate::derive::derive_for_binding(source, host, name)
    {
        return Config {
            preludes: Vec::new(),
            modules: d.modules,
            use_builtin_prelude: d.use_builtin_prelude,
        };
    }
    Config::resolve_for(host)
}

/// Offset a diagnostic on the embedded shader (`path == host`) into the host
/// file's template span. Diagnostics that already point at an injected module file
/// (a different path) are left untouched.
fn remap(d: Diag, host: &Path, emb: &Embedded) -> Diag {
    if d.path.as_path() != host {
        return d;
    }
    let pos = emb.map(d.line, d.col);
    Diag {
        path: host.to_path_buf(),
        line: pos.line,
        col: pos.col,
        ..d
    }
}

/// The "checked with lints only" note for an interpolated template, pinned to the
/// template's opening position in the host file.
fn interp_note(host: &Path, emb: &Embedded) -> Diag {
    let pos = emb
        .line_map
        .first()
        .copied()
        .unwrap_or(embed::HostPos { line: 1, col: 1 });
    Diag {
        path: host.to_path_buf(),
        line: pos.line,
        col: pos.col,
        len: 1,
        severity: Severity::Note,
        message: "embedded shader has a ${…} interpolation — checked with lints only \
                  (glslang validation skipped)"
            .to_string(),
        source: "embed",
    }
}

fn check_assembled(a: &Assembled) -> Vec<Diag> {
    let run = match run_glslang(a) {
        Ok(run) => run,
        Err(RunError::NotFound) => {
            return vec![tool_error(a, missing_glslang_message())];
        }
        Err(RunError::BadOverride(e)) => {
            return vec![tool_error(
                a,
                format!(
                    "GLSLINT_GLSLANG is set but couldn't be run ({e}) — point it at \
                     the glslangValidator (or glslang) executable"
                ),
            )];
        }
        Err(RunError::Io(e)) => {
            return vec![tool_error(
                a,
                format!("failed to run glslangValidator: {e}"),
            )];
        }
    };

    let diags = parse_output(a, &run.output);
    // A non-zero exit with nothing parseable must never pass silently (a span we
    // can't map, an unexpected message format, etc.).
    if diags.is_empty() && !run.success {
        let detail = run
            .output
            .lines()
            .map(str::trim)
            .filter(|l| l.starts_with("ERROR:") || l.starts_with("WARNING:"))
            .find(|l| !l.contains("compilation error") && !l.contains("compilation warning"))
            .unwrap_or("unknown error");
        return vec![tool_error(a, format!("glslangValidator failed: {detail}"))];
    }
    diags
}

enum RunError {
    NotFound,
    /// `GLSLINT_GLSLANG` was set but the binary it names couldn't be spawned.
    BadOverride(std::io::Error),
    Io(std::io::Error),
}

struct GlslangRun {
    output: String,
    success: bool,
}

/// Run glslangValidator on the assembled source via stdin. Tries `glslangValidator`
/// then `glslang` (the renamed binary), or `$GLSLINT_GLSLANG` when set.
fn run_glslang(a: &Assembled) -> Result<GlslangRun, RunError> {
    let (candidates, explicit) = glslang_candidates();
    for bin in candidates {
        let mut child = match Command::new(&bin)
            .arg("--stdin")
            .arg("-S")
            .arg(a.stage.glslang_stage())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
        {
            Ok(c) => c,
            // An explicit GLSLINT_GLSLANG that won't spawn (missing, a directory,
            // not executable) is a config error, not "no validator installed".
            Err(e) if explicit => return Err(RunError::BadOverride(e)),
            // Binary absent on PATH: fall through to the next candidate.
            Err(e) if e.kind() == ErrorKind::NotFound => continue,
            Err(e) => return Err(RunError::Io(e)),
        };

        // Write the whole (tiny) unit and close stdin before reading stdout —
        // glslang consumes all input before emitting, so this can't deadlock.
        {
            let mut stdin = child.stdin.take().expect("stdin was piped");
            if let Err(e) = stdin.write_all(a.source.as_bytes()) {
                return Err(RunError::Io(e));
            }
        }
        let out = child.wait_with_output().map_err(RunError::Io)?;
        // Diagnostics land on stdout; fold in stderr defensively.
        let mut output = String::from_utf8_lossy(&out.stdout).into_owned();
        output.push_str(&String::from_utf8_lossy(&out.stderr));
        return Ok(GlslangRun {
            output,
            success: out.status.success(),
        });
    }
    Err(RunError::NotFound)
}

/// The missing-validator error, naming the install command for *this* platform.
///
/// This is the first thing a user hits on a machine without glslang, and the
/// npm install path makes that the common case: `npm i -D glslint` brings the
/// binary but not its Khronos dependency, and that audience has no reason to
/// expect one. So the error names the exact command to run here rather than
/// reporting a generic "not found" and leaving the user to search for the fix.
fn missing_glslang_message() -> String {
    let install = if cfg!(target_os = "macos") {
        "install it with `brew install glslang`"
    } else if cfg!(target_os = "windows") {
        "install the Vulkan SDK, which ships glslangValidator.exe"
    } else {
        "install it with `apt install glslang-tools` (or your distro's glslang package)"
    };
    format!(
        "glslangValidator not found on PATH — {install}, \
         or set GLSLINT_GLSLANG to an existing binary"
    )
}

/// The binaries to try, and whether the choice was forced via `GLSLINT_GLSLANG`
/// (which changes how a spawn failure is reported).
fn glslang_candidates() -> (Vec<String>, bool) {
    if let Some(bin) = std::env::var_os("GLSLINT_GLSLANG") {
        return (vec![bin.to_string_lossy().into_owned()], true);
    }
    (
        vec!["glslangValidator".to_string(), "glslang".to_string()],
        false,
    )
}

/// Parse glslangValidator's diagnostics and map each home.
///
/// Format: `ERROR: <str>:<line>: 'token' : message`, where `<str>` is always 0
/// for our single stdin unit. Lines with no `<str>:<line>` prefix are file-level
/// (e.g. a bad `#version`) and surface as a fallback when nothing else maps.
fn parse_output(a: &Assembled, output: &str) -> Vec<Diag> {
    let mut mapped = Vec::new();
    let mut fileless = Vec::new();

    for line in output.lines() {
        let (severity, rest) = if let Some(r) = line.strip_prefix("ERROR: ") {
            (Severity::Error, r)
        } else if let Some(r) = line.strip_prefix("WARNING: ") {
            (Severity::Warning, r)
        } else {
            continue;
        };

        match parse_located(rest) {
            Some((lineno, token, msg)) => {
                // Parse-phase cascade terminator — drop it; the real error precedes.
                // (Semantic failures cascade differently — onto the same source
                // line — and are collapsed by `collapse_per_line` below.)
                if msg.contains("compilation terminated") {
                    continue;
                }
                if let Some(d) = map_located(a, lineno, token.as_deref(), severity, msg) {
                    mapped.push(d);
                }
            }
            None => {
                let msg = rest.trim();
                // Drop the per-run summary ("2 compilation errors. ...").
                if msg.contains("compilation error") || msg.contains("compilation warning") {
                    continue;
                }
                fileless.push((severity, msg.to_string()));
            }
        }
    }

    if !mapped.is_empty() {
        return collapse_per_line(mapped);
    }
    // Nothing mapped: surface any file-level messages, pinned to line 1.
    fileless
        .into_iter()
        .map(|(severity, message)| Diag {
            path: a.target.clone(),
            line: 1,
            col: 1,
            len: 1,
            severity,
            message,
            source: "glslang",
        })
        .collect()
}

/// Parse the `<str>:<line>: 'token' : message` body of a glslang diagnostic into
/// `(line, token, message)`. The message is kept verbatim (glslang's exact
/// wording, leading `'token'` and all); the token is split out only to refine the
/// column. Returns `None` when there's no `<str>:<line>` prefix (a file-level
/// message like "version not supported").
fn parse_located(rest: &str) -> Option<(u32, Option<String>, String)> {
    let mut parts = rest.splitn(3, ':');
    // Parsing the leading `<str>` index as a number is what distinguishes a
    // located diagnostic from a file-level one.
    let _str_no: u32 = parts.next()?.trim().parse().ok()?;
    let lineno: u32 = parts.next()?.trim().parse().ok()?;
    let message = parts.next()?.trim().to_string();

    // The offending token, when glslang quoted a non-empty one.
    let token = message
        .strip_prefix('\'')
        .and_then(|after| after.find('\'').map(|end| after[..end].to_string()))
        .filter(|t| !t.is_empty());

    Some((lineno, token, message))
}

/// Map a glslang `0:LINE` location to the original file, refining the column from
/// the offending token when it appears verbatim on the line. An error on a line
/// glslint itself injected is surfaced at the target's line 1 rather than dropped,
/// so a regression in our own prelude/setup can't pass silently.
fn map_located(
    a: &Assembled,
    asm_line: u32,
    token: Option<&str>,
    severity: Severity,
    message: String,
) -> Option<Diag> {
    let idx = asm_line.checked_sub(1)? as usize;
    match a.map.get(idx)? {
        // A line from a real source file: point the diagnostic there. The assembled
        // line is a verbatim copy of the original (no per-line rewrites), so a token
        // column found here is valid against the original too.
        Some(loc) => {
            let (col, len) = a
                .source
                .lines()
                .nth(idx)
                .and_then(|text| locate_token(text, token))
                .unwrap_or((1, 1));
            Some(Diag {
                path: loc.path.clone(),
                line: loc.line,
                col,
                len,
                severity,
                message: truncate_message(message),
                source: "glslang",
            })
        }
        // A line glslint injected (version / precision / prelude / wrapper main).
        // Clean in normal operation; if it errors, that's a regression in our own
        // code — surface it at line 1 instead of silently dropping it.
        None => Some(Diag {
            path: a.target.clone(),
            line: 1,
            col: 1,
            len: 1,
            severity,
            message: truncate_message(format!("(in glslint-injected code) {message}")),
            source: "glslang",
        }),
    }
}

/// Column (1-based char) and length of `token` within `line`, when it's an
/// identifier-like token present verbatim. `None` keeps the caller at column 1 —
/// we never point at a guessed location.
fn locate_token(line: &str, token: Option<&str>) -> Option<(u32, u32)> {
    let tok = token?;
    let first = tok.chars().next()?;
    if !(first.is_alphanumeric() || first == '_') {
        return None; // operators / punctuation — don't hunt for a stray match
    }
    // First *whole-word* occurrence. glslang doesn't say which occurrence it meant,
    // but matching on word boundaries at least avoids underlining `pos` inside
    // `position` or `speed` inside `speedFactor`.
    let bytes = line.as_bytes();
    let mut from = 0;
    while let Some(rel) = line[from..].find(tok) {
        let start = from + rel;
        let end = start + tok.len();
        let left_ok = start == 0 || !is_word_byte(bytes[start - 1]);
        let right_ok = end == line.len() || !is_word_byte(bytes[end]);
        if left_ok && right_ok {
            let col = line[..start].chars().count() as u32 + 1;
            return Some((col, tok.chars().count() as u32));
        }
        from = start + 1;
    }
    None
}

/// An ASCII identifier byte (`[A-Za-z0-9_]`). A multibyte UTF-8 byte is not one,
/// so a non-ASCII char correctly counts as a word boundary here.
fn is_word_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

/// Collapse glslang's per-line error cascade to its root cause. For a semantic
/// failure glslang does NOT stop at the first error: it emits the root cause and
/// then a string of *derived* errors (and sometimes exact duplicates) on the same
/// source line — e.g. a bad UBO-member access yields `'speed' : no such field`
/// followed by a giant `'=' : cannot convert from <whole block type>`. glslang
/// emits the root cause first, so keeping the first diagnostic per `(path, line)`
/// drops the noise the user can't act on. Lint diagnostics are added later and
/// are deliberately left untouched.
fn collapse_per_line(diags: Vec<Diag>) -> Vec<Diag> {
    let mut seen = std::collections::HashSet::new();
    diags
        .into_iter()
        .filter(|d| seen.insert((d.path.clone(), d.line)))
        .collect()
}

/// Cap message length. glslang inlines full type definitions into some messages
/// (an entire `uniform block{...}` for a bad interface-block access), which is
/// unreadable in a terminal or an editor hover. Truncate on a char boundary.
fn truncate_message(message: String) -> String {
    const MAX: usize = 200;
    if message.chars().count() > MAX {
        let mut t: String = message.chars().take(MAX).collect();
        t.push('');
        t
    } else {
        message
    }
}

/// A diagnostic for a tooling failure (validator missing or crashed), pinned to
/// the target's first line so it's visible in both the CLI and the editor.
fn tool_error(a: &Assembled, message: String) -> Diag {
    Diag {
        path: a.target.clone(),
        line: 1,
        col: 1,
        len: 1,
        severity: Severity::Error,
        message,
        source: "glslint",
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // test code: unwrap IS the assertion
mod tests {
    use super::*;
    use crate::assemble::{Assembled, Loc, Stage};
    use std::path::PathBuf;

    fn assembled(map: Vec<Option<Loc>>, source: &str) -> Assembled {
        Assembled {
            source: source.to_string(),
            stage: Stage::Fragment,
            map,
            target: PathBuf::from("/proj/draw.frag.glsl"),
            note: None,
        }
    }

    // --- missing-validator error: names the fix for the platform it's on ---

    #[test]
    fn missing_glslang_message_names_an_installer_and_the_override() {
        let m = missing_glslang_message();
        // The env override applies everywhere; the installer is platform-specific.
        assert!(m.contains("GLSLINT_GLSLANG"), "no override hint: {m}");
        let installer = if cfg!(target_os = "macos") {
            "brew install glslang"
        } else if cfg!(target_os = "windows") {
            "Vulkan SDK"
        } else {
            "glslang-tools"
        };
        assert!(
            m.contains(installer),
            "no install hint for this platform: {m}"
        );
        // print_diag renders one diagnostic per line; a newline would split it.
        assert!(!m.contains('\n'), "message must stay single-line: {m}");
    }

    // --- parse_located: the `<str>:<line>: 'token' : message` grammar ---

    #[test]
    fn parse_located_extracts_line_token_and_verbatim_message() {
        let (line, token, msg) =
            parse_located("0:5: 'undefined_a' : undeclared identifier ").unwrap();
        assert_eq!(line, 5);
        assert_eq!(token.as_deref(), Some("undefined_a"));
        // The message is kept verbatim, glslang's leading 'token' and all.
        assert_eq!(msg, "'undefined_a' : undeclared identifier");
    }

    #[test]
    fn parse_located_empty_token_becomes_none() {
        let (line, token, msg) = parse_located("0:5: '' : compilation terminated ").unwrap();
        assert_eq!(line, 5);
        assert_eq!(token, None);
        assert!(msg.contains("compilation terminated"));
    }

    #[test]
    fn parse_located_file_level_messages_have_no_prefix() {
        // A bad `#version` and its follow-on carry no `0:LINE:` prefix → None,
        // so they route to the line-1 fallback rather than a bogus location.
        assert!(
            parse_located("#version: only version 300, 310, and 320 support the es profile")
                .is_none()
        );
        assert!(parse_located("version not supported").is_none());
    }

    // --- locate_token: column refinement from the offending token ---

    #[test]
    fn locate_token_returns_char_column_and_length() {
        let line = "  float alpha = nope;";
        let (col, len) = locate_token(line, Some("nope")).unwrap();
        assert_eq!(len, 4);
        assert_eq!(col, line.find("nope").unwrap() as u32 + 1);
    }

    #[test]
    fn locate_token_column_is_char_based_not_byte_based() {
        // A multibyte char before the token: the column must count chars, not bytes
        // (the LSP/CLI both treat `col` as a character offset).
        let line = "x = café + bad;"; // 'é' is 2 bytes, 1 char
        let (col, _) = locate_token(line, Some("bad")).unwrap();
        let char_col = line.chars().position(|c| c == 'b').unwrap() as u32 + 1;
        let byte_col = line.find("bad").unwrap() as u32 + 1;
        assert_eq!(col, char_col);
        assert_ne!(col, byte_col);
    }

    #[test]
    fn locate_token_skips_operators_and_absent_tokens() {
        assert_eq!(locate_token("a = b;", Some("=")), None); // punctuation: not hunted
        assert_eq!(locate_token("float x;", Some("zzz")), None); // not present
        assert_eq!(locate_token("float x;", None), None); // no token quoted
    }

    #[test]
    fn locate_token_matches_whole_words_only() {
        // Skips `speed` inside `speedFactor`, lands on the standalone occurrence.
        let line = "float speedFactor; x = speed;";
        let (col, len) = locate_token(line, Some("speed")).unwrap();
        assert_eq!(len, 5);
        assert_eq!(col, line.rfind("speed").unwrap() as u32 + 1);
        // `pos` must not match inside `position`.
        assert_eq!(locate_token("vec2 position;", Some("pos")), None);
    }

    // --- map_located: translate an assembled line back to the original file ---

    #[test]
    fn map_located_surfaces_injected_code_errors_at_line_one() {
        // map[0] = None → glslint owns that assembled line. A real error there is a
        // regression in our injected code; surface it (don't drop it) at line 1.
        let a = assembled(vec![None], "#version 300 es\n");
        let d = map_located(&a, 1, None, Severity::Error, "boom".into()).unwrap();
        assert_eq!(d.line, 1);
        assert_eq!(d.path, a.target);
        assert!(d.message.contains("glslint-injected"));
    }

    #[test]
    fn map_located_retargets_to_the_injected_module_file() {
        // An error on an assembled line that came from an injected module must
        // point at THAT module, not the file under check.
        let module = PathBuf::from("/proj/windUniforms.glsl");
        let a = assembled(
            vec![
                None,
                Some(Loc {
                    path: module.clone(),
                    line: 3,
                }),
            ],
            "#version 300 es\nfloat uMax;\n",
        );
        let d = map_located(&a, 2, Some("uMax"), Severity::Error, "boom".into()).unwrap();
        assert_eq!(d.path, module);
        assert_eq!(d.line, 3);
    }

    #[test]
    fn map_located_truncates_giant_messages() {
        let a = assembled(
            vec![Some(Loc {
                path: PathBuf::from("/proj/x.frag.glsl"),
                line: 1,
            })],
            "x\n",
        );
        let giant = format!("'=' : cannot convert from {}", "a".repeat(500));
        let d = map_located(&a, 1, None, Severity::Error, giant).unwrap();
        assert!(d.message.chars().count() <= 201);
        assert!(d.message.ends_with(''));
    }

    // --- parse_output: cascade collapse + file-level fallback ---

    #[test]
    fn parse_output_collapses_cascade_to_first_per_line() {
        // Root cause + derived giant message + terminator + summary, all from one
        // bad line → exactly one diagnostic (the root cause) survives.
        let a = assembled(
            vec![Some(Loc {
                path: PathBuf::from("/proj/x.frag.glsl"),
                line: 7,
            })],
            "ignored\n",
        );
        let out = "x.frag.glsl\n\
                   ERROR: 0:1: 'speed' : no such field in structure 'wind'\n\
                   ERROR: 0:1: '=' :  cannot convert from a-giant-block-type\n\
                   ERROR: 0:1: '' : compilation terminated \n\
                   ERROR: 1 compilation errors.  No code generated.\n";
        let diags = parse_output(&a, out);
        assert_eq!(diags.len(), 1);
        assert!(diags[0].message.contains("no such field"));
        assert_eq!(diags[0].line, 7);
    }

    #[test]
    fn parse_output_routes_file_level_errors_to_line_one() {
        let a = assembled(vec![None], "#version 999 es\n");
        let out = "stdin\n\
                   ERROR: #version: only version 300, 310, and 320 support the es profile\n\
                   ERROR: version not supported\n\
                   ERROR: 1 compilation errors.  No code generated.\n";
        let diags = parse_output(&a, out);
        assert!(!diags.is_empty());
        assert!(diags.iter().all(|d| d.line == 1));
        assert!(diags.iter().any(|d| d.message.contains("version")));
    }

    // --- embedded shaders: JS/TS tagged templates ---

    /// Whether glslangValidator/glslang is on PATH, so the validation-dependent
    /// assertions can run (they do in CI, which installs glslang-tools).
    fn glslang_on_path() -> bool {
        ["glslangValidator", "glslang"].iter().any(|b| {
            Command::new(b)
                .arg("--version")
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()
                .is_ok()
        })
    }

    #[test]
    fn embedded_interpolation_is_lints_only_with_a_note() {
        // The interpolation path never touches glslang, so this runs everywhere.
        let src = include_str!("../tests/fixtures/interpolated.ts");
        let diags = check_source(Path::new("interpolated.ts"), src);

        // One note per interpolated template, at each template's opening line (the
        // `fs` and `legacy` declarations, at host lines 3 and 14).
        let notes: Vec<_> = diags
            .iter()
            .filter(|d| d.severity == Severity::Note)
            .collect();
        assert_eq!(notes.len(), 2, "diags: {diags:#?}");
        assert_eq!(notes[0].line, 3);
        assert_eq!(notes[1].line, 14);
        assert!(notes.iter().all(|d| d.source == "embed"));

        // The ES3-legacy lints still fire through the interpolation, mapped to the
        // host lines: `varying` on line 16, `gl_FragColor` on line 17.
        let varying = diags
            .iter()
            .find(|d| d.message.contains("varying"))
            .expect("varying lint");
        assert_eq!(varying.severity, Severity::Warning);
        assert_eq!(varying.line, 16);
        let frag = diags
            .iter()
            .find(|d| d.message.contains("gl_FragColor"))
            .expect("gl_FragColor lint");
        assert_eq!(frag.line, 17);

        // No glslang errors — the validator was skipped for both templates.
        assert!(diags.iter().all(|d| d.source != "glslang"));
    }

    #[test]
    fn embedded_error_maps_to_the_host_template_line() {
        let src = include_str!("../tests/fixtures/tagged.ts");
        let diags = check_source(Path::new("tagged.ts"), src);

        if glslang_on_path() {
            // The undeclared `nope` sits on host line 8; the clean `vs` yields
            // nothing. Exactly one glslang error, on line 8.
            let errs: Vec<_> = diags
                .iter()
                .filter(|d| d.severity == Severity::Error)
                .collect();
            assert_eq!(errs.len(), 1, "diags: {diags:#?}");
            assert_eq!(errs[0].line, 8);
            assert_eq!(errs[0].source, "glslang");
            assert!(errs[0].message.contains("nope"));
        } else {
            // Without a validator, the missing-tool error is still mapped into the
            // template span (the `fs` template opens on host line 4), never left at
            // the assembled unit's line 1.
            assert!(diags.iter().any(|d| d.line == 4 && d.source == "glslint"));
        }
    }

    #[test]
    fn embedded_stage_guess_does_not_false_positive_on_valid_shaders() {
        // Regression for the vertex-only-builtin class: a `gl_Position`-free vertex
        // shader (transform feedback) and a plain fragment shader are both valid and
        // must draw no error, even though neither has an obvious stage signal.
        if !glslang_on_path() {
            return;
        }
        let src = include_str!("../tests/fixtures/stages.ts");
        let diags = check_source(Path::new("stages.ts"), src);
        assert!(
            diags.iter().all(|d| d.severity != Severity::Error),
            "unexpected errors on valid shaders: {diags:#?}"
        );
    }
}