Skip to main content

bynk_wasm/
lib.rs

1//! The Bynk compiler as a wasm module for the in-browser REPL/playground (the
2//! in-browser track, slice 3 — ADR 0139).
3//!
4//! One entry — `bynk_compile` (wasm) / `compile` (native) — takes an in-memory
5//! Bynk source and returns a runnable **JavaScript module graph** plus diagnostics,
6//! with **no filesystem and no `tsc`**:
7//!
8//! ```text
9//! source ─▶ bynk_emit::compile_in_memory (Bundle / Browser)  ─▶ ProjectOutput (TS)
10//!        ─▶ bynk_driver::strip::strip_project_to_js                   ─▶ ProjectOutput (JS)
11//!        ─▶ { files: [{ path, kind, contents, map? }], diagnostics }
12//! ```
13//!
14//! The pipeline reuses the on-disk path wholesale (first-party injection, the
15//! per-platform binding, the strip-only emitter), so the returned graph is the
16//! complete set the browser links: the user module, the runtime modules it
17//! reaches (`__bynk_runtime/<module>.js`, ADR 0615), the `bynk-browser.js`
18//! binding, and `compose.js`. The crate compiles to `wasm32`
19//! (the `cdylib`); the same logic is exercised natively (the `rlib`) by the
20//! slice-3 tests, with the browser harness deferred to the REPL shell (slice 4).
21
22pub mod reference;
23
24use std::collections::HashMap;
25use std::path::PathBuf;
26use std::sync::Arc;
27
28use bynk_check::checker::{TyId, Types};
29use bynk_check::expr_types::type_at_offset;
30use bynk_check::firstparty::Platform;
31use bynk_check::locals::{LocalBinding, locals_at};
32use bynk_driver::project::{
33    AttributedError, BuildTarget, InMemoryAnalysis, analyse_in_memory, analyse_in_memory_project,
34    analyse_in_memory_with_types, compile_in_memory, slash_key,
35};
36use bynk_ide::completion;
37use bynk_model::entry::{EntryHandler, EntryShape};
38use bynk_syntax::CompileError;
39use bynk_syntax::span::Span;
40
41/// Where an emitted module comes from, so a consumer can show only the code
42/// that corresponds to what the user wrote (#2425). The graph itself is
43/// unchanged: the sandbox still links every file.
44#[derive(serde::Serialize, Clone, Copy, PartialEq, Eq, Debug)]
45#[serde(rename_all = "lowercase")]
46pub enum FileKind {
47    /// A module authored from the user's source (e.g. `hello/world.js`).
48    User,
49    /// The generated wiring that composes the program (`compose.js`).
50    Wiring,
51    /// The reached `__bynk_runtime/*.js` modules, the platform binding, and
52    /// injected first-party units (`bynk.js`, `bynk/locale/types.js`, …).
53    Support,
54}
55
56/// One emitted JavaScript module of the compiled program.
57#[derive(serde::Serialize)]
58pub struct EmittedFile {
59    /// Whether this is the user's code, the wiring, or support code.
60    pub kind: FileKind,
61    /// Output-relative path (e.g. `main.js`, `__bynk_runtime/result.js`, `bynk-browser.js`).
62    pub path: String,
63    /// The JavaScript source.
64    pub contents: String,
65    /// #2705: a source-map v3 JSON document mapping this module's JavaScript
66    /// lines back to the Bynk source (declaration and handler anchors, ADR
67    /// 0569). Present only on `user` modules; omitted for wiring and support
68    /// files. `sources` names the Bynk file as the emitter does; there is no
69    /// `sourcesContent` (the host holds the source).
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub map: Option<String>,
72}
73
74/// Rename a source map's single source to the module's logical path (the name
75/// the emitter was handed is the host's absolute path, which a browser has no
76/// use for and should not see). `None` if the map is not the expected JSON.
77fn with_source_name(map: &str, name: &str) -> Option<String> {
78    let mut v: serde_json::Value = serde_json::from_str(map).ok()?;
79    // A playground compile is one in-memory module, so its map has one source.
80    debug_assert_eq!(v.get("sources")?.as_array()?.len(), 1);
81    for s in v.get_mut("sources")?.as_array_mut()? {
82        *s = name.into();
83    }
84    serde_json::to_string(&v).ok()
85}
86
87/// A diagnostic flattened for the JS side, with a 1-indexed line/column.
88#[derive(serde::Serialize)]
89pub struct Diagnostic {
90    /// The source module the diagnostic belongs to, if attributable.
91    pub path: Option<String>,
92    pub line: usize,
93    pub col: usize,
94    /// Byte offsets of the diagnostic span (for the editor's inline lint range).
95    pub from: usize,
96    pub to: usize,
97    /// `"error"`, `"warning"` or `"hint"` (#2838).
98    pub severity: String,
99    /// The stable diagnostic category (e.g. `bynk.parse.expected_token`).
100    pub category: String,
101    pub message: String,
102    /// The registry's one-line summary of this code, so a consumer needs no copy
103    /// of the table. `null` only for a code that is not in the registry. (#2679)
104    pub summary: Option<String>,
105    /// A link to learn more: the curated Book page when the code has one (what
106    /// the LSP offers as `codeDescription`), otherwise the diagnostic index
107    /// section for the code's category. For the curated blurb and example, call
108    /// `bynk_explain(category)`. (#2679)
109    pub href: String,
110    /// Finding #47: previously dropped entirely for the playground. Plain
111    /// text, not positioned — the CLI/LSP renderers already carry the
112    /// harder problem of a label's span belonging to a different module
113    /// than `path` (finding #46); this flattening keeps to text only rather
114    /// than getting that wrong here too.
115    pub notes: Vec<String>,
116    pub labels: Vec<String>,
117}
118
119/// The outcome of compiling one in-memory source.
120#[derive(serde::Serialize)]
121pub struct CompileResult {
122    /// Whether a runnable JavaScript graph was produced.
123    pub ok: bool,
124    /// The runnable JS module graph (empty on failure).
125    pub files: Vec<EmittedFile>,
126    /// Errors on failure, or non-failing warnings on success.
127    pub diagnostics: Vec<Diagnostic>,
128    /// #2695: the `on call(...)` handler of each `service` in the program,
129    /// described from the checker's resolved types so a host can build a run's
130    /// arguments without parsing the source. Empty on failure.
131    pub entries: Vec<Entry>,
132}
133
134/// One service's `on call(...)` handler, for the host's Arguments row.
135#[derive(serde::Serialize)]
136pub struct Entry {
137    /// The context the service is declared in (`app.demo`).
138    pub unit: String,
139    pub service: String,
140    pub params: Vec<EntryParam>,
141    /// The declared return type, as the checker displays it.
142    pub returns: String,
143}
144
145/// One handler parameter.
146#[derive(serde::Serialize)]
147pub struct EntryParam {
148    pub name: String,
149    /// The declared type, as the checker displays it (`Slug`, `List[Int]`).
150    #[serde(rename = "type")]
151    pub ty: String,
152    /// The base type the declared type is, refines or wraps (`String` for
153    /// `Slug`); `null` for a record, sum or collection.
154    pub base: Option<&'static str>,
155    /// Whether the type is a named refined type (`type Slug = String where
156    /// ...`): a value is a `base` value its `T.of` accepts.
157    pub refined: bool,
158    /// The structural description, see the README.
159    pub shape: serde_json::Value,
160}
161
162fn shape_json(s: &EntryShape) -> serde_json::Value {
163    use serde_json::{Value, json};
164    let fields = |fs: &[(String, EntryShape)]| -> Vec<Value> {
165        fs.iter()
166            .map(|(n, s)| json!({ "name": n, "shape": shape_json(s) }))
167            .collect()
168    };
169    match s {
170        EntryShape::Base(b) => json!({ "kind": "base", "base": b }),
171        EntryShape::Refined { name, base } => {
172            json!({ "kind": "refined", "name": name, "base": base })
173        }
174        EntryShape::Opaque { name, base } => {
175            json!({ "kind": "opaque", "name": name, "base": base })
176        }
177        EntryShape::Record { name, fields: fs } => {
178            json!({ "kind": "record", "name": name, "fields": fields(fs) })
179        }
180        EntryShape::Sum { name, variants } => {
181            let vs: Vec<Value> = variants
182                .iter()
183                .map(|(n, fs)| json!({ "name": n, "fields": fields(fs) }))
184                .collect();
185            json!({ "kind": "sum", "name": name, "variants": vs })
186        }
187        EntryShape::List(t) => json!({ "kind": "list", "element": shape_json(t) }),
188        EntryShape::Set(t) => json!({ "kind": "set", "element": shape_json(t) }),
189        EntryShape::Option(t) => json!({ "kind": "option", "element": shape_json(t) }),
190        EntryShape::Map(k, v) => {
191            json!({ "kind": "map", "key": shape_json(k), "value": shape_json(v) })
192        }
193        EntryShape::Result(t, e) => {
194            json!({ "kind": "result", "ok": shape_json(t), "err": shape_json(e) })
195        }
196        EntryShape::Unit => json!({ "kind": "unit" }),
197        EntryShape::Named(name) => json!({ "kind": "named", "name": name }),
198        EntryShape::Recursive(name) => json!({ "kind": "recursive", "name": name }),
199        EntryShape::Other(display) => json!({ "kind": "other", "display": display }),
200    }
201}
202
203fn to_entries(handlers: Vec<EntryHandler>) -> Vec<Entry> {
204    handlers
205        .into_iter()
206        .map(|h| Entry {
207            unit: h.unit,
208            service: h.service,
209            returns: h.returns,
210            params: h
211                .params
212                .into_iter()
213                .map(|p| EntryParam {
214                    name: p.name,
215                    ty: p.ty,
216                    base: match &p.shape {
217                        EntryShape::Base(b) => Some(*b),
218                        EntryShape::Refined { base, .. } | EntryShape::Opaque { base, .. } => {
219                            Some(*base)
220                        }
221                        _ => None,
222                    },
223                    refined: matches!(p.shape, EntryShape::Refined { .. }),
224                    shape: shape_json(&p.shape),
225                })
226                .collect(),
227        })
228        .collect()
229}
230
231fn severity_str(err: &CompileError) -> &'static str {
232    match bynk_syntax::Severity::for_error(err) {
233        bynk_syntax::Severity::Error => "error",
234        bynk_syntax::Severity::Warning => "warning",
235        bynk_syntax::Severity::Hint => "hint",
236    }
237}
238
239/// The human-readable message carried by a caught panic payload, if any.
240fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
241    if let Some(s) = payload.downcast_ref::<&str>() {
242        (*s).to_string()
243    } else if let Some(s) = payload.downcast_ref::<String>() {
244        s.clone()
245    } else {
246        "unknown panic".to_string()
247    }
248}
249
250/// A synthetic `bynk.wasm.panic` diagnostic standing in for an internal compiler
251/// panic, so an unexpected `panic!`/index-out-of-bounds/`unreachable!` in the
252/// pipeline becomes a structured error rather than propagating past the boundary.
253fn panic_diagnostic(payload: Box<dyn std::any::Any + Send>) -> Diagnostic {
254    Diagnostic {
255        path: None,
256        line: 0,
257        col: 0,
258        from: 0,
259        to: 0,
260        severity: "error".to_string(),
261        category: "bynk.wasm.panic".to_string(),
262        message: format!("internal compiler panic: {}", panic_message(&*payload)),
263        summary: summary_of("bynk.wasm.panic"),
264        href: bynk_syntax::diagnostics::href("bynk.wasm.panic"),
265        notes: Vec::new(),
266        labels: Vec::new(),
267    }
268}
269
270/// Run a pipeline entry point, converting an unexpected panic into a diagnostic.
271///
272/// On the native `rlib` path (the tests and any host embedding) this genuinely
273/// unwinds the panic and returns `Err(diagnostic)`, so a reachable-in-principle
274/// `panic!` no longer propagates past the wasm boundary. On the actual
275/// `wasm32-unknown-unknown` target a panic still traps (`RuntimeError:
276/// unreachable`) because the stock target lowers unwinding to a trap — there the
277/// blast radius is bounded instead by the `console_error_panic_hook` (a legible
278/// console error and location) set in the wasm entry points, and this wrapper
279/// becomes effective for free if the playground build ever adopts wasm exception
280/// handling. Fixing the underlying panic sites remains the real fix (#717).
281///
282/// `Diagnostic` grew past clippy's large-`Err` threshold once `notes`/`labels`
283/// (finding #47) joined it; boxing it here would need every one of this
284/// module's several `Diagnostic { .. }` construction sites and its `serde`
285/// serialisation to route through a `Box` for one lint, so it's overridden
286/// instead — this is a single-error return on the panic path, not a hot loop.
287#[allow(clippy::result_large_err)]
288fn catch_panic<T>(f: impl FnOnce() -> T) -> Result<T, Diagnostic> {
289    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(panic_diagnostic)
290}
291
292/// The registry's one-line summary for a diagnostic `code`, if it is a registry code.
293fn summary_of(code: &str) -> Option<String> {
294    bynk_syntax::diagnostics::lookup(code).map(|d| d.summary.to_string())
295}
296
297/// What the compiler knows about a diagnostic code, for the playground's
298/// "learn more" affordance (#2679). `summary` is `null` only for a code not in
299/// the registry; `blurb`/`example` are present only for a curated code (the same
300/// table `bynk explain` prints); `href` is always set (see [`Diagnostic::href`]).
301#[derive(serde::Serialize)]
302pub struct Explanation {
303    pub code: String,
304    pub summary: Option<String>,
305    #[serde(skip_serializing_if = "Option::is_none")]
306    pub blurb: Option<String>,
307    #[serde(skip_serializing_if = "Option::is_none")]
308    pub example: Option<String>,
309    pub href: String,
310}
311
312/// Look up the explanation for `code`. Never fails: an unknown code yields
313/// `summary: null` and the diagnostic-index link.
314pub fn explain(code: &str) -> Explanation {
315    let curated = bynk_syntax::diagnostics::explain(code);
316    Explanation {
317        code: code.to_string(),
318        summary: summary_of(code),
319        blurb: curated.map(|e| e.blurb.to_string()),
320        example: curated.map(|e| e.example.to_string()),
321        href: bynk_syntax::diagnostics::href(code),
322    }
323}
324
325/// [`explain`] as a JSON string: `{ code, summary, blurb?, example?, href }`.
326pub fn explain_to_json(code: &str) -> String {
327    serde_json::to_string(&explain(code)).unwrap_or_else(|_| {
328        format!(
329            "{{\"code\":{code:?},\"summary\":null,\"href\":\"{}\"}}",
330            bynk_syntax::diagnostics::href("")
331        )
332    })
333}
334
335/// Flatten attributed errors to [`Diagnostic`]s, resolving line/col against the
336/// owning source where known (`sources`), else the user source (`fallback`).
337fn to_diagnostics(
338    errs: Vec<AttributedError>,
339    sources: &HashMap<PathBuf, String>,
340    fallback: &str,
341) -> Vec<Diagnostic> {
342    errs.into_iter()
343        .map(|a| {
344            let src = a
345                .source_path
346                .as_ref()
347                .and_then(|p| sources.get(p))
348                .map(String::as_str)
349                .unwrap_or(fallback);
350            let (line, col) = bynk_syntax::span::line_col(src, a.error.span.start);
351            Diagnostic {
352                path: a
353                    .source_path
354                    .as_ref()
355                    .map(|p| p.to_string_lossy().into_owned()),
356                line,
357                col,
358                from: a.error.span.start,
359                to: a.error.span.end,
360                severity: severity_str(&a.error).to_string(),
361                category: a.error.category.to_string(),
362                message: a.error.message.clone(),
363                summary: summary_of(a.error.category),
364                href: bynk_syntax::diagnostics::href(a.error.category),
365                notes: a.error.notes.clone(),
366                labels: a.error.labels.iter().map(|(_, msg)| msg.clone()).collect(),
367            }
368        })
369        .collect()
370}
371
372/// Compile a single in-memory Bynk source to a JavaScript module graph for the
373/// given platform (the playground passes [`Platform::Browser`]). Pure: no
374/// filesystem, no `tsc`. The in-process `Bundle` subset only; programs that reach
375/// Workers/Cloudflare-only shapes are reported as diagnostics (slice-2 platform
376/// lock), never silently mis-compiled.
377pub fn compile(source: &str, platform: Platform) -> CompileResult {
378    catch_panic(|| compile_inner(source, platform)).unwrap_or_else(|d| CompileResult {
379        ok: false,
380        files: Vec::new(),
381        diagnostics: vec![d],
382        entries: Vec::new(),
383    })
384}
385
386fn compile_inner(source: &str, platform: Platform) -> CompileResult {
387    match compile_in_memory(source, BuildTarget::Bundle, platform) {
388        Ok(out) => {
389            // The user's own modules: the only ones that get a source map.
390            let user_paths: HashMap<PathBuf, String> = out
391                .snapshots
392                .iter()
393                .map(|(p, _)| {
394                    (
395                        p.with_extension("js"),
396                        slash_key(p).to_string_lossy().into_owned(),
397                    )
398                })
399                .collect();
400            let only: std::collections::HashSet<PathBuf> = user_paths.keys().cloned().collect();
401            match bynk_driver::strip::strip_project_to_js_mapped(out, &only) {
402                Ok((js, mut maps)) => {
403                    // The user program is the single in-memory source, so warnings
404                    // resolve their line/col against it (the fallback).
405                    let diagnostics = to_diagnostics(js.warnings, &HashMap::new(), source);
406                    let entries = to_entries(js.entry_handlers);
407                    // #2148: the graph is the modules the browser links, so the
408                    // output's `package.json` (the ES-module marker for Node and
409                    // `tsc`) is left out.
410                    let files = js
411                        .artefacts
412                        .docs
413                        .into_iter()
414                        .filter(|(_, doc)| !matches!(doc, bynk_driver::project::Document::Json(_)))
415                        .map(|(path, doc)| {
416                            let kind = if user_paths.contains_key(&path) {
417                                FileKind::User
418                            } else if path == std::path::Path::new("compose.js") {
419                                FileKind::Wiring
420                            } else {
421                                FileKind::Support
422                            };
423                            // Injected first-party units are mapped too, but only
424                            // the user's own module is worth the bytes (#2705).
425                            let map = maps
426                                .remove(&path)
427                                .zip(user_paths.get(&path))
428                                .and_then(|(m, name)| with_source_name(&m, name));
429                            EmittedFile {
430                                kind,
431                                map,
432                                path: path.to_string_lossy().into_owned(),
433                                contents: doc.text(),
434                            }
435                        })
436                        .collect();
437                    CompileResult {
438                        ok: true,
439                        files,
440                        diagnostics,
441                        entries,
442                    }
443                }
444                // The emitter is strip-only (ADR 0136), so this is unreachable for a
445                // successful compile — surfaced as a diagnostic rather than a panic.
446                Err(e) => CompileResult {
447                    ok: false,
448                    files: Vec::new(),
449                    diagnostics: vec![Diagnostic {
450                        path: None,
451                        line: 0,
452                        col: 0,
453                        from: 0,
454                        to: 0,
455                        severity: "error".to_string(),
456                        category: "bynk.wasm.strip_failed".to_string(),
457                        message: e.to_string(),
458                        summary: summary_of("bynk.wasm.strip_failed"),
459                        href: bynk_syntax::diagnostics::href("bynk.wasm.strip_failed"),
460                        notes: Vec::new(),
461                        labels: Vec::new(),
462                    }],
463                    entries: Vec::new(),
464                },
465            }
466        }
467        Err(failure) => {
468            let sources: HashMap<PathBuf, String> = failure.snapshots.iter().cloned().collect();
469            CompileResult {
470                ok: false,
471                files: Vec::new(),
472                diagnostics: to_diagnostics(failure.errors, &sources, source),
473                entries: Vec::new(),
474            }
475        }
476    }
477}
478
479/// Compile to a JSON string — the wasm boundary representation of [`CompileResult`].
480pub fn compile_to_json(source: &str, platform: Platform) -> String {
481    serde_json::to_string(&compile(source, platform)).unwrap_or_else(|e| {
482        format!(
483            "{{\"ok\":false,\"files\":[],\"entries\":[],\"diagnostics\":[{{\"path\":null,\"line\":0,\"col\":0,\"from\":0,\"to\":0,\
484             \"severity\":\"error\",\"category\":\"bynk.wasm.serialize_failed\",\"message\":{:?}}}]}}",
485            e.to_string()
486        )
487    })
488}
489
490/// The result of formatting a single in-memory source (#2431).
491#[derive(serde::Serialize)]
492#[serde(untagged)]
493pub enum FormatResult {
494    Ok { ok: bool, formatted: String },
495    Err { ok: bool, error: String },
496}
497
498/// Format a source to the house style with default options. A source that does
499/// not parse yields the first error as `line:col: message`, never a panic.
500pub fn format(source: &str) -> FormatResult {
501    let run = || bynk_fmt::format_source(source, &bynk_fmt::FormatOptions::default());
502    match catch_panic(run) {
503        Ok(Ok(formatted)) => FormatResult::Ok {
504            ok: true,
505            formatted,
506        },
507        Ok(Err(e)) => {
508            // The formatter normalises CRLF first; locate against the same text.
509            let text = bynk_fmt::normalize_line_endings(source);
510            let error = e
511                .errors
512                .first()
513                .map(|err| {
514                    let (line, col) = bynk_syntax::span::line_col(&text, err.span.start);
515                    format!("{line}:{col}: {}", err.message)
516                })
517                .unwrap_or_else(|| "the source does not parse".to_string());
518            FormatResult::Err { ok: false, error }
519        }
520        Err(d) => FormatResult::Err {
521            ok: false,
522            error: d.message,
523        },
524    }
525}
526
527/// Format to a JSON string — `{"ok":true,"formatted":…}` or `{"ok":false,"error":…}`.
528pub fn format_to_json(source: &str) -> String {
529    serde_json::to_string(&format(source))
530        .unwrap_or_else(|_| "{\"ok\":false,\"error\":\"serialize failed\"}".to_string())
531}
532
533/// The diagnostics of a single in-memory source — non-bailing analysis, no emission
534/// (the editor's live, on-type diagnostics — slice 5d).
535#[derive(serde::Serialize)]
536pub struct AnalyzeResult {
537    pub diagnostics: Vec<Diagnostic>,
538}
539
540/// Analyse a source for diagnostics only (no compile/emit), for the given platform.
541pub fn analyze(source: &str, platform: Platform) -> AnalyzeResult {
542    catch_panic(|| analyze_inner(source, platform)).unwrap_or_else(|d| AnalyzeResult {
543        diagnostics: vec![d],
544    })
545}
546
547fn analyze_inner(source: &str, platform: Platform) -> AnalyzeResult {
548    let errs = analyse_in_memory(source, BuildTarget::Bundle, platform);
549    AnalyzeResult {
550        diagnostics: to_diagnostics(errs, &HashMap::new(), source),
551    }
552}
553
554/// Analyse to a JSON string — `{ diagnostics: [{ from, to, line, col, severity,
555/// category, message }] }`.
556pub fn analyze_to_json(source: &str, platform: Platform) -> String {
557    serde_json::to_string(&analyze(source, platform))
558        .unwrap_or_else(|_| "{\"diagnostics\":[]}".to_string())
559}
560
561/// The inferred type at a cursor position in a single in-memory source, or
562/// `None` if the expression at that position failed to type — per ADR
563/// 0094, a well-typed function still contributes types even when a *different*
564/// function in the same file has an error, so this isn't blanked by every
565/// mid-edit error, only by one at the position itself (or upstream of it, an
566/// unresolved name). The editor's hover tooltip (#397).
567#[derive(serde::Serialize)]
568pub struct HoverResult {
569    pub ty: Option<String>,
570}
571
572/// Hover for a byte `offset` into `source`, for the given platform.
573pub fn hover(source: &str, offset: usize, platform: Platform) -> HoverResult {
574    catch_panic(|| hover_inner(source, offset, platform)).unwrap_or(HoverResult { ty: None })
575}
576
577fn hover_inner(source: &str, offset: usize, platform: Platform) -> HoverResult {
578    let analysis = analyse_in_memory_with_types(source, BuildTarget::Bundle, platform);
579    let ty = type_at_offset(&analysis.expr_types, offset, &analysis.ty_intern)
580        .map(|t| t.display(&analysis.ty_intern));
581    HoverResult { ty }
582}
583
584/// Hover to a JSON string — `{ ty: string | null }`.
585pub fn hover_to_json(source: &str, offset: usize, platform: Platform) -> String {
586    serde_json::to_string(&hover(source, offset, platform))
587        .unwrap_or_else(|_| "{\"ty\":null}".to_string())
588}
589
590/// One completion candidate, serialised for the JS side — a shadow of
591/// `bynk_ide::completion::Completion`/`CompletionKind` (that crate stays
592/// serde-free; this is the wire DTO, same pattern as [`EmittedFile`]/[`Diagnostic`]).
593#[derive(serde::Serialize)]
594pub struct CompletionCandidate {
595    pub label: String,
596    /// "unit"/"capability"/"type"/"keyword"/"snippet"/"variant"/"member"/
597    /// "field"/"constructor"/"function"/"local".
598    pub kind: &'static str,
599    pub detail: Option<String>,
600    pub insert_text: Option<String>,
601}
602
603/// The editor's completion list at a cursor position (#808).
604#[derive(serde::Serialize)]
605pub struct CompleteResult {
606    pub items: Vec<CompletionCandidate>,
607}
608
609fn to_candidate(c: completion::Completion) -> CompletionCandidate {
610    use completion::CompletionKind::*;
611    let kind = match c.kind {
612        Unit => "unit",
613        Capability => "capability",
614        Type => "type",
615        Keyword => "keyword",
616        Snippet => "snippet",
617        Variant => "variant",
618        Member => "member",
619        Field => "field",
620        Constructor => "constructor",
621        Function => "function",
622        Constant => "constant",
623        Constraint => "constraint",
624    };
625    CompletionCandidate {
626        label: c.label,
627        kind,
628        detail: c.detail,
629        insert_text: c.insert_text,
630    }
631}
632
633/// Completion at a byte `offset` into an in-memory Bynk source, for the given
634/// platform (capability methods, types, keywords, in-scope locals, and
635/// value-receiver members — #808, the other half of #397 hover shipped).
636/// Single buffer, single call — no project files, no multi-doc overlay/caching
637/// (the wasm boundary has none of those, so `files: None` throughout).
638pub fn complete(source: &str, offset: usize, platform: Platform) -> CompleteResult {
639    catch_panic(|| complete_inner(source, offset, platform))
640        .unwrap_or(CompleteResult { items: Vec::new() })
641}
642
643fn complete_inner(source: &str, offset: usize, platform: Platform) -> CompleteResult {
644    complete_with(source, offset, None, |text| {
645        FileTypes::from(analyse_in_memory_with_types(
646            text,
647            BuildTarget::Bundle,
648            platform,
649        ))
650    })
651}
652
653/// One file's expression types and local bindings, from either the
654/// single-source or the project analysis.
655struct FileTypes {
656    expr_types: Vec<(Span, TyId)>,
657    ty_intern: Arc<Types>,
658    locals: Vec<LocalBinding>,
659}
660
661impl From<InMemoryAnalysis> for FileTypes {
662    fn from(a: InMemoryAnalysis) -> Self {
663        FileTypes {
664            expr_types: a.expr_types,
665            ty_intern: a.ty_intern,
666            locals: a.locals,
667        }
668    }
669}
670
671/// Completion over one buffer, with `analyse` typing that buffer (or a
672/// rewrite of it) in whatever context the caller has: alone, or inside its
673/// project (#2102 slice 2). `files` is the project's `.bynk` sources, for the
674/// candidates that look across units (`consumes U { … }`). An offset past the
675/// end or inside a character yields no candidates rather than a panic.
676fn complete_with(
677    source: &str,
678    offset: usize,
679    files: Option<&HashMap<PathBuf, String>>,
680    analyse: impl Fn(&str) -> FileTypes,
681) -> CompleteResult {
682    if !source.is_char_boundary(offset) {
683        return CompleteResult { items: Vec::new() };
684    }
685    let line_prefix = source[..offset].rsplit('\n').next().unwrap_or("");
686    let mut items: Vec<CompletionCandidate> = completion::complete(line_prefix, source, files)
687        .into_iter()
688        .map(to_candidate)
689        .collect();
690
691    // ADR 0093 D3: in-scope locals/params, alongside keywords/constructors at
692    // a keyword or expression position — the same two disjoint positions
693    // `bynk-lsp`'s handler merges locals into.
694    if completion::is_keyword_position(line_prefix)
695        || completion::is_expression_position(line_prefix)
696    {
697        let analysis = analyse(source);
698        items.extend(locals_at(&analysis.locals, offset).into_iter().map(|b| {
699            CompletionCandidate {
700                label: b.name.clone(),
701                kind: "local",
702                detail: Some(b.ty.clone()),
703                insert_text: None,
704            }
705        }));
706    }
707    // A lowercase `receiver.` is a value receiver: `complete()` yields nothing
708    // there directly (ADR 0093 D4), so retype the rewritten buffer (dropping
709    // the trailing partial member) and offer the receiver's kernel methods /
710    // record fields.
711    if items.is_empty()
712        && let Some((rewritten, recv_offset)) = completion::value_receiver_rewrite(source, offset)
713    {
714        let analysis = analyse(&rewritten);
715        if let Some(ty) = type_at_offset(&analysis.expr_types, recv_offset, &analysis.ty_intern) {
716            items = completion::value_member_candidates(ty, &analysis.ty_intern, source, files)
717                .into_iter()
718                .map(to_candidate)
719                .collect();
720        }
721    }
722    CompleteResult { items }
723}
724
725/// Complete to a JSON string — `{ items: [{ label, kind, detail, insert_text }] }`.
726pub fn complete_to_json(source: &str, offset: usize, platform: Platform) -> String {
727    serde_json::to_string(&complete(source, offset, platform))
728        .unwrap_or_else(|_| "{\"items\":[]}".to_string())
729}
730
731// #2102 slice 2: the same three editor queries over a whole in-memory project,
732// for the VS Code web extension, which loads the workspace through
733// `vscode.workspace.fs`. A project is a map of project-relative paths to text
734// (`bynk.toml` and every `.bynk` file; see
735// `bynk_driver::project::analyse_in_memory_project`), sent as the JSON object
736// `{ "<path>": "<text>", … }`.
737
738/// Parse a project's `{ path: text }` JSON. Malformed JSON is an empty project.
739pub fn project_files(files_json: &str) -> HashMap<PathBuf, String> {
740    serde_json::from_str::<HashMap<String, String>>(files_json)
741        .unwrap_or_default()
742        .into_iter()
743        .map(|(path, text)| (PathBuf::from(path), text))
744        .collect()
745}
746
747/// Every file's diagnostics, each carrying its project-relative `path`. A
748/// project-level diagnostic (a manifest problem, say) has `path: null`.
749/// A project analysis: every file's diagnostics, plus `warnings` about the
750/// project itself that aren't tied to a file (an ignored absolute `[paths]`
751/// entry), for the caller to show.
752#[derive(serde::Serialize)]
753pub struct ProjectAnalyzeResult {
754    pub diagnostics: Vec<Diagnostic>,
755    pub warnings: Vec<String>,
756}
757
758pub fn analyze_project(
759    files: &HashMap<PathBuf, String>,
760    platform: Platform,
761) -> ProjectAnalyzeResult {
762    catch_panic(|| {
763        let analysis = analyse_in_memory_project(files, BuildTarget::Bundle, platform);
764        // The analysis reports `/`-separated paths; look sources up the same way.
765        let sources: HashMap<PathBuf, String> = files
766            .iter()
767            .map(|(path, text)| (slash_key(path), text.clone()))
768            .collect();
769        ProjectAnalyzeResult {
770            diagnostics: to_diagnostics(analysis.errors, &sources, ""),
771            warnings: analysis
772                .ignored_paths
773                .into_iter()
774                .map(|(key, entry)| {
775                    format!(
776                        "bynk.toml: `[paths] {key}` entry `{entry}` is an absolute path, which \
777                         can't name a file in the project, so it is ignored (use a path \
778                         relative to the project root)"
779                    )
780                })
781                .collect(),
782        }
783    })
784    .unwrap_or_else(|d| ProjectAnalyzeResult {
785        diagnostics: vec![d],
786        warnings: Vec::new(),
787    })
788}
789
790/// The project's analysis, narrowed to one file's types and locals.
791fn project_file_types(
792    files: &HashMap<PathBuf, String>,
793    path: &std::path::Path,
794    platform: Platform,
795) -> FileTypes {
796    let mut analysis = analyse_in_memory_project(files, BuildTarget::Bundle, platform);
797    FileTypes {
798        expr_types: analysis.expr_types.remove(path).unwrap_or_default(),
799        ty_intern: analysis.ty_intern,
800        locals: analysis.locals.remove(path).unwrap_or_default(),
801    }
802}
803
804/// Hover at a byte `offset` into the project file at `path`, typed in the
805/// context of the whole project.
806pub fn hover_project(
807    files: &HashMap<PathBuf, String>,
808    path: &str,
809    offset: usize,
810    platform: Platform,
811) -> HoverResult {
812    catch_panic(|| {
813        let types = project_file_types(files, &slash_key(std::path::Path::new(path)), platform);
814        HoverResult {
815            ty: type_at_offset(&types.expr_types, offset, &types.ty_intern)
816                .map(|t| t.display(&types.ty_intern)),
817        }
818    })
819    .unwrap_or(HoverResult { ty: None })
820}
821
822/// Completion at a byte `offset` into the project file at `path`: the
823/// single-source candidates, plus the ones that need the rest of the project
824/// (names a `uses` brings in, another unit's capabilities).
825pub fn complete_project(
826    files: &HashMap<PathBuf, String>,
827    path: &str,
828    offset: usize,
829    platform: Platform,
830) -> CompleteResult {
831    catch_panic(|| {
832        // One spelling for every key, so the edited buffer below replaces its
833        // file rather than sitting beside a differently separated copy.
834        let files: &HashMap<PathBuf, String> = &files
835            .iter()
836            .map(|(p, text)| (slash_key(p), text.clone()))
837            .collect();
838        let path = slash_key(std::path::Path::new(path));
839        let Some(source) = files.get(&path) else {
840            return CompleteResult { items: Vec::new() };
841        };
842        let sources: HashMap<PathBuf, String> = files
843            .iter()
844            .filter(|(p, _)| p.extension().is_some_and(|e| e == "bynk"))
845            .map(|(p, t)| (p.clone(), t.clone()))
846            .collect();
847        complete_with(source, offset, Some(&sources), |text| {
848            let mut edited = files.clone();
849            edited.insert(path.clone(), text.to_string());
850            project_file_types(&edited, &path, platform)
851        })
852    })
853    .unwrap_or(CompleteResult { items: Vec::new() })
854}
855
856/// The platform an editor entry point analyses for, from the optional name the JS
857/// side passes (#2102). `None` keeps the playground's `browser` (its programs run
858/// in the page). The VS Code web extension passes `"cloudflare"`, the platform
859/// `bynk-lsp` analyses a project for (`Platform::default()`), so a unit that
860/// consumes `bynk.cloudflare` doesn't draw `bynk.target.vendor_required` in
861/// vscode.dev when it checks clean on the desktop. An unrecognised name falls
862/// back to `browser`, the same as `None`.
863pub fn platform_named(name: Option<&str>) -> Platform {
864    match name {
865        Some("cloudflare") => Platform::Cloudflare,
866        Some("node") => Platform::Node,
867        _ => Platform::Browser,
868    }
869}
870
871#[cfg(target_arch = "wasm32")]
872use wasm_bindgen::prelude::wasm_bindgen;
873
874/// Route panics to `console.error` with a readable message and location. Idempotent
875/// (`set_once` installs the hook exactly once), so every entry point may call it.
876/// Without this a panic on adversarial input surfaces as an opaque `RuntimeError:
877/// unreachable` with no clue to its origin (#717).
878#[cfg(target_arch = "wasm32")]
879fn install_panic_hook() {
880    console_error_panic_hook::set_once();
881}
882
883/// The wasm entry point for live editor diagnostics: analyse an in-memory Bynk
884/// source for the browser and return `{ diagnostics: [...] }` (with byte `from`/`to`
885/// spans for inline marking). Non-bailing — all diagnostics at once. `platform`
886/// is optional (see [`platform_named`]); the playground omits it.
887#[cfg(target_arch = "wasm32")]
888#[wasm_bindgen]
889pub fn bynk_analyze(source: &str, platform: Option<String>) -> String {
890    install_panic_hook();
891    analyze_to_json(source, platform_named(platform.as_deref()))
892}
893
894/// The wasm entry point for a diagnostic's "learn more": the compiler's summary,
895/// curated blurb/example (when one exists) and docs link for a diagnostic `code`
896/// (a `category` from any diagnostic), as `{ code, summary, blurb?, example?, href }`
897/// (#2679).
898#[cfg(target_arch = "wasm32")]
899#[wasm_bindgen]
900pub fn bynk_explain(code: &str) -> String {
901    install_panic_hook();
902    explain_to_json(code)
903}
904
905/// The wasm entry point for the standard-library reference: every built-in
906/// type's statics and methods, every first-party capability's operations and
907/// every first-party module's functions, with signatures, docs and
908/// `experimental`/`deprecated` marks, as `{ types, capabilities, modules }`
909/// (#2698). Takes no input; fixed per build.
910#[cfg(target_arch = "wasm32")]
911#[wasm_bindgen]
912pub fn bynk_reference() -> String {
913    install_panic_hook();
914    reference::reference_to_json()
915}
916
917/// The wasm entry point for the editor's hover tooltip: the inferred type at a
918/// byte `offset` into an in-memory Bynk source, as `{ "ty": string | null }`
919/// (#397). `platform` is optional (see [`platform_named`]).
920#[cfg(target_arch = "wasm32")]
921#[wasm_bindgen]
922pub fn bynk_hover(source: &str, offset: u32, platform: Option<String>) -> String {
923    install_panic_hook();
924    hover_to_json(source, offset as usize, platform_named(platform.as_deref()))
925}
926
927/// The wasm entry point for the editor's completion: context-aware candidates
928/// at a byte `offset` into an in-memory Bynk source, as
929/// `{ "items": [{ "label", "kind", "detail", "insert_text" }] }` (#808).
930/// `platform` is optional (see [`platform_named`]).
931#[cfg(target_arch = "wasm32")]
932#[wasm_bindgen]
933pub fn bynk_complete(source: &str, offset: u32, platform: Option<String>) -> String {
934    install_panic_hook();
935    complete_to_json(source, offset as usize, platform_named(platform.as_deref()))
936}
937
938/// The wasm entry point for project diagnostics (#2102 slice 2): analyse a
939/// whole in-memory project, given as `{ "<project-relative path>": "<text>" }`
940/// JSON, and return `{ diagnostics: [...] }`, each with its file's `path`.
941/// `platform` is optional (see [`platform_named`]).
942#[cfg(target_arch = "wasm32")]
943#[wasm_bindgen]
944pub fn bynk_analyze_project(files_json: &str, platform: Option<String>) -> String {
945    install_panic_hook();
946    let result = analyze_project(
947        &project_files(files_json),
948        platform_named(platform.as_deref()),
949    );
950    serde_json::to_string(&result).unwrap_or_else(|_| "{\"diagnostics\":[]}".to_string())
951}
952
953/// The wasm entry point for project hover (#2102 slice 2): the type at a byte
954/// `offset` into the project file at `path`, as `{ "ty": string | null }`.
955#[cfg(target_arch = "wasm32")]
956#[wasm_bindgen]
957pub fn bynk_hover_project(
958    files_json: &str,
959    path: &str,
960    offset: u32,
961    platform: Option<String>,
962) -> String {
963    install_panic_hook();
964    let result = hover_project(
965        &project_files(files_json),
966        path,
967        offset as usize,
968        platform_named(platform.as_deref()),
969    );
970    serde_json::to_string(&result).unwrap_or_else(|_| "{\"ty\":null}".to_string())
971}
972
973/// The wasm entry point for project completion (#2102 slice 2): candidates at a
974/// byte `offset` into the project file at `path`, as `{ "items": [...] }`.
975#[cfg(target_arch = "wasm32")]
976#[wasm_bindgen]
977pub fn bynk_complete_project(
978    files_json: &str,
979    path: &str,
980    offset: u32,
981    platform: Option<String>,
982) -> String {
983    install_panic_hook();
984    let result = complete_project(
985        &project_files(files_json),
986        path,
987        offset as usize,
988        platform_named(platform.as_deref()),
989    );
990    serde_json::to_string(&result).unwrap_or_else(|_| "{\"items\":[]}".to_string())
991}
992
993/// The wasm entry point for the playground's Format button (#2431): format an
994/// in-memory Bynk source to the house style (default options), returning
995/// `{ "ok": true, "formatted": string }` or `{ "ok": false, "error": string }`.
996#[cfg(target_arch = "wasm32")]
997#[wasm_bindgen]
998pub fn bynk_format(source: &str) -> String {
999    install_panic_hook();
1000    format_to_json(source)
1001}
1002
1003/// The wasm entry point: compile an in-memory Bynk source for the browser
1004/// playground, returning a JSON document
1005/// `{ ok, files: [{ path, contents, kind, map? }], diagnostics: [{ path, line, col, severity,
1006/// category, message }] }`.
1007#[cfg(target_arch = "wasm32")]
1008#[wasm_bindgen]
1009pub fn bynk_compile(source: &str) -> String {
1010    install_panic_hook();
1011    compile_to_json(source, Platform::Browser)
1012}
1013
1014#[cfg(test)]
1015mod tests {
1016    use super::*;
1017    use std::path::Path;
1018
1019    const PROG: &str = "context app.demo\n\
1020        \n\
1021        consumes bynk { Clock, Logger }\n\
1022        \n\
1023        service demo {\n\
1024        \x20 on call() -> Effect[Instant] by Caller given Clock, Logger {\n\
1025        \x20   let _ <- Logger.info(\"hi\")\n\
1026        \x20   let now <- Clock.now()\n\
1027        \x20   now\n\
1028        \x20 }\n\
1029        }\n";
1030
1031    /// #2838: a hint rides the compile result with `severity: "hint"`, and
1032    /// does not stop the compile.
1033    #[test]
1034    fn a_staircase_hint_is_reported_with_the_hint_severity() {
1035        let src = "context app.demo\n\
1036            \n\
1037            fn f(a: Option[Int], b: Option[Int]) -> Int {\n\
1038            \x20 match a {\n\
1039            \x20   None => 0,\n\
1040            \x20   Some(x) => match b {\n\
1041            \x20     None => 1,\n\
1042            \x20     Some(y) => x + y,\n\
1043            \x20   },\n\
1044            \x20 }\n\
1045            }\n";
1046        let r = compile(src, Platform::Browser);
1047        assert!(r.ok, "compile failed");
1048        let hints: Vec<_> = r
1049            .diagnostics
1050            .iter()
1051            .filter(|d| d.category == "bynk.parse.let_else_staircase")
1052            .collect();
1053        assert_eq!(hints.len(), 1);
1054        assert_eq!(hints[0].severity, "hint");
1055    }
1056
1057    /// ADR 0615 (#2442): the graph carries the runtime modules the program
1058    /// reaches and no more, every runtime file is `support`, and every relative
1059    /// import in the graph resolves to a file in it — the sandbox links the set
1060    /// as given.
1061    #[test]
1062    fn the_graph_links_and_carries_only_the_reached_runtime() {
1063        let r = compile(PROG, Platform::Browser);
1064        assert!(r.ok);
1065        let paths: std::collections::HashSet<String> =
1066            r.files.iter().map(|f| f.path.clone()).collect();
1067        let runtime: Vec<&str> = paths
1068            .iter()
1069            .filter(|p| p.starts_with("__bynk_runtime/"))
1070            .map(String::as_str)
1071            .collect();
1072        assert!(!runtime.is_empty(), "runtime modules present: {paths:?}");
1073        assert!(
1074            !paths.contains("runtime.js"),
1075            "no flat runtime.js: {paths:?}"
1076        );
1077        assert!(
1078            r.files
1079                .iter()
1080                .filter(|f| f.path.starts_with("__bynk_runtime/"))
1081                .all(|f| f.kind == FileKind::Support),
1082            "runtime files are `support`"
1083        );
1084        // The program reaches only a small slice of the runtime.
1085        assert!(
1086            runtime.len() < 8,
1087            "a 14-line program must not pull in the whole runtime: {runtime:?}"
1088        );
1089        for f in &r.files {
1090            let dir = Path::new(&f.path).parent().unwrap_or(Path::new(""));
1091            for line in f.contents.lines().filter(|l| l.starts_with("import ")) {
1092                let Some(spec) = line.rsplit('"').nth(1).filter(|s| s.starts_with('.')) else {
1093                    continue;
1094                };
1095                let mut resolved = PathBuf::new();
1096                for c in dir.join(spec).components() {
1097                    match c {
1098                        std::path::Component::ParentDir => {
1099                            resolved.pop();
1100                        }
1101                        std::path::Component::CurDir => {}
1102                        c => resolved.push(c),
1103                    }
1104                }
1105                assert!(
1106                    paths.contains(resolved.to_string_lossy().replace('\\', "/").as_str()),
1107                    "{} imports {spec}, which is not in the graph: {paths:?}",
1108                    f.path
1109                );
1110            }
1111        }
1112    }
1113
1114    #[test]
1115    fn format_returns_formatted_source_or_parse_error() {
1116        let ok: serde_json::Value = serde_json::from_str(&format_to_json(PROG)).unwrap();
1117        assert_eq!(ok["ok"], true);
1118        assert!(ok["formatted"].as_str().unwrap().contains("service demo"));
1119        let bad: serde_json::Value =
1120            serde_json::from_str(&format_to_json("context app.demo\nservice {")).unwrap();
1121        assert_eq!(bad["ok"], false);
1122        assert!(!bad["error"].as_str().unwrap().is_empty());
1123    }
1124
1125    #[test]
1126    fn compiles_browser_program_to_js_graph() {
1127        let r = compile(PROG, Platform::Browser);
1128        assert!(
1129            r.ok,
1130            "should compile: {:?}",
1131            r.diagnostics.first().map(|d| &d.message)
1132        );
1133        // The full runnable graph: user module + runtime + browser binding + compose.
1134        let paths: Vec<&str> = r.files.iter().map(|f| f.path.as_str()).collect();
1135        assert!(
1136            paths.iter().all(|p| p.ends_with(".js")),
1137            "all JS: {paths:?}"
1138        );
1139        assert!(
1140            paths.contains(&"__bynk_runtime/result.js"),
1141            "runtime present: {paths:?}"
1142        );
1143        assert!(
1144            paths.contains(&"bynk-browser.js"),
1145            "browser binding present: {paths:?}"
1146        );
1147        // #2425: each file is tagged by origin.
1148        let kind = |p: &str| r.files.iter().find(|f| f.path == p).map(|f| f.kind);
1149        assert_eq!(kind("app/demo.js"), Some(FileKind::User));
1150        assert_eq!(kind("compose.js"), Some(FileKind::Wiring));
1151        assert_eq!(kind("__bynk_runtime/result.js"), Some(FileKind::Support));
1152        assert_eq!(kind("bynk-browser.js"), Some(FileKind::Support));
1153        assert_eq!(
1154            r.files.iter().filter(|f| f.kind == FileKind::User).count(),
1155            1,
1156            "only the user's module is `user`"
1157        );
1158        // Injected first-party units are never mistaken for the user's code.
1159        assert!(
1160            r.files
1161                .iter()
1162                .filter(|f| f.path == "bynk.js" || f.path.starts_with("bynk/"))
1163                .all(|f| f.kind == FileKind::Support),
1164            "first-party units are `support`"
1165        );
1166        // No residual TypeScript type syntax survived the strip.
1167        let user = r
1168            .files
1169            .iter()
1170            .find(|f| f.path == "app/demo.js")
1171            .expect("user module");
1172        assert!(
1173            !user.contents.contains(": Promise<"),
1174            "annotations stripped:\n{}",
1175            user.contents
1176        );
1177    }
1178
1179    #[test]
1180    fn surfaces_diagnostics_for_a_bad_program() {
1181        let r = compile("context app.demo\n\nthis is not bynk\n", Platform::Browser);
1182        assert!(!r.ok);
1183        assert!(r.files.is_empty());
1184        assert!(!r.diagnostics.is_empty());
1185        assert!(r.diagnostics.iter().all(|d| d.severity == "error"));
1186        // Line/col point into the user source.
1187        assert!(r.diagnostics.iter().any(|d| d.line >= 1));
1188    }
1189
1190    /// #2679: every diagnostic carries the registry summary and a docs link.
1191    #[test]
1192    fn diagnostics_carry_a_summary_and_href() {
1193        let r = analyze("context app.demo\n\nthis is not bynk\n", Platform::Browser);
1194        assert!(!r.diagnostics.is_empty());
1195        for d in &r.diagnostics {
1196            assert!(d.summary.is_some(), "no summary for {}", d.category);
1197            assert_eq!(d.href, format!("https://bynk-lang.org/d/{}", d.category));
1198        }
1199        // Also present on the serialised wire shape (additive fields).
1200        let json: serde_json::Value = serde_json::from_str(&analyze_to_json(
1201            "context app.demo\n\nthis is not bynk\n",
1202            Platform::Browser,
1203        ))
1204        .unwrap();
1205        let d = &json["diagnostics"][0];
1206        assert!(d["category"].is_string() && d["message"].is_string());
1207        assert!(d["summary"].is_string() && d["href"].is_string());
1208    }
1209
1210    /// #2679: the host-synthetic codes are registered too, so they resolve.
1211    #[test]
1212    fn a_synthetic_code_resolves_from_the_registry() {
1213        let d = panic_diagnostic(Box::new("boom"));
1214        assert!(d.summary.is_some());
1215        assert_eq!(d.href, "https://bynk-lang.org/d/bynk.wasm.panic");
1216    }
1217
1218    /// #3876: every registered code links to its own page, curated or not.
1219    #[test]
1220    fn href_is_the_code_page_for_every_registered_code() {
1221        let curated = bynk_syntax::diagnostics::EXPLANATIONS
1222            .first()
1223            .expect("at least one curated code");
1224        assert_eq!(explain(curated.code).href, curated.href());
1225        let plain = bynk_syntax::diagnostics::REGISTRY
1226            .iter()
1227            .find(|d| bynk_syntax::diagnostics::explain(d.code).is_none())
1228            .expect("an uncurated code");
1229        assert_eq!(
1230            explain(plain.code).href,
1231            format!("https://bynk-lang.org/d/{}", plain.code)
1232        );
1233    }
1234
1235    #[test]
1236    fn explain_returns_summary_blurb_example_and_href() {
1237        let e = bynk_syntax::diagnostics::EXPLANATIONS.first().unwrap();
1238        let v: serde_json::Value = serde_json::from_str(&explain_to_json(e.code)).unwrap();
1239        assert_eq!(v["code"], e.code);
1240        assert!(v["summary"].is_string());
1241        assert_eq!(v["blurb"], e.blurb);
1242        assert_eq!(v["example"], e.example);
1243        assert_eq!(v["href"], e.href());
1244    }
1245
1246    #[test]
1247    fn explain_omits_blurb_for_an_uncurated_code_and_survives_an_unknown_one() {
1248        let plain = bynk_syntax::diagnostics::REGISTRY
1249            .iter()
1250            .find(|d| bynk_syntax::diagnostics::explain(d.code).is_none())
1251            .unwrap();
1252        let v: serde_json::Value = serde_json::from_str(&explain_to_json(plain.code)).unwrap();
1253        assert_eq!(v["summary"], plain.summary);
1254        assert!(v.get("blurb").is_none() && v.get("example").is_none());
1255        let u: serde_json::Value = serde_json::from_str(&explain_to_json("nope")).unwrap();
1256        assert_eq!(u["code"], "nope");
1257        assert!(u["summary"].is_null());
1258        assert_eq!(u["href"], "https://bynk-lang.org/d/");
1259    }
1260
1261    #[test]
1262    fn cloudflare_shapes_are_rejected_in_the_browser() {
1263        // The slice-2 platform lock fires through the in-memory path too.
1264        let prog = "context cache.store\n\
1265            \n\
1266            consumes bynk.cloudflare { Kv }\n\
1267            \n\
1268            service cache {\n\
1269            \x20 on call(k: String) -> Effect[Option[String]] by Caller given Kv {\n\
1270            \x20   let v <- Kv.get(k)\n\
1271            \x20   v\n\
1272            \x20 }\n\
1273            }\n";
1274        let r = compile(prog, Platform::Browser);
1275        assert!(
1276            !r.ok,
1277            "a cloudflare-only program must not compile for the browser"
1278        );
1279        assert!(
1280            r.diagnostics
1281                .iter()
1282                .any(|d| d.category == "bynk.target.vendor_required"),
1283            "expected the platform lock: {:?}",
1284            r.diagnostics
1285                .iter()
1286                .map(|d| &d.category)
1287                .collect::<Vec<_>>()
1288        );
1289    }
1290
1291    /// #2102: the VS Code web extension analyses for `cloudflare`, as `bynk-lsp`
1292    /// does, so a unit consuming `bynk.cloudflare` checks clean there; the
1293    /// playground's default (`browser`) still reports the vendor lock.
1294    #[test]
1295    fn platform_named_selects_the_analysis_platform() {
1296        assert_eq!(platform_named(None), Platform::Browser);
1297        assert_eq!(platform_named(Some("cloudflare")), Platform::Cloudflare);
1298        assert_eq!(platform_named(Some("node")), Platform::Node);
1299        assert_eq!(platform_named(Some("browser")), Platform::Browser);
1300        assert_eq!(platform_named(Some("mainframe")), Platform::Browser);
1301
1302        let prog = "context kv.index\n\n\
1303            consumes bynk.cloudflare { Kv }\n\n\
1304            service scan {\n\
1305            \x20 on call(prefix: String) -> Effect[Result[List[String], ()]] by Caller given Kv {\n\
1306            \x20   let keys <- Kv.list(Some(prefix))\n\
1307            \x20   Ok(keys)\n\
1308            \x20 }\n\
1309            }\n";
1310        let categories = |p: Platform| -> Vec<String> {
1311            analyze(prog, p)
1312                .diagnostics
1313                .into_iter()
1314                .map(|d| d.category)
1315                .collect()
1316        };
1317        assert_eq!(
1318            categories(platform_named(Some("cloudflare"))),
1319            Vec::<String>::new()
1320        );
1321        assert!(
1322            categories(platform_named(None)).contains(&"bynk.target.vendor_required".to_string()),
1323            "the browser default keeps the vendor lock: {:?}",
1324            categories(platform_named(None))
1325        );
1326    }
1327
1328    #[test]
1329    fn compile_to_json_is_valid_json() {
1330        let json = compile_to_json(PROG, Platform::Browser);
1331        let v: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
1332        assert_eq!(v["ok"], true);
1333        assert!(v["files"].as_array().is_some_and(|a| !a.is_empty()));
1334    }
1335
1336    #[test]
1337    fn analyze_reports_check_errors_for_a_context() {
1338        // A type mismatch in a *context* — returning a String where Int is declared.
1339        // The non-bailing analyse must report it (slice 5d's reason to exist: plain
1340        // single-source `diagnose` only checks commons, not contexts).
1341        let prog = "context app.demo\n\n\
1342            consumes bynk { Logger }\n\n\
1343            service demo {\n\
1344            \x20 on call() -> Effect[Int] by Caller given Logger {\n\
1345            \x20   let _ <- Logger.info(\"x\")\n\
1346            \x20   \"not an int\"\n\
1347            \x20 }\n\
1348            }\n";
1349        let r = analyze(prog, Platform::Browser);
1350        assert!(
1351            r.diagnostics.iter().any(|d| d.severity == "error"),
1352            "a type mismatch should be reported: {:?}",
1353            r.diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
1354        );
1355        // A real diagnostic carries a span for inline marking.
1356        assert!(r.diagnostics.iter().any(|d| d.to > d.from));
1357    }
1358
1359    #[test]
1360    fn hover_reports_the_inferred_type_of_an_expression() {
1361        // The tail expression `now` (the *reference*, not the `let now <-`
1362        // binding) — the last occurrence of the substring in `PROG`.
1363        let offset = PROG.rfind("now").expect("PROG mentions `now`");
1364        let r = hover(PROG, offset, Platform::Browser);
1365        assert_eq!(r.ty.as_deref(), Some("Instant"));
1366    }
1367
1368    #[test]
1369    fn hover_outside_any_expression_is_none() {
1370        // Offset 0 sits in the `context` keyword — a declaration, not an
1371        // expression, so nothing is recorded there.
1372        let r = hover(PROG, 0, Platform::Browser);
1373        assert_eq!(r.ty, None);
1374    }
1375
1376    #[test]
1377    fn hover_to_json_is_valid_json() {
1378        let offset = PROG.rfind("now").expect("PROG mentions `now`");
1379        let json = hover_to_json(PROG, offset, Platform::Browser);
1380        let v: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
1381        assert_eq!(v["ty"], "Instant");
1382    }
1383
1384    #[test]
1385    fn hover_survives_a_sibling_error() {
1386        // ADR 0094: hovering a well-typed expression must not go blank just
1387        // because a *different* function in the same buffer is mid-edit and
1388        // broken — the whole point of exposing the checker's partial
1389        // `expr_types` map rather than its old all-or-nothing gate.
1390        let prog = "commons app.demo\n\n\
1391            fn good() -> Int {\n  42\n}\n\n\
1392            fn bad() -> Int {\n  \"oops\"\n}\n";
1393        let offset = prog.find("42").expect("prog mentions 42");
1394        let r = hover(prog, offset, Platform::Browser);
1395        assert_eq!(r.ty.as_deref(), Some("Int"));
1396    }
1397
1398    #[test]
1399    fn hover_on_an_expression_that_failed_to_type_is_none() {
1400        // The checker records `Ty::Error` for `"oops" + 1`; hover shows no
1401        // type rather than the `<type error>` placeholder.
1402        let prog = "commons app.demo\n\nfn bad() -> Int {\n  \"oops\" + 1\n}\n";
1403        let offset = prog.find("+ 1").expect("prog mentions + 1");
1404        let r = hover(prog, offset, Platform::Browser);
1405        assert_eq!(r.ty, None);
1406    }
1407
1408    #[test]
1409    fn complete_offers_in_scope_capability_after_given() {
1410        let prog = "context app.demo\n\n\
1411            consumes bynk { Clock, Logger }\n\n\
1412            service demo {\n\
1413            \x20 on call() -> Effect[Instant] by Caller given \n\
1414            \x20   Clock.now()\n\
1415            \x20 }\n\
1416            }\n";
1417        let offset = prog.find("given \n").expect("prog mentions given") + "given ".len();
1418        let r = complete(prog, offset, Platform::Browser);
1419        assert!(
1420            r.items
1421                .iter()
1422                .any(|c| c.label == "Logger" && c.kind == "capability"),
1423            "{:?}",
1424            r.items.iter().map(|c| &c.label).collect::<Vec<_>>()
1425        );
1426    }
1427
1428    #[test]
1429    fn complete_offers_in_scope_locals_at_expression_position() {
1430        // ADR 0093 D3/D4: `bynk_complete` folds the two contexts that live
1431        // handler-side in `bynk-lsp` (locals, value-receiver members) into
1432        // the one wasm call — no analysis overlay/caching, single buffer.
1433        let offset = PROG.rfind("now").expect("PROG mentions `now`");
1434        let r = complete(PROG, offset, Platform::Browser);
1435        assert!(
1436            r.items.iter().any(|c| c.label == "now"
1437                && c.kind == "local"
1438                && c.detail.as_deref() == Some("Instant")),
1439            "{:?}",
1440            r.items
1441                .iter()
1442                .map(|c| (&c.label, c.kind))
1443                .collect::<Vec<_>>()
1444        );
1445    }
1446
1447    #[test]
1448    fn complete_offers_value_receiver_members_after_dot() {
1449        let prog = "commons app.demo\n\n\
1450            fn f() -> String {\n\
1451            \x20 let value = \"hi\"\n\
1452            \x20 value.\n\
1453            }\n";
1454        let offset = prog.find("value.\n").expect("prog mentions value.") + "value.".len();
1455        let r = complete(prog, offset, Platform::Browser);
1456        assert!(
1457            r.items
1458                .iter()
1459                .any(|c| c.label == "split" && c.kind == "member"),
1460            "{:?}",
1461            r.items.iter().map(|c| &c.label).collect::<Vec<_>>()
1462        );
1463    }
1464
1465    #[test]
1466    fn complete_survives_a_sibling_error() {
1467        // Same ADR 0094 ceiling as hover: a broken sibling function must not
1468        // blank out completion in a well-typed one.
1469        let prog = "commons app.demo\n\n\
1470            fn good() -> Int {\n  let count = 42\n  count\n}\n\n\
1471            fn bad() -> Int {\n  \"oops\"\n}\n";
1472        let offset = prog.rfind("count").expect("prog mentions count");
1473        let r = complete(prog, offset, Platform::Browser);
1474        assert!(
1475            r.items
1476                .iter()
1477                .any(|c| c.label == "count" && c.kind == "local"),
1478            "{:?}",
1479            r.items
1480                .iter()
1481                .map(|c| (&c.label, c.kind))
1482                .collect::<Vec<_>>()
1483        );
1484    }
1485
1486    #[test]
1487    fn complete_to_json_is_valid_json() {
1488        let offset = PROG.rfind("now").expect("PROG mentions `now`");
1489        let json = complete_to_json(PROG, offset, Platform::Browser);
1490        let v: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
1491        assert!(v["items"].as_array().is_some_and(|a| !a.is_empty()));
1492    }
1493
1494    #[test]
1495    fn complete_survives_a_panic() {
1496        // An out-of-bounds offset panics inside `complete_inner`'s slicing
1497        // (`source[..offset]`); `complete`'s own `catch_panic` wrapper must
1498        // still degrade to empty items rather than propagate, same guarantee
1499        // `catch_panic_converts_panic_to_a_diagnostic` proves for the wrapper
1500        // in general.
1501        let prev = std::panic::take_hook();
1502        std::panic::set_hook(Box::new(|_| {}));
1503        let r = complete("", usize::MAX, Platform::Browser);
1504        std::panic::set_hook(prev);
1505        assert!(r.items.is_empty());
1506    }
1507
1508    #[test]
1509    fn catch_panic_converts_panic_to_a_diagnostic() {
1510        // Silence the default hook's stderr backtrace for this deliberate panic,
1511        // then restore it so no other test is affected.
1512        let prev = std::panic::take_hook();
1513        std::panic::set_hook(Box::new(|_| {}));
1514        let caught = catch_panic(|| -> i32 { panic!("boom {}", 42) });
1515        std::panic::set_hook(prev);
1516
1517        let d = caught.expect_err("a panic must become an Err(diagnostic)");
1518        assert_eq!(d.severity, "error");
1519        assert_eq!(d.category, "bynk.wasm.panic");
1520        assert!(
1521            d.message.contains("boom 42"),
1522            "the panic message is carried through: {}",
1523            d.message
1524        );
1525    }
1526
1527    #[test]
1528    fn catch_panic_passes_a_value_through() {
1529        assert_eq!(catch_panic(|| 7).ok(), Some(7));
1530    }
1531
1532    #[test]
1533    fn analyze_clean_program_has_no_errors() {
1534        let r = analyze(PROG, Platform::Browser);
1535        assert!(
1536            r.diagnostics.iter().all(|d| d.severity != "error"),
1537            "clean program should have no errors: {:?}",
1538            r.diagnostics.iter().map(|d| &d.message).collect::<Vec<_>>()
1539        );
1540    }
1541
1542    // #2102 slice 2: project analysis for the VS Code web extension.
1543
1544    const TEXT: &str = "commons app.text\n\n\
1545        fn greeting(subject: String) -> String {\n\
1546        \x20 \"Hello, \\(subject)!\"\n\
1547        }\n";
1548
1549    const WEB: &str = "context app.web\n\n\
1550        uses app.text\n\n\
1551        consumes bynk { Logger }\n\n\
1552        service api {\n\
1553        \x20 on call() -> Effect[String] by Caller given Logger {\n\
1554        \x20   let _ <- Logger.info(\"hi\")\n\
1555        \x20   let message = greeting(\"World\")\n\
1556        \x20   message\n\
1557        \x20 }\n\
1558        }\n";
1559
1560    fn project(web: &str) -> HashMap<PathBuf, String> {
1561        HashMap::from([
1562            (
1563                PathBuf::from("bynk.toml"),
1564                "[project]\nname = \"p\"\nversion = \"0.1.0\"\n".to_string(),
1565            ),
1566            (PathBuf::from("src/app/text.bynk"), TEXT.to_string()),
1567            (PathBuf::from("src/app/web.bynk"), web.to_string()),
1568        ])
1569    }
1570
1571    fn categories(r: &ProjectAnalyzeResult) -> Vec<(Option<String>, String)> {
1572        r.diagnostics
1573            .iter()
1574            .map(|d| (d.path.clone(), d.category.clone()))
1575            .collect()
1576    }
1577
1578    #[test]
1579    fn a_project_resolves_uses_across_files() {
1580        // Alone, the context can't see `app.text`.
1581        let alone = analyze(WEB, Platform::Cloudflare);
1582        assert!(
1583            alone
1584                .diagnostics
1585                .iter()
1586                .any(|d| d.category == "bynk.uses.unknown_commons")
1587        );
1588        // With its project, it checks clean.
1589        let r = analyze_project(&project(WEB), Platform::Cloudflare);
1590        assert!(r.diagnostics.is_empty(), "{:?}", categories(&r));
1591    }
1592
1593    #[test]
1594    fn a_project_reports_a_cross_file_misuse_against_its_file() {
1595        let r = analyze_project(
1596            &project(&WEB.replace("greeting(\"World\")", "greeting(1)")),
1597            Platform::Cloudflare,
1598        );
1599        let cats = categories(&r);
1600        assert!(!cats.is_empty(), "the misuse is reported");
1601        assert!(
1602            cats.iter()
1603                .all(|(path, _)| path.as_deref() == Some("src/app/web.bynk")),
1604            "attributed to the using file: {cats:?}"
1605        );
1606    }
1607
1608    #[test]
1609    fn a_project_honours_paths_include() {
1610        // With `include = ["lib"]`, files under `src/` aren't part of it.
1611        let mut files = project(WEB);
1612        files.insert(
1613            PathBuf::from("bynk.toml"),
1614            "[project]\nname = \"p\"\nversion = \"0.1.0\"\n\n[paths]\ninclude = [\"lib\"]\n"
1615                .to_string(),
1616        );
1617        let text = files.remove(Path::new("src/app/text.bynk")).unwrap();
1618        files.insert(PathBuf::from("lib/app/text.bynk"), text);
1619        let web = files.remove(Path::new("src/app/web.bynk")).unwrap();
1620        files.insert(PathBuf::from("lib/app/web.bynk"), web);
1621        files.insert(PathBuf::from("src/app/stray.bynk"), "not bynk".to_string());
1622        let r = analyze_project(&files, Platform::Cloudflare);
1623        assert!(r.diagnostics.is_empty(), "{:?}", categories(&r));
1624    }
1625
1626    fn manifest(paths: &str) -> String {
1627        format!("[project]\nname = \"p\"\nversion = \"0.1.0\"\n\n[paths]\n{paths}\n")
1628    }
1629
1630    #[test]
1631    fn a_project_honours_a_dot_slash_include() {
1632        // `./src` names the same tree as `src`. Were it left as written, no key
1633        // would start with it and every file would silently drop out, so the
1634        // cross-file misuse below would go unreported.
1635        let mut files = project(&WEB.replace("greeting(\"World\")", "greeting(1)"));
1636        files.insert(
1637            PathBuf::from("bynk.toml"),
1638            manifest("include = [\"./src\"]"),
1639        );
1640        let r = analyze_project(&files, Platform::Cloudflare);
1641        let cats = categories(&r);
1642        assert!(!cats.is_empty(), "the files under ./src are analysed");
1643        assert!(
1644            cats.iter()
1645                .all(|(path, _)| path.as_deref() == Some("src/app/web.bynk")),
1646            "{cats:?}"
1647        );
1648    }
1649
1650    #[test]
1651    fn a_project_warns_about_absolute_paths_entries() {
1652        // An absolute include can't name a file in the project: it is ignored
1653        // and reported, and with no include left the conventional `src`
1654        // layout applies, so the project still checks.
1655        let mut files = project(WEB);
1656        files.insert(
1657            PathBuf::from("bynk.toml"),
1658            manifest("include = [\"/home/me/proj/src\"]\nexclude = [\"C:/gen\", \"gen\"]"),
1659        );
1660        let r = analyze_project(&files, Platform::Cloudflare);
1661        assert!(r.diagnostics.is_empty(), "{:?}", categories(&r));
1662        assert_eq!(r.warnings.len(), 2, "{:?}", r.warnings);
1663        assert!(r.warnings[0].contains("`[paths] include` entry `/home/me/proj/src`"));
1664        assert!(r.warnings[1].contains("`[paths] exclude` entry `C:/gen`"));
1665        // Relative entries draw no warning.
1666        let r = analyze_project(&project(WEB), Platform::Cloudflare);
1667        assert!(r.warnings.is_empty());
1668    }
1669
1670    #[test]
1671    fn a_project_honours_a_dot_slash_exclude_and_a_root_include() {
1672        // A flat layout (`include = ["./"]`, the root) with `exclude = ["./gen"]`:
1673        // the broken file under gen/ is left out, the rest checks clean.
1674        let mut files: HashMap<PathBuf, String> = project(WEB)
1675            .into_iter()
1676            .map(|(p, t)| (PathBuf::from(p.to_string_lossy().replace("src/", "")), t))
1677            .collect();
1678        files.insert(
1679            PathBuf::from("bynk.toml"),
1680            manifest("include = [\"./\"]\nexclude = [\"./gen\"]"),
1681        );
1682        files.insert(PathBuf::from("gen/junk.bynk"), "not bynk".to_string());
1683        let r = analyze_project(&files, Platform::Cloudflare);
1684        assert!(r.diagnostics.is_empty(), "{:?}", categories(&r));
1685        // Without the exclude, gen/junk.bynk is analysed and fails to parse.
1686        files.insert(PathBuf::from("bynk.toml"), manifest("include = [\".\"]"));
1687        let r = analyze_project(&files, Platform::Cloudflare);
1688        assert!(
1689            categories(&r)
1690                .iter()
1691                .any(|(path, _)| path.as_deref() == Some("gen/junk.bynk")),
1692            "{:?}",
1693            categories(&r)
1694        );
1695    }
1696
1697    #[test]
1698    fn a_project_hovers_a_name_from_another_file() {
1699        let files = project(WEB);
1700        let offset = WEB.rfind("message").expect("WEB mentions `message`");
1701        let r = hover_project(&files, "src/app/web.bynk", offset, Platform::Cloudflare);
1702        assert_eq!(r.ty.as_deref(), Some("String"));
1703        // An unknown path hovers nothing.
1704        let r = hover_project(&files, "src/app/nope.bynk", offset, Platform::Cloudflare);
1705        assert_eq!(r.ty, None);
1706    }
1707
1708    #[test]
1709    fn a_project_completes_locals_typed_across_files() {
1710        let src = WEB.replace("    message\n", "    m\n");
1711        let files = project(&src);
1712        let offset = src.rfind("    m\n").expect("the partial local") + "    m".len();
1713        let r = complete_project(&files, "src/app/web.bynk", offset, Platform::Cloudflare);
1714        let message = r
1715            .items
1716            .iter()
1717            .find(|c| c.label == "message")
1718            .unwrap_or_else(|| panic!("`message` is offered: {:?}", labels(&r)));
1719        assert_eq!(message.detail.as_deref(), Some("String"));
1720        // An offset inside a multi-byte character offers nothing, not a panic.
1721        let files = project(&WEB.replace("hi", "hé"));
1722        let inside = WEB.find("hi").unwrap() + 2;
1723        let r = complete_project(&files, "src/app/web.bynk", inside, Platform::Cloudflare);
1724        assert!(r.items.is_empty());
1725    }
1726
1727    fn labels(r: &CompleteResult) -> Vec<&str> {
1728        r.items.iter().map(|c| c.label.as_str()).collect()
1729    }
1730
1731    /// Windows CI caught `src\app/web.bynk`: the project model joins identity
1732    /// paths with the platform separator. Every path a project analysis hands
1733    /// back, and every key it takes, is `/`-separated on every platform.
1734    #[test]
1735    fn project_paths_are_slash_separated_on_every_platform() {
1736        let misuse = WEB.replace("greeting(\"World\")", "greeting(1)");
1737        // Keys spelled with the platform's own joins (`\` on Windows).
1738        let native: HashMap<PathBuf, String> = project(&misuse)
1739            .into_iter()
1740            .map(|(p, text)| {
1741                let joined = p.iter().fold(PathBuf::new(), |acc, part| acc.join(part));
1742                (joined, text)
1743            })
1744            .collect();
1745        for files in [project(&misuse), native] {
1746            let r = analyze_project(&files, Platform::Cloudflare);
1747            assert!(!r.diagnostics.is_empty(), "the misuse is reported");
1748            for d in &r.diagnostics {
1749                let path = d.path.as_deref().unwrap_or_default();
1750                assert!(!path.contains('\\'), "a `/` path, not {path:?}");
1751                assert_eq!(path, "src/app/web.bynk");
1752                // Resolved against the file's own text, so a real line.
1753                assert!(d.line > 1, "line/col from web.bynk: {}", d.line);
1754            }
1755            // The `"hi"` literal still types next to the misuse.
1756            let offset = misuse.find("\"hi\"").unwrap() + 1;
1757            let r = hover_project(&files, "src/app/web.bynk", offset, Platform::Cloudflare);
1758            assert_eq!(
1759                r.ty.as_deref(),
1760                Some("String"),
1761                "hover finds the file under its `/` key"
1762            );
1763        }
1764    }
1765
1766    #[test]
1767    fn slash_key_joins_components_with_slashes() {
1768        let joined = Path::new("src").join("app").join("web.bynk");
1769        assert_eq!(slash_key(&joined), PathBuf::from("src/app/web.bynk"));
1770        assert_eq!(
1771            slash_key(Path::new("./src/a.bynk")),
1772            PathBuf::from("src/a.bynk")
1773        );
1774        #[cfg(windows)]
1775        assert_eq!(
1776            slash_key(Path::new(r"src\app/web.bynk")),
1777            PathBuf::from("src/app/web.bynk")
1778        );
1779        // On Unix a `\` is part of a file name, not a separator.
1780        #[cfg(unix)]
1781        assert_eq!(
1782            slash_key(Path::new(r"src/a\b.bynk")),
1783            PathBuf::from(r"src/a\b.bynk")
1784        );
1785    }
1786
1787    #[test]
1788    fn project_files_parses_the_wire_map() {
1789        let files = project_files(r#"{"bynk.toml":"x","src/a.bynk":"y"}"#);
1790        assert_eq!(
1791            files.get(Path::new("src/a.bynk")).map(String::as_str),
1792            Some("y")
1793        );
1794        assert!(project_files("not json").is_empty());
1795    }
1796
1797    // ---- #2695: entry handler signatures ----
1798
1799    const ENTRY_PROG: &str = "context app.sig\n\
1800        \n\
1801        type Slug = String where NonEmpty && MaxLength(20)\n\
1802        type Point = { x: Int, y: Int }\n\
1803        type Shape = | Dot | Circle(r: Int)\n\
1804        type Node = { label: String, next: Option[Node] }\n\
1805        \n\
1806        service greet {\n\
1807        \x20 on call(tag: Slug, n: Int, pts: List[Point], s: Shape, node: Node) -> Effect[String] by Caller {\n\
1808        \x20   \"hi\"\n\
1809        \x20 }\n\
1810        }\n";
1811
1812    fn compile_json(src: &str) -> serde_json::Value {
1813        serde_json::from_str(&compile_to_json(src, Platform::Browser)).unwrap()
1814    }
1815
1816    #[test]
1817    fn compile_reports_the_entry_handler_signature() {
1818        let v = compile_json(ENTRY_PROG);
1819        assert_eq!(v["ok"], true, "{v}");
1820        let entries = v["entries"].as_array().unwrap();
1821        assert_eq!(entries.len(), 1, "{entries:?}");
1822        let e = &entries[0];
1823        assert_eq!(e["unit"], "app.sig");
1824        assert_eq!(e["service"], "greet");
1825        assert_eq!(e["returns"], "Effect[String]");
1826        let params = e["params"].as_array().unwrap();
1827        let names: Vec<&str> = params.iter().map(|p| p["name"].as_str().unwrap()).collect();
1828        assert_eq!(names, ["tag", "n", "pts", "s", "node"]);
1829
1830        // The issue's example: a refined type reports what it refines.
1831        let tag = &params[0];
1832        assert_eq!(tag["type"], "Slug");
1833        assert_eq!(tag["base"], "String");
1834        assert_eq!(tag["refined"], true);
1835        assert_eq!(tag["shape"]["kind"], "refined");
1836
1837        // A plain base type is not refined.
1838        let n = &params[1];
1839        assert_eq!(n["type"], "Int");
1840        assert_eq!(n["base"], "Int");
1841        assert_eq!(n["refined"], false);
1842        assert_eq!(
1843            n["shape"],
1844            serde_json::json!({"kind": "base", "base": "Int"})
1845        );
1846
1847        // Lists and records are described structurally.
1848        let pts = &params[2];
1849        assert_eq!(pts["type"], "List[Point]");
1850        assert!(pts["base"].is_null());
1851        assert_eq!(pts["refined"], false);
1852        assert_eq!(pts["shape"]["kind"], "list");
1853        let point = &pts["shape"]["element"];
1854        assert_eq!(point["kind"], "record");
1855        assert_eq!(point["name"], "Point");
1856        assert_eq!(point["fields"][1]["name"], "y");
1857        assert_eq!(point["fields"][1]["shape"]["base"], "Int");
1858
1859        // Sums list their variants and payloads.
1860        let shape = &params[3]["shape"];
1861        assert_eq!(shape["kind"], "sum");
1862        assert_eq!(shape["variants"][0]["name"], "Dot");
1863        assert_eq!(shape["variants"][1]["fields"][0]["name"], "r");
1864
1865        // A self-referential record is named, not expanded forever.
1866        let next = &params[4]["shape"]["fields"][1]["shape"];
1867        assert_eq!(next["kind"], "option");
1868        assert_eq!(
1869            next["element"],
1870            serde_json::json!({"kind": "recursive", "name": "Node"})
1871        );
1872    }
1873
1874    #[test]
1875    fn compile_reports_no_params_for_a_nullary_entry() {
1876        let v = compile_json(PROG);
1877        assert_eq!(v["ok"], true);
1878        let entries = v["entries"].as_array().unwrap();
1879        assert_eq!(entries.len(), 1, "first-party units are not reported");
1880        assert_eq!(entries[0]["service"], "demo");
1881        assert!(entries[0]["params"].as_array().unwrap().is_empty());
1882    }
1883
1884    #[test]
1885    fn compile_failure_reports_no_entries_and_keeps_the_existing_shape() {
1886        let v = compile_json(
1887            "context app.bad\nservice s { on call(x: Nope) -> Effect[Int] by Caller { 1 } }\n",
1888        );
1889        assert_eq!(v["ok"], false);
1890        assert!(v["entries"].as_array().unwrap().is_empty());
1891        assert!(v["files"].as_array().unwrap().is_empty());
1892        assert!(!v["diagnostics"].as_array().unwrap().is_empty());
1893    }
1894
1895    #[test]
1896    fn compile_describes_opaque_map_result_set_and_generic_params() {
1897        let v = compile_json(
1898            "context app.more\n\
1899             \n\
1900             type Token = opaque String\n\
1901             type Page[T] = { items: List[T] }\n\
1902             \n\
1903             service s {\n\
1904             \x20 on call(t: Token, m: Map[String, Int], r: Result[Int, String], u: Set[Int], p: Page[Int]) -> Effect[Int] by Caller { 1 }\n\
1905             }\n",
1906        );
1907        assert_eq!(v["ok"], true, "{v}");
1908        let params = v["entries"][0]["params"].as_array().unwrap();
1909        assert_eq!(params[0]["shape"]["kind"], "opaque");
1910        assert_eq!(params[0]["base"], "String");
1911        assert_eq!(params[0]["refined"], false);
1912        assert_eq!(params[1]["shape"]["kind"], "map");
1913        assert_eq!(params[1]["shape"]["key"]["base"], "String");
1914        assert_eq!(params[1]["shape"]["value"]["base"], "Int");
1915        assert_eq!(params[2]["shape"]["kind"], "result");
1916        assert_eq!(params[2]["shape"]["err"]["base"], "String");
1917        assert_eq!(params[3]["shape"]["kind"], "set");
1918        assert_eq!(params[4]["shape"]["kind"], "other");
1919        assert_eq!(params[4]["shape"]["display"], "Page[Int]");
1920    }
1921
1922    #[test]
1923    fn compile_caps_the_expansion_depth() {
1924        // Eight nested records: past the cap a record is named, not expanded.
1925        let mut src = String::from("context app.deep\n\ntype R0 = { n: Int }\n");
1926        for i in 1..8 {
1927            src.push_str(&format!("type R{i} = {{ inner: R{} }}\n", i - 1));
1928        }
1929        src.push_str("\nservice s {\n  on call(r: R7) -> Effect[Int] by Caller { 1 }\n}\n");
1930        let v = compile_json(&src);
1931        assert_eq!(v["ok"], true, "{v}");
1932        let mut shape = &v["entries"][0]["params"][0]["shape"];
1933        let mut depth = 0;
1934        while shape["kind"] == "record" {
1935            shape = &shape["fields"][0]["shape"];
1936            depth += 1;
1937        }
1938        assert_eq!(depth, 6);
1939        assert_eq!(shape, &serde_json::json!({"kind": "named", "name": "R1"}));
1940    }
1941
1942    #[test]
1943    fn compile_expands_a_shared_record_once_per_parameter() {
1944        let v = compile_json(
1945            "context app.fan\n\
1946             \n\
1947             type P = { n: Int }\n\
1948             type W = { a: P, b: P, c: P }\n\
1949             \n\
1950             service s {\n\
1951             \x20 on call(w: W, p: P) -> Effect[Int] by Caller { 1 }\n\
1952             }\n",
1953        );
1954        assert_eq!(v["ok"], true, "{v}");
1955        let params = v["entries"][0]["params"].as_array().unwrap();
1956        let f = &params[0]["shape"]["fields"];
1957        assert_eq!(f[0]["shape"]["kind"], "record");
1958        let named = serde_json::json!({"kind": "named", "name": "P"});
1959        assert_eq!(f[1]["shape"], named);
1960        assert_eq!(f[2]["shape"], named);
1961        // The next parameter starts afresh.
1962        assert_eq!(params[1]["shape"]["kind"], "record");
1963    }
1964
1965    /// #2705: a `user` module carries a v3 source map; wiring and support
1966    /// files carry none (the field is omitted, not null).
1967    #[test]
1968    fn only_user_modules_carry_a_source_map() {
1969        let v = compile_json(PROG);
1970        let files = v["files"].as_array().unwrap();
1971        for f in files {
1972            match f["kind"].as_str().unwrap() {
1973                "user" => {
1974                    let m: serde_json::Value =
1975                        serde_json::from_str(f["map"].as_str().expect("user map")).unwrap();
1976                    assert_eq!(m["version"], 3);
1977                    assert_eq!(m["sources"], serde_json::json!(["app/demo.bynk"]));
1978                    assert!(
1979                        m.get("sourcesContent").is_none_or(
1980                            |c| c.is_null() || c.as_array().is_some_and(|a| a.is_empty())
1981                        )
1982                    );
1983                }
1984                _ => assert!(f.get("map").is_none(), "{}", f["path"]),
1985            }
1986        }
1987        assert!(files.iter().any(|f| f["kind"] == "user"));
1988    }
1989
1990    /// #2705: the map points a JS line back at the Bynk line it came from, so
1991    /// a host can highlight in both directions from the result alone.
1992    #[test]
1993    fn the_map_sends_a_js_line_back_to_its_bynk_line() {
1994        let v = compile_json(PROG);
1995        let user = v["files"]
1996            .as_array()
1997            .unwrap()
1998            .iter()
1999            .find(|f| f["kind"] == "user")
2000            .unwrap();
2001        let js = user["contents"].as_str().unwrap();
2002        let map = oxc_sourcemap::SourceMap::from_json_string(user["map"].as_str().unwrap())
2003            .expect("a parseable v3 map");
2004        let bynk_line_of = |needle: &str| -> Vec<u32> {
2005            let js_line = js
2006                .lines()
2007                .position(|l| l.contains(needle))
2008                .unwrap_or_else(|| panic!("`{needle}` in the JS:\n{js}"))
2009                as u32;
2010            map.get_tokens()
2011                .filter(|t| t.get_dst_line() == js_line)
2012                .map(|t| t.get_src_line())
2013                .collect()
2014        };
2015        // PROG: line 7 (1-based) is the Logger.info statement, line 8 Clock.now.
2016        let logger = bynk_line_of("Logger.info");
2017        assert!(logger.contains(&6), "Logger.info -> {logger:?}");
2018        let clock = bynk_line_of("Clock.now");
2019        assert!(clock.contains(&7), "Clock.now -> {clock:?}");
2020    }
2021}