Skip to main content

bynk_driver/
tsc_report.rs

1//! #3068: report a `tsc` failure on generated TypeScript as a Bynk diagnostic,
2//! `bynk.codegen.tsc_failed`, at the Bynk source the failing line came from.
3//!
4//! A program that passed the checker never *should* produce TypeScript that
5//! `tsc` rejects, so such a failure is a compiler bug, and a raw
6//! `out/workers/room/handlers.ts(120,74): error TS2345` line is no use to the
7//! person who hit it. This module parses `tsc`'s output, maps each error's line
8//! back through the emitted `.ts.map` (ADR 0103: line-level, each generated line
9//! mapped to its nearest enclosing statement), and builds a
10//! [`ProjectFailure`] so the usual renderers print it like any other diagnostic.
11//!
12//! Mapping is line-level only (the maps carry no useful column), so the Bynk span
13//! is the whole mapped source line; the TS column stays in the attached note. An
14//! error that cannot be mapped is still reported, at the project level.
15
16use crate::emsg;
17use std::collections::BTreeMap;
18use std::path::{Path, PathBuf};
19
20use crate::npm_install::PackageManager;
21use bynk_project::AttributedError;
22use bynk_syntax::error::CompileError;
23use bynk_syntax::span::Span;
24
25use crate::coverage::SourceMap;
26use crate::project::ProjectFailure;
27
28/// Where to report a compiler bug.
29const REPORT_URL: &str = "https://github.com/bynk-lang/bynk/issues";
30/// At most this many distinct Bynk locations are reported; the rest are counted.
31const MAX_LOCATIONS: usize = 10;
32
33pub const CODE: &str = "bynk.codegen.tsc_failed";
34
35/// One `error TSnnnn` record from `tsc`'s output.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct TscError {
38    /// The file as `tsc` printed it.
39    pub file: String,
40    /// 1-based line and column in the generated file.
41    pub line: usize,
42    pub col: usize,
43    /// `TS2345`.
44    pub code: String,
45    /// The message, continuation lines joined with newlines.
46    pub message: String,
47}
48
49/// Parse `tsc --pretty false` output into its error records. Lines that are not
50/// records (the `Found N errors` footer, blanks) are ignored; an indented line
51/// continues the previous record's message.
52pub fn parse_tsc_output(text: &str) -> Vec<TscError> {
53    let mut out: Vec<TscError> = Vec::new();
54    for raw in text.lines() {
55        let line = raw.trim_end_matches('\r');
56        if let Some(rec) = parse_record(line) {
57            out.push(rec);
58        } else if line.starts_with(char::is_whitespace)
59            && !line.trim().is_empty()
60            && let Some(last) = out.last_mut()
61        {
62            last.message.push('\n');
63            last.message.push_str(line.trim_end());
64        }
65    }
66    out
67}
68
69/// `path(line,col): error TS1234: message`. The path may itself contain
70/// parentheses, so split on the *last* `(digits,digits): error TS` marker.
71fn parse_record(line: &str) -> Option<TscError> {
72    let marker = "): error TS";
73    let end = line.find(marker)?;
74    let head = &line[..end];
75    let open = head.rfind('(')?;
76    let file = &head[..open];
77    let (l, c) = head[open + 1..].split_once(',')?;
78    let (line_no, col) = (l.trim().parse().ok()?, c.trim().parse().ok()?);
79    let rest = &line[end + marker.len()..];
80    let (digits, message) = rest.split_once(':')?;
81    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
82        return None;
83    }
84    Some(TscError {
85        file: file.to_string(),
86        line: line_no,
87        col,
88        code: format!("TS{digits}"),
89        message: message.trim().to_string(),
90    })
91}
92
93/// Normalise a source-map `sources` entry to compare with a snapshot's path.
94fn norm(p: &str) -> String {
95    let p = p.replace('\\', "/");
96    let mut s = p.as_str();
97    while let Some(r) = s.strip_prefix("./").or_else(|| s.strip_prefix("../")) {
98        s = r;
99    }
100    s.to_string()
101}
102
103/// The text of the snapshot a map's source name refers to.
104fn find_snapshot<'a>(
105    name: &str,
106    snapshots: &'a [(PathBuf, String)],
107) -> Option<(&'a Path, &'a str)> {
108    let name = norm(name);
109    snapshots
110        .iter()
111        .filter_map(|(p, t)| {
112            let key = norm(&p.to_string_lossy());
113            (key == name
114                || key.ends_with(&format!("/{name}"))
115                || name.ends_with(&format!("/{key}")))
116            .then_some((key.len(), p.as_path(), t.as_str()))
117        })
118        .max_by_key(|(len, _, _)| *len)
119        .map(|(_, p, t)| (p, t))
120}
121
122/// Where `tsc` may have meant `file` from: it prints paths relative to the
123/// directory it ran in, which is not always the emit root.
124fn generated_candidates(file: &str, emit_root: &Path) -> Vec<PathBuf> {
125    let p = Path::new(file);
126    let mut c = vec![p.to_path_buf()];
127    if p.is_relative() {
128        c.push(emit_root.join(p));
129        if let Some(parent) = emit_root.parent() {
130            c.push(parent.join(p));
131        }
132        // `out/workers/x.ts` printed against an emit root named `out`.
133        if let Some(name) = emit_root.file_name()
134            && let Ok(rest) = p.strip_prefix(name)
135        {
136            c.push(emit_root.join(rest));
137        }
138    }
139    c
140}
141
142/// Where one `tsc` error resolved to, if it did.
143struct Resolved {
144    source: PathBuf,
145    /// 0-based line in the Bynk source.
146    line: usize,
147    span: Span,
148    /// The generated line's text, for the secondary note.
149    generated: Option<String>,
150}
151
152fn resolve(err: &TscError, emit_root: &Path, snapshots: &[(PathBuf, String)]) -> Option<Resolved> {
153    for ts in generated_candidates(&err.file, emit_root) {
154        let Ok(map_text) = std::fs::read_to_string(format!("{}.map", ts.display())) else {
155            continue;
156        };
157        let Some(map) = SourceMap::parse(&map_text) else {
158            continue;
159        };
160        let Some(gen_line) = err.line.checked_sub(1) else {
161            continue;
162        };
163        let Some((name, src_line)) = map.resolve(gen_line) else {
164            continue;
165        };
166        let Some((path, text)) = find_snapshot(name, snapshots) else {
167            continue;
168        };
169        let line = src_line as usize;
170        let mut start = 0usize;
171        let mut found = None;
172        for (i, l) in text.split_inclusive('\n').enumerate() {
173            if i == line {
174                let body = l.trim_end_matches(['\n', '\r']);
175                let lead = body.len() - body.trim_start().len();
176                found = Some((start + lead, start + body.trim_end().len().max(lead)));
177                break;
178            }
179            start += l.len();
180        }
181        let Some((s, e)) = found else {
182            continue;
183        };
184        let generated = std::fs::read_to_string(&ts)
185            .ok()
186            .and_then(|g| g.lines().nth(err.line - 1).map(|l| l.trim().to_string()));
187        return Some(Resolved {
188            source: path.to_path_buf(),
189            line,
190            span: Span::new(s, e),
191            generated,
192        });
193    }
194    None
195}
196
197/// Build the diagnostics for a failed `tsc` run, or `None` when its output holds
198/// no `error TS` record (a crash, an out-of-memory, a missing install): that is a
199/// toolchain failure, not evidence of a compiler bug, and the caller reports the
200/// raw output as it always did.
201///
202/// `emit_root` is the directory the TypeScript (and its `.map`s) was written to;
203/// `snapshots` and `display_root` are the build's, so the Bynk file renders with
204/// source context.
205pub fn diagnose(
206    tsc_output: &str,
207    emit_root: &Path,
208    snapshots: &[(PathBuf, String)],
209    display_root: &Path,
210) -> Option<ProjectFailure> {
211    let errors = parse_tsc_output(tsc_output);
212    if errors.is_empty() {
213        return None;
214    }
215    // One diagnostic per Bynk location; several TS errors on one statement
216    // are notes on the same diagnostic. `None` collects the unmapped ones.
217    type Group = (Option<Resolved>, Vec<TscError>);
218    let mut order: Vec<(Option<(PathBuf, usize)>, Group)> = Vec::new();
219    let mut index: BTreeMap<Option<(PathBuf, usize)>, usize> = BTreeMap::new();
220    for err in errors {
221        let r = resolve(&err, emit_root, snapshots);
222        let key = r.as_ref().map(|r| (r.source.clone(), r.line));
223        match index.get(&key) {
224            Some(&i) => order[i].1.1.push(err),
225            None => {
226                index.insert(key.clone(), order.len());
227                order.push((key, (r, vec![err])));
228            }
229        }
230    }
231    let total = order.len();
232    let mut out = Vec::new();
233    for (_, (resolved, errs)) in order.into_iter().take(MAX_LOCATIONS) {
234        let (source_path, span, mapped) = match &resolved {
235            Some(r) => (Some(r.source.clone()), r.span, true),
236            None => (None, Span::new(0, 0), false),
237        };
238        let mut message =
239            String::from("the generated TypeScript for this code does not type-check");
240        if !mapped {
241            message.push_str(" (no Bynk source location could be determined for it)");
242        }
243        let mut e = CompileError::new(CODE, span, message).with_note(format!(
244            "this is a bug in the Bynk compiler, not in your program. Please report it at {REPORT_URL} with this output and, if you can, a minimal repro"
245        ));
246        for t in &errs {
247            e = e.with_note(format!(
248                "tsc: {} at {}({},{}): {}",
249                t.code,
250                t.file,
251                t.line,
252                t.col,
253                t.message.replace('\n', "\n      ")
254            ));
255        }
256        if let Some(g) = resolved.as_ref().and_then(|r| r.generated.as_deref()) {
257            e = e.with_note(format!("generated: {g}"));
258        }
259        out.push(AttributedError::new(source_path, e));
260    }
261    if total > MAX_LOCATIONS {
262        out.push(AttributedError::new(
263            None,
264            CompileError::new(
265                CODE,
266                Span::new(0, 0),
267                format!(
268                    "and {} more location(s) where the generated TypeScript does not type-check",
269                    total - MAX_LOCATIONS
270                ),
271            ),
272        ));
273    }
274    Some(ProjectFailure {
275        errors: out,
276        snapshots: snapshots.to_vec(),
277        display_root: display_root.to_path_buf(),
278    })
279}
280
281/// What running `tsc` over an emitted tree came to.
282enum Ran {
283    Passed,
284    /// `tsc` ran and failed; its combined stdout and stderr.
285    Failed(String),
286    /// No runner could be started; why, for the message.
287    Unavailable(Vec<String>),
288}
289
290/// The `tsc` ladder `bynk test` uses (`tsc`, then the package manager's runner
291/// fetching `typescript@<major>`), type-checking only. There is no `tsx` rung:
292/// it does not type-check.
293fn run_tsc(tsconfig: &Path, manager: PackageManager) -> Ran {
294    use std::process::Stdio;
295    let runners = crate::tools::Ladder::tsc(manager);
296    let mut failures = Vec::new();
297    for rung in runners.rungs() {
298        let mut cmd = rung.command();
299        cmd.arg("-p")
300            .arg(tsconfig)
301            .args(["--noEmit", "--pretty", "false"]);
302        match cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).output() {
303            Ok(o) if o.status.success() => return Ran::Passed,
304            Ok(o) => {
305                let mut text = String::from_utf8_lossy(&o.stdout).into_owned();
306                let err = String::from_utf8_lossy(&o.stderr);
307                if !err.trim().is_empty() {
308                    text.push('\n');
309                    text.push_str(&err);
310                }
311                return Ran::Failed(text);
312            }
313            Err(e) => failures.push(rung.start_failure(&e)),
314        }
315    }
316    Ran::Unavailable(failures)
317}
318
319/// A fresh, empty directory only this process can use: created with `create_dir`
320/// (which fails if the path exists, so a leftover from a killed run or one a
321/// local user pre-created is never reused) under an unpredictable name, mode 0700
322/// on Unix. Retries on a collision.
323fn private_temp_dir() -> std::io::Result<PathBuf> {
324    use std::hash::{BuildHasher, Hasher};
325    let mut last = None;
326    for _ in 0..16 {
327        // `RandomState` is randomly keyed per instance: unpredictable without a
328        // new dependency.
329        let r = std::collections::hash_map::RandomState::new()
330            .build_hasher()
331            .finish();
332        let path =
333            std::env::temp_dir().join(format!("bynk-check-emit-{}-{r:016x}", std::process::id()));
334        let mut b = std::fs::DirBuilder::new();
335        #[cfg(unix)]
336        std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700);
337        match b.create(&path) {
338            Ok(()) => return Ok(path),
339            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => last = Some(e),
340            Err(e) => return Err(e),
341        }
342    }
343    Err(last.unwrap_or_else(|| std::io::Error::other("no free temporary directory name")))
344}
345
346/// `bynk check --emit` for one project (#3068): generate the Workers output into
347/// a temporary directory and type-check it, reporting a `tsc` failure as
348/// `bynk.codegen.tsc_failed`. Run after the ordinary check has passed. `true`
349/// when the generated TypeScript type-checks.
350pub fn check_emit(prog: &str, input: &Path, short: bool) -> bool {
351    let options = match crate::try_project_options(input) {
352        Ok(o) => o.target(crate::project::BuildTarget::Workers),
353        Err(e) => {
354            emsg!("{prog}: error: {e}");
355            return false;
356        }
357    };
358    let out = match crate::project::compile_project(&options) {
359        Ok(o) => o,
360        Err(failure) => {
361            // The check just passed, so this is itself unexpected; say so plainly.
362            crate::print_project_failure(&failure);
363            return false;
364        }
365    };
366    let manager = crate::npm_install::system_tool_manager(input);
367    let tmp = match private_temp_dir() {
368        Ok(t) => t,
369        Err(e) => {
370            emsg!("{prog}: error: could not create a temporary directory: {e}");
371            return false;
372        }
373    };
374    let root = tmp.join("out");
375    let result = (|| {
376        for (path, doc) in &out.artefacts.docs {
377            if let Err(e) = crate::write_document(path, doc, &out.artefacts.docs, &root) {
378                emsg!(
379                    "{prog}: error: could not write {}: {e}",
380                    root.join(path).display()
381                );
382                return false;
383            }
384        }
385        match run_tsc(&root.join("tsconfig.json"), manager) {
386            Ran::Passed => true,
387            Ran::Unavailable(why) => {
388                emsg!(
389                    "{prog}: error: `check --emit` needs `tsc` (with Node.js) to type-check the generated TypeScript, and found none that runs."
390                );
391                for w in &why {
392                    eprintln!("  {w}");
393                }
394                eprintln!(
395                    "  Install it with `{}`.",
396                    manager.global_install(&crate::tools::pins::typescript_spec())
397                );
398                false
399            }
400            Ran::Failed(text) => {
401                match diagnose(&text, &root, &out.snapshots, &out.display_root) {
402                    Some(f) if short => crate::print_project_failure_short(&f),
403                    Some(f) => crate::print_project_failure(&f),
404                    // No `error TS` record: a crash, not evidence of a compiler bug.
405                    None => emsg!("{prog}: error: tsc failed on the generated TypeScript:\n{text}"),
406                }
407                false
408            }
409        }
410    })();
411    let _ = std::fs::remove_dir_all(&tmp);
412    result
413}
414
415/// [`check_emit`] over a project or, at a workspace root, every member.
416pub fn check_emit_all(prog: &str, input: &Path, short: bool, each: bool) -> bool {
417    if let Ok(Some(Ok(ws))) = crate::workspace_at_each(input, each) {
418        let mut ok = true;
419        for m in &ws.members {
420            ok &= check_emit(prog, &crate::member_dir(input, m), short);
421        }
422        return ok;
423    }
424    check_emit(prog, input, short)
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430
431    #[test]
432    fn parses_records_footer_and_continuations() {
433        let text = "out/a.ts(120,74): error TS2345: Argument of type 'X' is not assignable.\n  Type 'X' is missing property 'Clock'.\nout/b (1).ts(3,4): error TS2322: Nope.\n\nFound 2 errors in 2 files.\n";
434        let errs = parse_tsc_output(text);
435        assert_eq!(errs.len(), 2);
436        assert_eq!(errs[0].file, "out/a.ts");
437        assert_eq!((errs[0].line, errs[0].col), (120, 74));
438        assert_eq!(errs[0].code, "TS2345");
439        assert!(errs[0].message.contains("missing property 'Clock'"));
440        assert_eq!(errs[1].file, "out/b (1).ts");
441        assert_eq!(errs[1].line, 3);
442    }
443
444    #[test]
445    fn non_records_are_not_errors() {
446        assert!(parse_tsc_output("error: spawn tsc ENOENT\nkilled\n").is_empty());
447        assert!(
448            diagnose(
449                "FATAL ERROR: heap out of memory",
450                Path::new("out"),
451                &[],
452                Path::new("")
453            )
454            .is_none()
455        );
456    }
457
458    #[test]
459    fn unmapped_errors_are_still_reported() {
460        let f = diagnose(
461            "out/gone.ts(1,1): error TS2322: Nope.\n",
462            Path::new("/nonexistent/out"),
463            &[],
464            Path::new(""),
465        )
466        .expect("a record is a failure");
467        assert_eq!(f.errors.len(), 1);
468        assert!(f.errors[0].source_path.is_none());
469        assert_eq!(f.errors[0].error.category, CODE);
470        assert!(
471            f.errors[0]
472                .error
473                .message
474                .contains("no Bynk source location")
475        );
476    }
477}