Skip to main content

bynk_check/
fixtures.rs

1//! #2841: the checker-side rules for a suite's `fixture name = "path"`
2//! declarations — the path rules and the content rules shared with `embed`
3//! ([`crate::embeds`], [`crate::assets`]) but for the project's `fixtures/`
4//! folder, the name rules, and the unused warning.
5//!
6//! A fixture is a project file's text, a `String` constant in the declaring
7//! suite's cases. Unlike an embed it is test-only: its text goes into test
8//! output and never into a deployable, so it comes from `fixtures/` (not
9//! `embeds/`), may be large ([`MAX_FIXTURE_BYTES`]), and has no project total.
10//!
11//! The checker stays disk-free: the folder reaches it from the caller as a
12//! [`bynk_project::assets::FixtureFolder`], and [`read_declared_fixtures`] reads
13//! only the files a declaration names.
14
15use std::collections::{BTreeMap, BTreeSet, HashSet};
16
17use bynk_syntax::ast::{
18    ArgPattern, Block, ExprKind, FixtureDecl, SeqOutcome, SourceUnit, StubRhs, SuiteDecl,
19    expr_children, statement_exprs,
20};
21use bynk_syntax::error::CompileError;
22
23use crate::project_model::ErrorSink;
24use bynk_project::ParsedFile;
25
26/// The largest fixture file, in bytes. A fixture never ships, so the cap only
27/// keeps a test module a reasonable size; there is no project total.
28pub const MAX_FIXTURE_BYTES: usize = 4 * 1024 * 1024;
29
30/// `bynk.fixture.unsafe_path` for `f`, when its path is empty, absolute or
31/// contains a `..` segment (the rule an asset's and an embed's paths follow).
32pub fn unsafe_path_error(f: &FixtureDecl) -> Option<CompileError> {
33    let reason = crate::assets::unsafe_asset_path_reason(&f.path)?;
34    Some(
35        CompileError::new(
36            "bynk.fixture.unsafe_path",
37            f.path_span,
38            format!("fixture `{}` has an unsafe path: {reason}", f.name.name),
39        )
40        .with_note("a fixture path is relative to the project root and must stay inside it"),
41    )
42}
43
44/// `bynk.fixture.outside_fixtures_dir` for `f`, when its path is safe but does
45/// not lie inside the project's fixtures folder, so a declaration can never
46/// read `.env` or a source file by mistake.
47pub fn outside_fixtures_dir_error(f: &FixtureDecl) -> Option<CompileError> {
48    if crate::assets::unsafe_asset_path_reason(&f.path).is_some()
49        || bynk_project::assets::is_in_fixtures_dir(&f.path)
50    {
51        return None;
52    }
53    let dir = bynk_project::assets::PROJECT_FIXTURES_DIR;
54    Some(
55        CompileError::new(
56            "bynk.fixture.outside_fixtures_dir",
57            f.path_span,
58            format!(
59                "fixture `{}` must name a file in the project's `{dir}/` folder",
60                f.name.name
61            ),
62        )
63        .with_note(format!(
64            "a fixture comes only from `{dir}/`; move the file there and name it `{dir}/…`"
65        )),
66    )
67}
68
69/// The path rules for `f`, in order (at most one applies).
70pub fn path_errors(f: &FixtureDecl) -> Option<CompileError> {
71    unsafe_path_error(f).or_else(|| outside_fixtures_dir_error(f))
72}
73
74/// The suite of a parsed file, when it is one.
75fn suite_of(pf: &ParsedFile) -> Option<&SuiteDecl> {
76    match pf.unit() {
77        SourceUnit::Suite(s) => Some(s),
78        _ => None,
79    }
80}
81
82/// The path errors ([`path_errors`]) for each fixture, and
83/// `bynk.fixture.missing_file` for each whose (otherwise valid) path
84/// names no file in `available` — the project's `fixtures/` folder as the
85/// caller read it. `None` skips the check (nothing on disk was consulted).
86pub fn phase_fixture_files(
87    parsed: &[ParsedFile],
88    available: Option<&BTreeSet<String>>,
89    errors: &mut ErrorSink,
90) {
91    for pf in parsed {
92        let Some(suite) = suite_of(pf) else { continue };
93        for f in &suite.fixtures {
94            // The path rules need no folder, so they hold for a check too.
95            if let Some(e) = path_errors(f) {
96                errors.push_for(Some(&pf.identity_path()), e);
97                continue;
98            }
99            let Some(available) = available else { continue };
100            let key = bynk_project::assets::normalise_asset_path(&f.path);
101            if !available.contains(&key) {
102                errors.push_for(
103                    Some(&pf.identity_path()),
104                    CompileError::new(
105                        "bynk.fixture.missing_file",
106                        f.path_span,
107                        format!(
108                            "fixture `{}` names `{key}`, which does not exist",
109                            f.name.name
110                        ),
111                    )
112                    .with_note(
113                        "a fixture must be a regular file in the project's `fixtures/` folder; symbolic links are not followed",
114                    ),
115                );
116            }
117        }
118    }
119}
120
121/// The text of every declared fixture file in `folder`, keyed by normalised
122/// path — read through the folder's reader once each, and only for a file a
123/// declaration names. Content rules are an embed's ([`crate::embeds::embedded_text`]):
124/// valid UTF-8 (`bynk.fixture.invalid_encoding`), no NUL byte
125/// (`bynk.fixture.binary_content`), a BOM dropped and newlines normalised; and
126/// at most [`MAX_FIXTURE_BYTES`] (`bynk.fixture.too_large`). A read failure is
127/// `bynk.fixture.unreadable_file`. Each is reported on every declaration that
128/// names the file, and the file is left out.
129pub fn read_declared_fixtures(
130    parsed: &[ParsedFile],
131    folder: &bynk_project::assets::FixtureFolder,
132    errors: &mut ErrorSink,
133) -> BTreeMap<String, String> {
134    let mut out: BTreeMap<String, String> = BTreeMap::new();
135    let mut refused: BTreeMap<String, (&'static str, String)> = BTreeMap::new();
136    for pf in parsed {
137        let Some(suite) = suite_of(pf) else { continue };
138        for f in &suite.fixtures {
139            if path_errors(f).is_some() {
140                continue;
141            }
142            let key = bynk_project::assets::normalise_asset_path(&f.path);
143            if !folder.files().contains(&key) || out.contains_key(&key) {
144                continue;
145            }
146            if !refused.contains_key(&key) {
147                match read_one(folder, &key) {
148                    Ok(text) => {
149                        out.insert(key.clone(), text);
150                        continue;
151                    }
152                    Err(refusal) => {
153                        refused.insert(key.clone(), refusal);
154                    }
155                }
156            }
157            let (code, detail) = &refused[&key];
158            errors.push_for(
159                Some(&pf.identity_path()),
160                refusal_error(code, f, &key, detail),
161            );
162        }
163    }
164    out
165}
166
167/// One file's text, or the diagnostic code and detail that refuse it.
168fn read_one(
169    folder: &bynk_project::assets::FixtureFolder,
170    key: &str,
171) -> Result<String, (&'static str, String)> {
172    let bytes = folder.read(key).map_err(|e| {
173        (
174            "bynk.fixture.unreadable_file",
175            format!("the read failed: {e}"),
176        )
177    })?;
178    if bytes.len() > MAX_FIXTURE_BYTES {
179        return Err((
180            "bynk.fixture.too_large",
181            format!(
182                "it is {} bytes, over the {MAX_FIXTURE_BYTES}-byte limit for one fixture file",
183                bytes.len()
184            ),
185        ));
186    }
187    crate::embeds::embedded_text(&bytes).map_err(|code| {
188        if code == "bynk.embed.invalid_encoding" {
189            (
190                "bynk.fixture.invalid_encoding",
191                "it is not valid UTF-8".to_string(),
192            )
193        } else {
194            (
195                "bynk.fixture.binary_content",
196                "it contains a NUL byte, so it is a binary file".to_string(),
197            )
198        }
199    })
200}
201
202fn refusal_error(code: &'static str, f: &FixtureDecl, key: &str, detail: &str) -> CompileError {
203    let what = match code {
204        "bynk.fixture.unreadable_file" => "could not be read",
205        "bynk.fixture.invalid_encoding" => "is not UTF-8 text",
206        "bynk.fixture.binary_content" => "is not text",
207        "bynk.fixture.too_large" => "is too large for a fixture",
208        other => unreachable!("`{other}` is not a fixture refusal code"),
209    };
210    CompileError::new(
211        code,
212        f.path_span,
213        format!("fixture `{}` names `{key}`, which {what}", f.name.name),
214    )
215    .with_note(detail.to_string())
216    .with_note("a fixture is a `String`; read a binary file another way")
217}
218
219/// The name rules and the unused warning for one suite's fixtures.
220///
221/// `taken` is every value name in the suite's case scope (its view's, with the
222/// target's services and agents; see `test_suites::bound_value_names`): a
223/// fixture of the same name is `bynk.resolve.name_conflict`, as an embed's is.
224/// A repeated fixture name is `bynk.fixture.duplicate`, and a name a helper
225/// `fn` of the suite declares is the helper's `bynk.suite.fn_name_clash`. A fixture no `case`,
226/// `property`, helper, `stub` or `env` entry mentions is `bynk.fixture.unused`,
227/// a warning.
228pub fn check_suite_fixtures(
229    suite: &SuiteDecl,
230    taken: &HashSet<String>,
231    errors: &mut Vec<CompileError>,
232) {
233    let mut seen: BTreeMap<&str, &FixtureDecl> = BTreeMap::new();
234    for f in &suite.fixtures {
235        let name = f.name.name.as_str();
236        if let Some(prev) = seen.get(name) {
237            errors.push(
238                CompileError::new(
239                    "bynk.fixture.duplicate",
240                    f.name.span,
241                    format!("fixture `{name}` is already declared"),
242                )
243                .with_label(prev.name.span, "previously declared here"),
244            );
245            continue;
246        }
247        seen.insert(name, f);
248        if taken.contains(name) || name.starts_with("__") || name == "deps" {
249            errors.push(CompileError::new(
250                "bynk.resolve.name_conflict",
251                f.name.span,
252                format!("fixture `{name}` conflicts with a declaration of the same name in this suite's scope"),
253            ));
254        }
255    }
256    if suite.fixtures.is_empty() {
257        return;
258    }
259    let mut mentioned: HashSet<&str> = HashSet::new();
260    for c in &suite.cases {
261        collect_idents(&c.body, &mut mentioned);
262    }
263    for p in &suite.properties {
264        if let Some(w) = &p.forall.where_pred {
265            collect_expr_idents(w, &mut mentioned);
266        }
267        collect_idents(&p.forall.body, &mut mentioned);
268    }
269    for f in &suite.fns {
270        collect_idents(&f.body, &mut mentioned);
271    }
272    // #2850: a stub's argument patterns, values and `after` may name one too.
273    let stubs = suite
274        .stubs
275        .iter()
276        .chain(suite.cases.iter().flat_map(|c| c.stubs.iter()));
277    for st in stubs {
278        for a in &st.args {
279            if let ArgPattern::Value(e) = a {
280                collect_expr_idents(e, &mut mentioned);
281            }
282        }
283        match &st.rhs {
284            StubRhs::Returns(e) => collect_expr_idents(e, &mut mentioned),
285            StubRhs::ReturnsEach(outcomes, _) => {
286                for o in outcomes {
287                    if let SeqOutcome::Value(e) = o {
288                        collect_expr_idents(e, &mut mentioned);
289                    }
290                }
291            }
292            StubRhs::Fails(_) | StubRhs::Never(_) => {}
293        }
294        if let Some(a) = &st.after {
295            collect_expr_idents(a, &mut mentioned);
296        }
297    }
298    // #2956: and an `env` entry's value, the suite's or a case's.
299    let envs = suite
300        .envs
301        .iter()
302        .chain(suite.cases.iter().flat_map(|c| c.envs.iter()));
303    for entry in envs.flat_map(|e| e.entries.iter()) {
304        collect_expr_idents(&entry.value, &mut mentioned);
305    }
306    for f in &suite.fixtures {
307        if !mentioned.contains(f.name.name.as_str()) {
308            errors.push(CompileError::new(
309                "bynk.fixture.unused",
310                f.name.span,
311                format!("fixture `{}` is never used in this suite", f.name.name),
312            ));
313        }
314    }
315}
316
317fn collect_idents<'a>(b: &'a Block, out: &mut HashSet<&'a str>) {
318    let mut roots = Vec::new();
319    for s in &b.statements {
320        statement_exprs(s, &mut roots);
321    }
322    roots.push(&b.tail);
323    for e in roots {
324        collect_expr_idents(e, out);
325    }
326}
327
328fn collect_expr_idents<'a>(e: &'a bynk_syntax::ast::Expr, out: &mut HashSet<&'a str>) {
329    if let ExprKind::Ident(id) = &e.kind {
330        out.insert(id.name.as_str());
331    }
332    if let ExprKind::Block(b) = &e.kind {
333        collect_idents(b, out);
334    }
335    for c in expr_children(e) {
336        collect_expr_idents(c, out);
337    }
338}