Skip to main content

bynk_driver/
eval.rs

1//! `bynk eval` (#3585): evaluate a snippet in a project's context and report
2//! the value it ends in.
3//!
4//! The snippet becomes the body of one `case` in a synthetic `suite` that
5//! targets a unit of the project, exactly as a doc example marked `bynk test`
6//! does ([`crate::doc_examples`]), so it sees what a suite for that unit sees:
7//! the unit's declarations, its own `consumes`, and the `stub`s it declares. It
8//! is built and run by [`crate::test_runner::run_test`] under the test runtime,
9//! so no real capability is ever reached (a capability the snippet calls needs a
10//! `stub`). The case's last expression is not discarded, as an ordinary case's
11//! is: it is encoded as the wire shape `Json.encode` gives it and reported
12//! beside its type (`lower_test_case_body_reporting` in `bynk-emit`).
13//!
14//! **Stateless.** Each evaluation is independent. A client that wants an
15//! earlier cell's `let`s in scope sends them again ahead of the snippet.
16//!
17//! **Header.** A suite's `consumes` and `stub` clauses belong to the suite, not
18//! to a case, so the snippet's leading `consumes` and `stub` lines (with the
19//! blank and `//` comment lines among them) are the suite's, and the rest is
20//! the case's body. A snippet uses what it needs from another unit by
21//! `consumes`ing it, as a suite file does.
22//!
23//! **Line-preserving.** The synthetic suite has the snippet's lines, each on
24//! the line it has in the snippet; only the first line is longer, by the
25//! generated `suite … {` opening.
26//!
27//! This is an explicit, local run of code the user wrote in their own workspace,
28//! at the trust level of `bynk test`. It does not overturn ADR 0638, which kept
29//! the refined-type explorer off the build-and-run path because a hover is an
30//! implicit request.
31
32use std::collections::HashMap;
33use std::path::{Path, PathBuf};
34use std::process::ExitCode;
35use std::time::Duration;
36
37use bynk_syntax::ast::SourceUnit;
38use bynk_syntax::lexer::tokenize;
39use bynk_syntax::parser::parse_unit_with_recovery;
40use serde_json::Value;
41
42use crate::test_runner::{TestArgs, TestFormat, run_test};
43
44// 1B.2a (#4028): defined beside the test-harness generation that lowers it.
45pub use bynk_emit::testgen::EVAL_CASE;
46
47/// How long an evaluation may run before it is killed, when the caller sets no
48/// limit of its own.
49pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
50
51/// What to evaluate, and where.
52#[derive(Debug, Clone)]
53pub struct EvalRequest {
54    /// The project root.
55    pub input: PathBuf,
56    /// The dotted name of the unit (a `commons` or a `context`) whose scope the
57    /// snippet is evaluated in.
58    pub unit: String,
59    /// The snippet: optional leading `consumes`/`stub` lines, then statements
60    /// ending in the expression whose value is wanted.
61    pub snippet: String,
62    /// Unsaved buffers, layered over the project's files (ADR 0626): an
63    /// absolute path to the file's text.
64    pub buffers: HashMap<PathBuf, String>,
65    /// The project's own suites to build in, by target unit: the suites whose
66    /// `stub`s the snippet wants. Every other suite of the project is left out
67    /// of the build, so an unrelated suite that does not compile cannot block an
68    /// evaluation; a suite named here is built, and its errors are reported.
69    pub suites: Vec<String>,
70    /// The time limit. The evaluation is killed, and reported as timed out,
71    /// after this long.
72    pub timeout: Duration,
73}
74
75/// One diagnostic of a snippet that does not check.
76#[derive(Debug, Clone, PartialEq, serde::Serialize)]
77pub struct EvalDiagnostic {
78    /// The file it is in, as the project names it; absent for the snippet
79    /// itself, whose `line` and `col` are then the snippet's own (1-based).
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub file: Option<String>,
82    pub line: u32,
83    pub col: u32,
84    /// `"error"`, `"warning"` or `"hint"`.
85    pub severity: String,
86    /// The diagnostic's code, `bynk.types.let_annotation_mismatch`.
87    pub code: String,
88    pub message: String,
89}
90
91/// The result document `bynk eval` prints: `{"value", "type", "diagnostics"}`,
92/// and an `error` when the snippet ran to no value.
93#[derive(Debug, Clone, PartialEq)]
94pub struct EvalReport {
95    /// The wire shape of the snippet's last expression; `null` when there is
96    /// none (and when the expression is the unit value, which `type` tells).
97    /// Absent from the document when `error` is present.
98    pub value: Option<Value>,
99    /// That expression's type, or `null` with no value. Absent from the
100    /// document when `error` is present.
101    pub ty: Option<String>,
102    /// Why the snippet did not check, one entry each; empty otherwise.
103    pub diagnostics: Vec<EvalDiagnostic>,
104    /// Absent when there is a value or `diagnostics` says why not.
105    pub error: Option<EvalError>,
106}
107
108impl serde::Serialize for EvalReport {
109    /// `value` and `type` come first, and are left out when `error` says why
110    /// there is no value.
111    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
112        use serde::ser::SerializeMap as _;
113        let mut map = serializer.serialize_map(None)?;
114        if self.error.is_none() {
115            map.serialize_entry("value", &self.value)?;
116            map.serialize_entry("type", &self.ty)?;
117        }
118        map.serialize_entry("diagnostics", &self.diagnostics)?;
119        if let Some(error) = &self.error {
120            map.serialize_entry("error", error)?;
121        }
122        map.end()
123    }
124}
125
126/// A snippet that checked but ran to no value.
127#[derive(Debug, Clone, PartialEq, serde::Serialize)]
128pub struct EvalError {
129    /// `"runtime"` (a refusal, a failed `expect`, an unstubbed capability),
130    /// `"timeout"`, or `"setup"` (no such unit, no runner).
131    pub kind: &'static str,
132    pub message: String,
133}
134
135impl EvalReport {
136    /// Whether the snippet produced a value.
137    pub fn succeeded(&self) -> bool {
138        self.ty.is_some()
139    }
140}
141
142impl From<EvalOutcome> for EvalReport {
143    fn from(outcome: EvalOutcome) -> Self {
144        let none = |diagnostics, error| EvalReport {
145            value: None,
146            ty: None,
147            diagnostics,
148            error,
149        };
150        let error = |kind, message| none(Vec::new(), Some(EvalError { kind, message }));
151        match outcome {
152            EvalOutcome::Value { value, ty } => EvalReport {
153                value: Some(value),
154                ty: Some(ty),
155                diagnostics: Vec::new(),
156                error: None,
157            },
158            EvalOutcome::Diagnostics(diagnostics) => none(diagnostics, None),
159            EvalOutcome::Failed(message) => error("runtime", message),
160            EvalOutcome::TimedOut(message) => error("timeout", message),
161            EvalOutcome::Error(message) => error("setup", message),
162        }
163    }
164}
165
166/// Where the snippet sits in the file it was built into, to put a diagnostic
167/// back at the snippet's own line and column.
168struct Placement {
169    /// The file's key in the project's sources.
170    file: PathBuf,
171    /// The lines of the file ahead of the snippet's first.
172    line_offset: u32,
173    /// The snippet's lines.
174    lines: u32,
175    /// The characters generated ahead of the snippet on its first line.
176    prefix: usize,
177}
178
179impl Placement {
180    /// Whether `path`, as the run printed it (as typed from the working
181    /// directory, so possibly relative), is the file the snippet was built into.
182    /// The file may not exist on disk (a synthetic suite), so its directory is
183    /// compared canonically, and its name.
184    fn holds(&self, path: &Path) -> bool {
185        let canonical = |dir: Option<&Path>| {
186            let dir = dir
187                .filter(|d| !d.as_os_str().is_empty())
188                .unwrap_or(Path::new("."));
189            dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
190        };
191        path.file_name() == self.file.file_name()
192            && canonical(path.parent()) == canonical(self.file.parent())
193    }
194}
195
196/// The `--format short` line `line` as a diagnostic. A line with no location
197/// (`error[code]: message`) has line and column 0.
198fn parse_diagnostic(line: &str, at: &Placement) -> Option<EvalDiagnostic> {
199    let (location, rest) = [": error[", ": warning[", ": hint["]
200        .iter()
201        .find_map(|marker| {
202            line.find(marker)
203                .map(|at| (Some(&line[..at]), &line[at + 2..]))
204        })
205        .or_else(|| {
206            ["error[", "warning[", "hint["]
207                .iter()
208                .any(|m| line.starts_with(m))
209                .then_some((None, line))
210        })?;
211    let (severity, rest) = rest.split_once('[')?;
212    let (code, message) = rest.split_once("]: ")?;
213    let (mut file, mut line_no, mut col) = (None, 0u32, 0u32);
214    if let Some(location) = location {
215        let mut parts = location.rsplitn(3, ':');
216        col = parts.next()?.parse().ok()?;
217        line_no = parts.next()?.parse().ok()?;
218        let path = parts.next()?;
219        let in_snippet = at.holds(Path::new(path))
220            && line_no > at.line_offset
221            && line_no <= at.line_offset + at.lines;
222        if in_snippet {
223            // The snippet's own line; the first carries any generated opening.
224            line_no -= at.line_offset;
225            if line_no == 1 {
226                col = col.saturating_sub(at.prefix as u32).max(1);
227            }
228        } else {
229            file = Some(path.to_string());
230        }
231    }
232    Some(EvalDiagnostic {
233        file,
234        line: line_no,
235        col,
236        severity: severity.to_string(),
237        code: code.to_string(),
238        message: message.to_string(),
239    })
240}
241
242/// What an evaluation produced.
243#[derive(Debug, Clone, PartialEq)]
244pub enum EvalOutcome {
245    /// The snippet ran. `value` is the wire shape of its last expression and
246    /// `ty` that expression's type.
247    Value { value: Value, ty: String },
248    /// The project or the snippet did not compile: the diagnostics.
249    Diagnostics(Vec<EvalDiagnostic>),
250    /// The snippet compiled and ran, but a failure stopped it (a refused
251    /// refined-type construction, an `expect` that did not hold, a capability
252    /// with no stub).
253    Failed(String),
254    /// The snippet ran past its time limit and was killed.
255    TimedOut(String),
256    /// The evaluation could not be set up or run (no such unit, no runner).
257    Error(String),
258}
259
260/// The unit `text` declares, when it parses without an error. A warning the
261/// parser reports (a lint) does not stop a unit being found.
262fn parse_clean(text: &str) -> Option<SourceUnit> {
263    let tokens = tokenize(text).ok()?;
264    let (unit, errors) = parse_unit_with_recovery(&tokens, text);
265    errors
266        .iter()
267        .all(|e| bynk_syntax::Severity::for_error(e) != bynk_syntax::Severity::Error)
268        .then_some(unit)
269        .flatten()
270}
271
272/// The key, in `sources`, of the file that declares the unit `unit`.
273fn unit_file(sources: &HashMap<PathBuf, String>, unit: &str) -> Option<PathBuf> {
274    let mut keys: Vec<&PathBuf> = sources.keys().collect();
275    keys.sort();
276    keys.into_iter()
277        .find(|key| match parse_clean(&sources[*key]) {
278            Some(SourceUnit::Commons(c)) => c.name.joined() == unit,
279            Some(SourceUnit::Context(c)) => c.name.joined() == unit,
280            _ => false,
281        })
282        .cloned()
283}
284
285/// What stands in for a suite file left out of the build: a suite of one case
286/// that is never selected. (A suite with no case emits a module that does not
287/// type-check.)
288fn left_out(target: &str) -> String {
289    format!(
290        "// left out of this `bynk eval` build\nsuite {target} {{ case \"left out\" {{ expect 1 == 1 }} }}\n"
291    )
292}
293
294/// A stand-in for every suite of `sources` that is not among `keep` (by target
295/// unit), to lay over them: a snippet needs only its target unit's own
296/// declarations, and the project's suites are built only when asked for.
297fn left_out_suites(
298    sources: &HashMap<PathBuf, String>,
299    keep: &[String],
300) -> HashMap<PathBuf, String> {
301    let mut out = HashMap::new();
302    for (key, text) in sources {
303        let target = match parse_clean(text) {
304            Some(SourceUnit::Suite(suite)) => Some(suite.target.joined()),
305            Some(_) => None,
306            // A suite that does not parse is still left out, as the target its
307            // own `suite <name>` line names.
308            None => text.lines().find_map(|l| {
309                let name = l.strip_prefix("suite ")?;
310                let end = name.find(|c: char| c.is_whitespace() || c == '{');
311                Some(name[..end.unwrap_or(name.len())].to_string())
312            }),
313        };
314        if let Some(target) = target.filter(|t| !keep.contains(t)) {
315            out.insert(key.clone(), left_out(&target));
316        }
317    }
318    out
319}
320
321/// How many leading lines of `snippet` are the suite's own: `consumes` and
322/// `stub` clauses (each running to its closing bracket if it opens one), and
323/// the blank and `//` lines among them. Zero when the snippet opens with
324/// anything else.
325fn header_lines(snippet: &str) -> usize {
326    let mut end = 0;
327    let mut depth: i32 = 0;
328    for (i, line) in snippet.lines().enumerate() {
329        let trimmed = line.trim();
330        if depth > 0 {
331            // The continuation of a clause with an open bracket.
332        } else if trimmed.starts_with("consumes ") || trimmed.starts_with("stub ") {
333            end = i + 1;
334        } else if !(trimmed.is_empty() || trimmed.starts_with("//")) {
335            break;
336        }
337        if depth > 0 || trimmed.starts_with("consumes ") || trimmed.starts_with("stub ") {
338            depth += bracket_delta(trimmed);
339            if depth <= 0 {
340                depth = 0;
341                end = i + 1;
342            }
343        }
344    }
345    end
346}
347
348/// How many more brackets `line` opens than it closes, leaving out those in a
349/// string literal and in a `//` comment.
350fn bracket_delta(line: &str) -> i32 {
351    let mut delta = 0;
352    let mut in_string = false;
353    let mut chars = line.chars().peekable();
354    while let Some(c) = chars.next() {
355        match c {
356            '\\' if in_string => {
357                chars.next();
358            }
359            '"' => in_string = !in_string,
360            '/' if !in_string && chars.peek() == Some(&'/') => break,
361            '{' | '(' | '[' if !in_string => delta += 1,
362            '}' | ')' | ']' if !in_string => delta -= 1,
363            _ => {}
364        }
365    }
366    delta
367}
368
369/// The snippet's lines, with the case opened on the last header line (or the
370/// first, with no header) and no closer, and how many characters that opening
371/// adds to the first line.
372fn case_lines(snippet: &str) -> (Vec<String>, usize) {
373    let header = header_lines(snippet);
374    let mut lines: Vec<String> = snippet.lines().map(str::to_string).collect();
375    if lines.is_empty() {
376        lines.push(String::new());
377    }
378    let open = format!("case \"{EVAL_CASE}\" {{");
379    if header == 0 {
380        lines[0] = format!("{open} {}", lines[0]);
381        (lines, open.len() + 1)
382    } else {
383        lines[header - 1].push_str(&format!(" {open}"));
384        (lines, 0)
385    }
386}
387
388/// The synthetic suite for `snippet`, targeting `unit`: the snippet's own
389/// lines, with the suite and case openings added to the first and last header
390/// lines and the closers after the last line. Also how many characters the
391/// generated opening adds to the first line.
392pub fn suite_text(unit: &str, snippet: &str) -> (String, usize) {
393    let (mut lines, case_prefix) = case_lines(snippet);
394    let suite_prefix = format!("suite {unit} {{ ");
395    lines[0] = format!("{suite_prefix}{}", lines[0]);
396    let mut text = lines.join("\n");
397    text.push_str("\n} }\n");
398    (text, suite_prefix.len() + case_prefix)
399}
400
401/// `existing`, a suite file, with the snippet's case added at its end (before
402/// its closing brace, in brace form, whose offset is `close`): the snippet then
403/// sees the suite's own `consumes`, `stub`s, `fn`s and fixtures. Also the lines
404/// ahead of the snippet's first and the characters generated on it.
405fn merged_suite_text(existing: &str, close: Option<usize>, snippet: &str) -> (String, u32, usize) {
406    let (lines, prefix) = case_lines(snippet);
407    let head = &existing[..close.unwrap_or(existing.len())];
408    let mut text = format!("{head}\n{}\n", lines.join("\n"));
409    let offset = text[..head.len() + 1].matches('\n').count() as u32;
410    text.push_str("}\n");
411    if let Some(close) = close {
412        text.push_str(&existing[close..]);
413    }
414    (text, offset, prefix)
415}
416
417/// The suite file of `sources` for the target `unit` that a snippet is merged
418/// into when the caller names that suite: its key and the offset of its closing
419/// brace. An error says why the unit's suites cannot host a snippet.
420fn host_suite(
421    sources: &HashMap<PathBuf, String>,
422    unit: &str,
423) -> Result<(PathBuf, Option<usize>), String> {
424    let mut keys: Vec<&PathBuf> = sources.keys().collect();
425    keys.sort();
426    let mut other_tier = false;
427    for key in keys {
428        let text = &sources[key];
429        let Some(SourceUnit::Suite(suite)) = parse_clean(text) else {
430            continue;
431        };
432        if suite.target.joined() != unit {
433            continue;
434        }
435        // A suite of another tier cannot host a snippet; a unit suite can.
436        if suite
437            .tier
438            .is_some_and(|t| t != bynk_syntax::ast::TestTier::Unit)
439        {
440            other_tier = true;
441            continue;
442        }
443        let close = match suite.form {
444            bynk_syntax::ast::CommonsForm::Fragment => None,
445            bynk_syntax::ast::CommonsForm::Brace => match text[..suite.span.end].rfind('}') {
446                Some(at) => Some(at),
447                None => continue,
448            },
449        };
450        return Ok((key.clone(), close));
451    }
452    Err(if other_tier {
453        format!(
454            "`{unit}` has no unit suite for a snippet to be built into: its suites are of another tier, and a snippet is evaluated at the unit tier"
455        )
456    } else {
457        format!("there is no suite for `{unit}` to build the snippet into")
458    })
459}
460
461/// Run `request`: the snippet's value, or why there is none.
462pub fn evaluate(request: &EvalRequest) -> EvalOutcome {
463    // Absolute, so the synthetic file's key is inside the root an overlay is
464    // judged against, however the project was named.
465    // (Not `canonicalize`, which gives a `\\?\` path on Windows that `tsc` refuses.)
466    let input = std::path::absolute(&request.input).unwrap_or_else(|_| request.input.clone());
467    let options = match crate::try_project_options(&input) {
468        Ok(o) => o,
469        Err(e) => return EvalOutcome::Error(e.to_string()),
470    };
471    // The project's sources, with the buffers laid over them, to find the unit.
472    // A buffer is matched to a project file by canonical path, as the overlay
473    // is, however either was spelled.
474    let buffers: HashMap<PathBuf, String> = request
475        .buffers
476        .iter()
477        .map(|(path, text)| {
478            (
479                path.canonicalize().unwrap_or_else(|_| path.clone()),
480                text.clone(),
481            )
482        })
483        .collect();
484    let mut sources = options.sources.clone().unwrap_or_default();
485    sources.retain(|k, _| !buffers.contains_key(&k.canonicalize().unwrap_or_else(|_| k.clone())));
486    sources.extend(buffers.clone());
487    let Some(key) = unit_file(&sources, &request.unit) else {
488        return EvalOutcome::Error(format!(
489            "no `commons` or `context` named `{}` in the project",
490            request.unit
491        ));
492    };
493    // The suite sits beside the unit's file. A file the project really has is
494    // never overwritten.
495    let stem = key.file_stem().unwrap_or_default().to_string_lossy();
496    let mut synthetic = key.with_file_name(format!("{stem}.eval.bynk"));
497    let mut n = 0;
498    while sources.contains_key(&synthetic) {
499        n += 1;
500        synthetic = key.with_file_name(format!("{stem}.eval{n}.bynk"));
501    }
502    // The overlay judges a new file against the project's canonical root, so the
503    // suite is keyed by the canonical form of its folder (which exists).
504    let synthetic = match (
505        synthetic.parent().map(std::path::Path::canonicalize),
506        synthetic.file_name(),
507    ) {
508        (Some(Ok(dir)), Some(name)) => dir.join(name),
509        _ => synthetic,
510    };
511    let mut overlay = buffers;
512    overlay.extend(left_out_suites(&sources, &request.suites));
513    // Only the unit's own suite can host the snippet: it is the one whose
514    // `stub`s and `fn`s apply to a case of that unit.
515    if let Some(other) = request.suites.iter().find(|s| **s != request.unit) {
516        return EvalOutcome::Error(format!(
517            "`--suite {other}` is not the unit being evaluated (`{}`): only that unit's suite can hold the snippet",
518            request.unit
519        ));
520    }
521    let placement = if request.suites.is_empty() {
522        let (text, prefix) = suite_text(&request.unit, &request.snippet);
523        let lines = text.lines().count() as u32;
524        let placement = Placement {
525            file: synthetic.clone(),
526            line_offset: 0,
527            lines,
528            prefix,
529        };
530        overlay.insert(synthetic, text);
531        placement
532    } else {
533        let (key, close) = match host_suite(&sources, &request.unit) {
534            Ok(host) => host,
535            Err(message) => return EvalOutcome::Error(message),
536        };
537        let (text, line_offset, prefix) =
538            merged_suite_text(&sources[&key], close, &request.snippet);
539        let lines = request.snippet.lines().count().max(1) as u32;
540        overlay.insert(key.clone(), text);
541        Placement {
542            file: key,
543            line_offset,
544            lines,
545            prefix,
546        }
547    };
548    let args = TestArgs {
549        no_run: false,
550        format: TestFormat::Json,
551        suite: vec![request.unit.clone()],
552        case: vec![EVAL_CASE.to_string()],
553        run_timeout: Some(request.timeout),
554        overlay: Some(overlay),
555        ..TestArgs::discovery(input)
556    };
557    let (code, text) = crate::test_stream::capture(|| run_test("bynk", args));
558    interpret(code, &text, &placement)
559}
560
561/// What the `bynk test --format json` document `text` says about the snippet.
562fn interpret(code: ExitCode, text: &str, at: &Placement) -> EvalOutcome {
563    let Ok(doc) = serde_json::from_str::<Value>(text) else {
564        return EvalOutcome::Error(format!("the test run said: {}", text.trim()));
565    };
566    let lines = |key: &str| -> Vec<String> {
567        doc["error"][key]
568            .as_array()
569            .into_iter()
570            .flatten()
571            .filter_map(|l| l.as_str().map(str::to_string))
572            .collect()
573    };
574    let message = doc["error"]["message"].as_str().map(str::to_string);
575    match doc["error"]["kind"].as_str() {
576        Some("compile") => {
577            return EvalOutcome::Diagnostics(
578                lines("diagnostics")
579                    .iter()
580                    .filter_map(|l| parse_diagnostic(l, at))
581                    .collect(),
582            );
583        }
584        Some("timeout") => {
585            return EvalOutcome::TimedOut(message.unwrap_or_else(|| "timed out".to_string()));
586        }
587        Some(_) => {
588            let mut parts: Vec<String> = message.into_iter().collect();
589            parts.extend(doc["error"]["stderr"].as_str().map(str::to_string));
590            return EvalOutcome::Error(parts.join("\n"));
591        }
592        None => {}
593    }
594    if let Some(eval) = doc.get("eval") {
595        let ty = eval["type"].as_str().unwrap_or_default().to_string();
596        return match eval.get("value") {
597            Some(value) => EvalOutcome::Value {
598                value: value.clone(),
599                ty,
600            },
601            None => EvalOutcome::Failed(format!(
602                "the snippet ran, but its value, of type `{ty}`, has no wire shape to report"
603            )),
604        };
605    }
606    let failure = doc["suites"]
607        .as_array()
608        .into_iter()
609        .flatten()
610        .flat_map(|s| s["cases"].as_array().into_iter().flatten())
611        .find(|c| c["outcome"] == "fail")
612        .map(|c| c["message"].as_str().unwrap_or("the snippet failed"));
613    match failure {
614        Some(message) => EvalOutcome::Failed(message.to_string()),
615        None if code == ExitCode::SUCCESS => {
616            EvalOutcome::Error("the snippet ran but reported no value".to_string())
617        }
618        None => EvalOutcome::Error(format!("the test run failed: {}", text.trim())),
619    }
620}
621
622#[cfg(test)]
623mod tests {
624    use super::*;
625
626    #[test]
627    fn a_snippet_without_a_header_is_all_case_body() {
628        assert_eq!(header_lines("let x = 1\nx + 1"), 0);
629        assert_eq!(
630            suite_text("demo.calc", "double(21)"),
631            (
632                "suite demo.calc { case \"bynk eval\" { double(21)\n} }\n".to_string(),
633                "suite demo.calc { case \"bynk eval\" { ".len()
634            )
635        );
636    }
637
638    #[test]
639    fn leading_consumes_and_stub_lines_are_the_suites() {
640        let snippet =
641            "consumes shop.order { Placed }\n// a stub\nstub Clock.now() returns 0\nlet x = 1\nx";
642        assert_eq!(header_lines(snippet), 3);
643        assert_eq!(
644            suite_text("demo.calc", snippet).0,
645            "suite demo.calc { consumes shop.order { Placed }\n// a stub\nstub Clock.now() returns 0 case \"bynk eval\" {\nlet x = 1\nx\n} }\n"
646        );
647    }
648
649    #[test]
650    fn a_clause_with_an_open_bracket_runs_to_its_close() {
651        let snippet = "consumes shop.order {\n  Placed,\n  Shipped,\n}\nlet n = 1\nn";
652        assert_eq!(header_lines(snippet), 4);
653    }
654
655    #[test]
656    fn a_clause_after_a_statement_is_the_bodys() {
657        // It is a parse error there, and the compiler says so at its line.
658        assert_eq!(header_lines("let x = 1\nconsumes a.b\nx"), 0);
659    }
660
661    const UNIT: &str = "\
662context demo
663
664consumes bynk { Fetch, Request, Method, Response }
665
666type Percent = Int where InRange(0, 100)
667
668fn double(n: Int) -> Int {
669  n * 2
670}
671
672fn spin(n: Int) -> Int {
673  spin(n + 1)
674}
675
676service relay {
677  on call(url: String) -> Effect[Int] by Caller given Fetch {
678    let res <- Fetch.send(Request {
679      method: Get,
680      url: url,
681      contentType: None,
682      authorization: None,
683      headers: Map.empty(),
684      body: None,
685    })
686    match res {
687      Ok(r) => Effect.pure(r.status)
688      Err(_) => Effect.pure(-1)
689    }
690  }
691}
692";
693
694    const FETCH: &str = "\
695consumes bynk { Fetch, Request, Method, Response }
696let res <- Fetch.send(Request { method: Get, url: \"https://example.com\", contentType: None, authorization: None, headers: Map.empty(), body: None })
697";
698
699    /// A scratch project, removed when dropped.
700    struct Project(PathBuf);
701
702    impl std::ops::Deref for Project {
703        type Target = Path;
704        fn deref(&self) -> &Path {
705            &self.0
706        }
707    }
708
709    impl Drop for Project {
710        fn drop(&mut self) {
711            let _ = std::fs::remove_dir_all(&self.0);
712        }
713    }
714
715    fn project(tag: &str) -> Project {
716        project_with(tag, UNIT)
717    }
718
719    fn project_with(tag: &str, unit: &str) -> Project {
720        let root = std::env::temp_dir().join(format!("bynk_eval_{tag}_{}", std::process::id()));
721        let _ = std::fs::remove_dir_all(&root);
722        std::fs::create_dir_all(root.join("src")).unwrap();
723        std::fs::write(root.join("bynk.toml"), "[project]\nname = \"p\"\n").unwrap();
724        std::fs::write(root.join("src/demo.bynk"), unit).unwrap();
725        // Not `canonicalize`, which gives a `\\?\` path on Windows that `tsc` refuses.
726        Project(std::path::absolute(&root).unwrap())
727    }
728
729    fn eval_with(root: &Path, snippet: &str, timeout: Duration) -> EvalOutcome {
730        evaluate(&EvalRequest {
731            input: root.to_path_buf(),
732            unit: "demo".to_string(),
733            snippet: snippet.to_string(),
734            buffers: HashMap::new(),
735            suites: Vec::new(),
736            timeout,
737        })
738    }
739
740    fn eval(root: &Path, snippet: &str) -> EvalOutcome {
741        eval_with(root, snippet, Duration::from_secs(120))
742    }
743
744    fn value(outcome: EvalOutcome) -> (Value, String) {
745        match outcome {
746            EvalOutcome::Value { value, ty } => (value, ty),
747            other => panic!("expected a value, got {other:?}"),
748        }
749    }
750
751    /// One project, several evaluations: each is a real build and run.
752    #[test]
753    fn evaluates_in_a_units_scope() {
754        let root = project("scope");
755
756        let (v, ty) = value(eval(&root, "double(21)"));
757        assert_eq!((v, ty.as_str()), (serde_json::json!(42), "Int"));
758
759        // Earlier cells arrive as a preamble of `let`s.
760        let (v, _) = value(eval(&root, "let x = 4\ndouble(x)"));
761        assert_eq!(v, serde_json::json!(8));
762
763        let (v, ty) = value(eval(&root, "[1, 2, 3]"));
764        assert_eq!(
765            (v, ty.as_str()),
766            (serde_json::json!([1, 2, 3]), "List[Int]")
767        );
768
769        // A refined-type construction that succeeds, and one that fails.
770        let (v, ty) = value(eval(&root, "Percent.of(50)"));
771        assert_eq!(v, serde_json::json!({"kind": "Ok", "value": 50}));
772        assert_eq!(ty, "Result[Percent, ValidationError]");
773        let (v, _) = value(eval(&root, "Percent.of(500)"));
774        assert_eq!(v["kind"], "Err");
775        assert_eq!(v["error"]["message"], "must be in range [0, 100]");
776    }
777
778    #[test]
779    fn a_capability_needs_a_stub() {
780        let root = project("stub");
781        // Unstubbed, the test runtime refuses: nothing reaches the network.
782        match eval(&root, &format!("{FETCH}res")) {
783            EvalOutcome::Failed(message) => {
784                assert!(message.contains("`Fetch.send` is not stubbed"), "{message}");
785            }
786            other => panic!("expected a refusal, got {other:?}"),
787        }
788        // Stubbed in the preamble, it answers.
789        let stubbed = format!(
790            "stub Fetch.send(_) returns Ok(Response {{ status: 204, headers: Map.empty(), body: \"\" }})\n{FETCH}"
791        );
792        let (v, _) = value(eval(&root, &format!("{stubbed}res")));
793        assert_eq!(v["kind"], "Ok");
794        assert_eq!(v["value"]["status"], 204);
795    }
796
797    #[test]
798    fn a_snippet_that_does_not_check_reports_diagnostics() {
799        let root = project("diag");
800        match eval(&root, "let x: Int = \"oops\"\nx") {
801            EvalOutcome::Diagnostics(found) => {
802                // In the snippet, on its line, at the column in the snippet.
803                let d = found
804                    .iter()
805                    .find(|d| d.code == "bynk.types.let_annotation_mismatch")
806                    .unwrap_or_else(|| panic!("{found:?}"));
807                assert_eq!((d.file.as_deref(), d.line, d.col), (None, 1, 14));
808                assert_eq!(d.severity, "error");
809            }
810            other => panic!("expected diagnostics, got {other:?}"),
811        }
812    }
813
814    #[test]
815    fn a_snippet_that_does_not_end_is_killed() {
816        let root = project("timeout");
817        let outcome = eval_with(&root, "spin(0)", Duration::from_secs(5));
818        assert!(matches!(outcome, EvalOutcome::TimedOut(_)), "{outcome:?}");
819    }
820
821    #[test]
822    fn an_unsaved_buffer_is_what_is_evaluated() {
823        let root = project("buffer");
824        let file = root.join("src/demo.bynk");
825        let edited = UNIT.replace("n * 2", "n * 3");
826        let outcome = evaluate(&EvalRequest {
827            input: root.to_path_buf(),
828            unit: "demo".to_string(),
829            snippet: "double(2)".to_string(),
830            buffers: HashMap::from([(file, edited)]),
831            suites: Vec::new(),
832            timeout: Duration::from_secs(120),
833        });
834        assert_eq!(value(outcome).0, serde_json::json!(6));
835    }
836
837    #[test]
838    fn an_unknown_unit_is_an_error() {
839        let root = project("unknown");
840        let outcome = evaluate(&EvalRequest {
841            input: root.to_path_buf(),
842            unit: "nope".to_string(),
843            snippet: "1".to_string(),
844            buffers: HashMap::new(),
845            suites: Vec::new(),
846            timeout: Duration::from_secs(5),
847        });
848        assert!(matches!(outcome, EvalOutcome::Error(_)), "{outcome:?}");
849    }
850
851    #[test]
852    fn a_short_line_is_a_diagnostic() {
853        let at = |file: &str, line_offset, lines| Placement {
854            file: PathBuf::from(file),
855            line_offset,
856            lines,
857            prefix: 10,
858        };
859        let synthetic = at("/p/src/demo.eval.bynk", 0, 3);
860        let d = parse_diagnostic(
861            "/p/src/demo.eval.bynk:2:5: error[bynk.resolve.unknown_name]: unknown name `x`",
862            &synthetic,
863        )
864        .unwrap();
865        assert_eq!((d.file, d.line, d.col), (None, 2, 5));
866        let d = parse_diagnostic(
867            "/p/src/demo.bynk:7:1: warning[a.b]: odd: really",
868            &synthetic,
869        )
870        .unwrap();
871        assert_eq!(d.file.as_deref(), Some("/p/src/demo.bynk"));
872        assert_eq!(d.message, "odd: really");
873        let d = parse_diagnostic("error[a.b]: no place", &synthetic).unwrap();
874        assert_eq!((d.line, d.col), (0, 0));
875        // Built into a suite file, the lines ahead of the snippet and after it
876        // are the suite's own, and so is a file of the same name elsewhere.
877        let hosted = at("/p/tests/demo.bynk", 8, 2);
878        let line = |path: &str, n: u32| format!("{path}:{n}:3: error[a.b]: here");
879        let found = parse_diagnostic(&line("/p/tests/demo.bynk", 9), &hosted).unwrap();
880        assert_eq!((found.file, found.line), (None, 1));
881        for (path, n) in [
882            ("/p/tests/demo.bynk", 4),
883            ("/p/tests/demo.bynk", 11),
884            ("/p/src/demo.bynk", 9),
885        ] {
886            let d = parse_diagnostic(&line(path, n), &hosted).unwrap();
887            assert_eq!((d.file.as_deref(), d.line), (Some(path), n));
888        }
889    }
890
891    #[test]
892    fn brackets_in_strings_and_comments_do_not_extend_a_clause() {
893        let snippet = "stub Fetch.send(_) returns Ok(Response { status: 200, headers: Map.empty(), body: \"(\" })\nconsumes a.b // (old)\nlet x = 1\nx";
894        assert_eq!(header_lines(snippet), 2);
895    }
896
897    #[test]
898    fn a_value_with_no_wire_shape_says_so() {
899        let root = project("shapeless");
900        match eval(&root, "Effect.pure(1)") {
901            EvalOutcome::Failed(message) => {
902                assert!(message.contains("no wire shape"), "{message}");
903            }
904            other => panic!("expected a report of no wire shape, got {other:?}"),
905        }
906    }
907
908    const MAILER_UNIT: &str = "\
909context demo
910
911capability Mailer {
912  fn send(to: String) -> Effect[Bool]
913}
914
915service api from http {
916  on POST(\"/todos\") (body: String) -> Effect[HttpResult[String]] by v: Visitor given Mailer {
917    let sent <- Mailer.send(\"bob\")
918    if sent { Created(body) } else { BadRequest(\"no mail\") }
919  }
920}
921";
922
923    /// #3699: a `trace(Cap.op)` list, and one of its call records, have the
924    /// wire shape of a record of the operation's parameters. The module's codec
925    /// closure once held the list's codec but not the record's, so the
926    /// generated TypeScript did not type-check.
927    #[test]
928    fn a_trace_of_call_records_reports_its_value() {
929        let root = project_with("trace_records", MAILER_UNIT);
930        let run =
931            "stub Mailer.send(_) returns true\nlet r <- api.POST(\"/todos\", \"x\") by Visitor\n";
932        let (v, ty) = value(eval(&root, &format!("{run}trace(Mailer.send)")));
933        assert_eq!(
934            (v, ty.as_str()),
935            (
936                serde_json::json!([{"to": "bob"}]),
937                "List[__Mailer_send_Call]"
938            )
939        );
940        let (v, _) = value(eval(&root, &format!("{run}trace(Mailer.send).get(0)")));
941        assert_eq!(
942            v,
943            serde_json::json!({"kind": "Some", "value": {"to": "bob"}})
944        );
945        let (v, _) = value(eval(
946            &root,
947            &format!(
948                "{run}match trace(Mailer.send).get(0) {{ Some(c) => Json.encode(c), None => \"\" }}"
949            ),
950        ));
951        assert_eq!(v, serde_json::json!("{\"to\":\"bob\"}"));
952    }
953
954    const STUBBING_SUITE: &str = "\
955suite demo {
956  consumes bynk { Fetch, Request, Method, Response }
957  stub Fetch.send(_) returns Ok(Response { status: 204, headers: Map.empty(), body: \"\" })
958
959  case \"x\" {
960    expect double(1) == 2
961  }
962}
963";
964
965    fn with_suite(root: &Path, text: &str) {
966        std::fs::create_dir_all(root.join("tests")).unwrap();
967        std::fs::write(root.join("tests/demo.bynk"), text).unwrap();
968    }
969
970    #[test]
971    fn a_suite_that_does_not_compile_does_not_block_an_evaluation() {
972        let root = project("broken_suite");
973        with_suite(
974            &root,
975            "suite demo {\n  case \"broken\" {\n    let x: Int = \"no\"\n    expect x == 1\n  }\n}\n",
976        );
977        // Another unit's suite, left out as well, still builds a module that
978        // type-checks beside the evaluation's.
979        std::fs::write(
980            root.join("src/other.bynk"),
981            "commons other\n\nfn one() -> Int {\n  1\n}\n",
982        )
983        .unwrap();
984        std::fs::write(
985            root.join("tests/other.bynk"),
986            "suite other {\n  case \"one\" {\n    expect one() == 1\n  }\n}\n",
987        )
988        .unwrap();
989        assert_eq!(value(eval(&root, "double(2)")).0, serde_json::json!(4));
990    }
991
992    #[test]
993    fn a_named_suite_is_built_in_and_its_stubs_apply() {
994        let root = project("named_suite");
995        with_suite(&root, STUBBING_SUITE);
996        let send = FETCH.to_string() + "res";
997        // Left out, the suite's stub is not there to answer.
998        assert!(matches!(eval(&root, &send), EvalOutcome::Failed(_)));
999        // Named, it is, and the snippet needs no stub of its own.
1000        let request = |suites: Vec<String>| EvalRequest {
1001            input: root.to_path_buf(),
1002            unit: "demo".to_string(),
1003            snippet: FETCH.to_string() + "res",
1004            buffers: HashMap::new(),
1005            suites,
1006            timeout: Duration::from_secs(120),
1007        };
1008        let (v, _) = value(evaluate(&request(vec!["demo".to_string()])));
1009        assert_eq!(v["value"]["status"], 204);
1010        // And a named suite that does not compile is reported.
1011        with_suite(
1012            &root,
1013            "suite demo {\n  case \"x\" {\n    let n: Int = \"no\"\n  }\n}\n",
1014        );
1015        match evaluate(&request(vec!["demo".to_string()])) {
1016            EvalOutcome::Diagnostics(d) => {
1017                let d = &d[0];
1018                assert_eq!(d.line, 3, "{d:?}");
1019                assert!(
1020                    d.file.as_deref().is_some_and(|f| f.ends_with("demo.bynk")),
1021                    "{d:?}"
1022                );
1023            }
1024            other => panic!("expected the suite's diagnostics, got {other:?}"),
1025        }
1026    }
1027
1028    fn request(root: &Path, snippet: &str, suites: &[&str]) -> EvalRequest {
1029        EvalRequest {
1030            input: root.to_path_buf(),
1031            unit: "demo".to_string(),
1032            snippet: snippet.to_string(),
1033            buffers: HashMap::new(),
1034            suites: suites.iter().map(|s| s.to_string()).collect(),
1035            timeout: Duration::from_secs(120),
1036        }
1037    }
1038
1039    #[test]
1040    fn an_error_in_the_unit_is_the_units_even_when_a_suite_hosts_the_snippet() {
1041        let root = project("hosted_unit_error");
1042        with_suite(&root, STUBBING_SUITE);
1043        // The unit and its suite are both `demo.bynk`, in different folders; the
1044        // error is on a line past the suite's own.
1045        let file = root.join("src/demo.bynk");
1046        let broken = format!("{UNIT}\nfn bad() -> Int {{\n  \"no\"\n}}\n");
1047        let line = broken.lines().position(|l| l.contains("\"no\"")).unwrap() as u32 + 1;
1048        let mut r = request(&root, "1", &["demo"]);
1049        r.buffers = HashMap::from([(file, broken)]);
1050        match evaluate(&r) {
1051            EvalOutcome::Diagnostics(d) => {
1052                let d = d
1053                    .iter()
1054                    .find(|d| d.line == line)
1055                    .unwrap_or_else(|| panic!("{d:?}"));
1056                assert!(
1057                    d.file.as_deref().is_some_and(|f| f.ends_with("demo.bynk")),
1058                    "{d:?}"
1059                );
1060            }
1061            other => panic!("expected diagnostics, got {other:?}"),
1062        }
1063    }
1064
1065    #[test]
1066    fn a_unit_suite_hosts_the_snippet_whatever_other_suites_the_unit_has() {
1067        let root = project("tiers");
1068        with_suite(&root, STUBBING_SUITE);
1069        // Sorts before `demo.bynk`, and is not a unit suite.
1070        std::fs::write(
1071            root.join("tests/a_integration.bynk"),
1072            "suite demo as integration {\n  case \"integrated\" {\n    expect 1 == 1\n  }\n}\n",
1073        )
1074        .unwrap();
1075        let (v, _) = value(evaluate(&request(
1076            &root,
1077            &(FETCH.to_string() + "res"),
1078            &["demo"],
1079        )));
1080        assert_eq!(v["value"]["status"], 204);
1081    }
1082
1083    #[test]
1084    fn a_suite_that_cannot_host_is_said_so() {
1085        let root = project("no_host");
1086        // No suite at all.
1087        match evaluate(&request(&root, "1", &["demo"])) {
1088            EvalOutcome::Error(m) => assert!(m.contains("no suite for `demo`"), "{m}"),
1089            other => panic!("{other:?}"),
1090        }
1091        // Only another tier's.
1092        std::fs::create_dir_all(root.join("tests")).unwrap();
1093        std::fs::write(
1094            root.join("tests/demo.bynk"),
1095            "suite demo as integration {\n  case \"x\" {\n    expect 1 == 1\n  }\n}\n",
1096        )
1097        .unwrap();
1098        match evaluate(&request(&root, "1", &["demo"])) {
1099            EvalOutcome::Error(m) => assert!(m.contains("another tier"), "{m}"),
1100            other => panic!("{other:?}"),
1101        }
1102        // A suite that is not the unit's.
1103        match evaluate(&request(&root, "1", &["other"])) {
1104            EvalOutcome::Error(m) => assert!(m.contains("not the unit being evaluated"), "{m}"),
1105            other => panic!("{other:?}"),
1106        }
1107    }
1108
1109    #[test]
1110    fn a_suite_that_does_not_parse_is_left_out_as_the_target_it_names() {
1111        let sources = HashMap::from([(
1112            PathBuf::from("/p/tests/other.bynk"),
1113            "suite other {\n  case \"x\" {{{\n".to_string(),
1114        )]);
1115        assert_eq!(left_out_suites(&sources, &[]).len(), 1);
1116        // Named, the broken suite is kept, so its errors are the evaluation's.
1117        assert!(left_out_suites(&sources, &["other".to_string()]).is_empty());
1118    }
1119
1120    #[test]
1121    fn a_report_leaves_out_value_and_type_when_it_has_an_error() {
1122        let report = EvalReport::from(EvalOutcome::Failed("no".to_string()));
1123        assert_eq!(
1124            serde_json::to_string(&report).unwrap(),
1125            r#"{"diagnostics":[],"error":{"kind":"runtime","message":"no"}}"#
1126        );
1127        let report = EvalReport::from(EvalOutcome::Value {
1128            value: serde_json::json!(1),
1129            ty: "Int".to_string(),
1130        });
1131        assert_eq!(
1132            serde_json::to_string(&report).unwrap(),
1133            r#"{"value":1,"type":"Int","diagnostics":[]}"#
1134        );
1135    }
1136
1137    #[test]
1138    fn a_unit_the_parser_only_warns_about_is_found() {
1139        // Three nested `match`es draw a lint from the parser, not an error.
1140        let unit = "\
1141context demo
1142
1143fn sum(a: Option[Int], b: Option[Int], c: Option[Int]) -> Int {
1144  match a {
1145    Some(x) => match b {
1146      Some(y) => match c {
1147        Some(z) => x + y + z
1148        None => 0
1149      }
1150      None => 0
1151    }
1152    None => 0
1153  }
1154}
1155";
1156        let root = project_with("lint", unit);
1157        let (v, _) = value(eval(&root, "sum(Some(1), Some(2), Some(3))"));
1158        assert_eq!(v, serde_json::json!(6));
1159    }
1160}