bynk_driver/project/in_memory.rs
1use super::diagnostics::Mode;
2use super::diagnostics::ProjectFailure;
3use super::output::finish_build;
4use super::pipeline::RunChecks;
5use super::pipeline::run_checks;
6use bynk_check::project_model::BuildTarget;
7use bynk_emit::emit_model::ImportExt;
8use bynk_emit::emit_model::ProjectOutput;
9use bynk_emit::emit_model::RemoteTests;
10use bynk_project::AttributedError;
11use bynk_project::LabelFile;
12use bynk_project::SchemaLock;
13use bynk_project::assets;
14use std::collections::HashMap;
15use std::path::{Component, Path, PathBuf};
16use std::sync::Arc;
17
18use bynk_check::checker::{TyId, Types};
19use bynk_check::firstparty::Platform;
20use bynk_syntax::lexer;
21use bynk_syntax::parser;
22
23/// Compile a single **in-memory** Bynk source through the full project pipeline —
24/// no filesystem access (in-browser track, slice 3). The source is the in-process
25/// `Bundle` subset that `consumes bynk`; first-party injection and the per-platform
26/// binding emission run exactly as for an on-disk build, so the returned
27/// [`ProjectOutput`] is the complete module graph (the user unit + `runtime.ts` +
28/// the `bynk-<platform>.ts` binding + `compose.ts`). The wasm entry point pairs
29/// this with `bynk-strip` to produce JavaScript for the playground.
30///
31/// The module's logical path is **derived from its declared unit name** (a context
32/// `app.demo` ⇒ `app/demo.bynk`), so the name↔path alignment check passes without
33/// real files; a source that does not parse falls back to `main.bynk` and the parse
34/// error is reported normally.
35pub fn compile_in_memory(
36 source: &str,
37 target: BuildTarget,
38 platform: Platform,
39) -> Result<ProjectOutput, ProjectFailure> {
40 // T3.6b (R4.1): one table for this virtual project's compile.
41 let tys = &Arc::new(Types::new());
42 // A single-tree (`src_root == tests_root`) virtual project rooted at `.`: the
43 // one source file is supplied directly and its text layered in via the
44 // overlay, so discovery and every other disk read are bypassed.
45 let root = PathBuf::from(".");
46 let path = in_memory_logical_path(source);
47 let mut overlay = HashMap::new();
48 overlay.insert(path.clone(), source.to_string());
49 let trees = vec![(root.clone(), PathBuf::new())];
50 let run = run_checks(
51 &trees,
52 target,
53 platform,
54 ImportExt::Js,
55 Mode::Build,
56 &overlay,
57 &[],
58 Some(vec![vec![path]]),
59 false,
60 false,
61 false,
62 true,
63 &SchemaLock::Off,
64 None,
65 &root,
66 None,
67 None,
68 None,
69 None,
70 None,
71 false,
72 tys,
73 None,
74 );
75 finish_build(run, ImportExt::Js, Path::new(""), &[], None, None, None)
76}
77
78/// [`compile_in_memory`] for several files (#1830): each `(path, source)` pair
79/// is one project file, its path relative to a single-tree root exactly as on
80/// disk (`demo/shop.bynk` for `context demo.shop`, `tests/shop.bynk` for a
81/// suite). Test-only, so a unit test can build a multi-unit project, or a
82/// unit with its suite, without a fixture directory; reach it through
83/// `crate::testkit`. `tests` keeps the suites, as `bynk test` does; off is
84/// the deployable build `bynk compile` makes.
85#[doc(hidden)] // test support: `bynk-emit`'s tests drive the pipeline through it
86pub fn compile_files_in_memory(
87 files: &[(&str, &str)],
88 target: BuildTarget,
89 platform: Platform,
90 tests: bool,
91) -> Result<ProjectOutput, ProjectFailure> {
92 compile_files_in_memory_remote(files, target, platform, tests, None, None)
93}
94
95/// [`compile_files_in_memory`] as a remote test build (#2138,
96/// [`CompileOptions::remote_tests`]).
97#[doc(hidden)] // test support: `bynk-emit`'s tests drive the pipeline through it
98pub fn compile_files_in_memory_remote(
99 files: &[(&str, &str)],
100 target: BuildTarget,
101 platform: Platform,
102 tests: bool,
103 remote: Option<&RemoteTests>,
104 asset_files: Option<&assets::AssetFolder>,
105) -> Result<ProjectOutput, ProjectFailure> {
106 compile_files_in_memory_locked(files, target, platform, tests, remote, asset_files, None)
107}
108
109/// [`compile_files_in_memory_remote`] with a pre-read `bynk.contracts.lock`
110/// (#2554, [`CompileOptions::contracts_lock`]).
111#[doc(hidden)] // test support: `bynk-emit`'s tests drive the pipeline through it
112pub fn compile_files_in_memory_locked(
113 files: &[(&str, &str)],
114 target: BuildTarget,
115 platform: Platform,
116 tests: bool,
117 remote: Option<&RemoteTests>,
118 asset_files: Option<&assets::AssetFolder>,
119 contracts_lock: Option<&str>,
120) -> Result<ProjectOutput, ProjectFailure> {
121 let tys = &Arc::new(Types::new());
122 let root = PathBuf::from(".");
123 let paths: Vec<PathBuf> = files.iter().map(|(p, _)| PathBuf::from(p)).collect();
124 let overlay: HashMap<PathBuf, String> = files
125 .iter()
126 .map(|(p, src)| (PathBuf::from(p), (*src).to_string()))
127 .collect();
128 let trees = vec![(root.clone(), PathBuf::new())];
129 let run = run_checks(
130 &trees,
131 target,
132 platform,
133 ImportExt::Js,
134 Mode::Build,
135 &overlay,
136 &[],
137 Some(vec![paths]),
138 false,
139 false,
140 false,
141 tests,
142 &SchemaLock::Off,
143 remote,
144 &root,
145 asset_files,
146 None,
147 None,
148 None,
149 None,
150 false,
151 tys,
152 None,
153 );
154 finish_build(
155 run,
156 ImportExt::Js,
157 Path::new(""),
158 &[],
159 None,
160 None,
161 contracts_lock,
162 )
163}
164
165/// Analyse a single **in-memory** Bynk source and return all diagnostics —
166/// non-bailing, no emission (in-browser track, slice 5d). The editor calls this
167/// on every (debounced) keystroke for live diagnostics: unlike [`compile_in_memory`]
168/// (build mode, which bails at the first failing phase), this runs in `Analyse`
169/// mode, so parse / resolve / check diagnostics are recovered and reported together
170/// — and it works for a `context` (the playground's typical program), not only a
171/// commons. Same fs-free seam as `compile_in_memory`.
172pub fn analyse_in_memory(
173 source: &str,
174 target: BuildTarget,
175 platform: Platform,
176) -> Vec<AttributedError> {
177 analyse_in_memory_with_types(source, target, platform).errors
178}
179
180/// The outcome of [`analyse_in_memory_with_types`]: diagnostics plus the
181/// analysed file's `(span, type)` entries (span-sorted — see
182/// [`ExprTypeSink::take_files`](bynk_check::expr_types::ExprTypeSink::take_files)), for a position→type query (#397, the
183/// playground's hover), and its local bindings (#808, the playground's
184/// completion — `bynk_check::locals::locals_at` over `locals` answers
185/// "what's in scope at this offset").
186pub struct InMemoryAnalysis {
187 pub errors: Vec<AttributedError>,
188 pub expr_types: Vec<(bynk_syntax::span::Span, TyId)>,
189 /// T3.6b (R4.1): the table `expr_types`' ids resolve against.
190 pub ty_intern: std::sync::Arc<bynk_check::checker::Types>,
191 pub locals: Vec<bynk_check::locals::LocalBinding>,
192}
193
194/// Like [`analyse_in_memory`], but also exposes the expression-type map the
195/// checker captured (ADR 0063's `expr_types` sink) — the same one
196/// `bynk_check::analysis::analyse_project` drains — instead of discarding it. Per ADR 0094,
197/// this is a best-effort **partial** map in `Analyse` mode: a function that
198/// type-checked cleanly contributes its types even if a *different* function
199/// in the same file has an error, so `expr_types` is empty only when the
200/// expression at hand never typed at all (e.g. it sits in an unresolved
201/// region, ADR 0094's "out of scope — the resolve gate"), not merely because
202/// the file has some error somewhere.
203pub fn analyse_in_memory_with_types(
204 source: &str,
205 target: BuildTarget,
206 platform: Platform,
207) -> InMemoryAnalysis {
208 // T3.6b (R4.1): one table for the whole analysis — every unit it checks
209 // interns into this, so the `TyId`s it hands back on `InMemoryAnalysis`
210 // all resolve against the one table it also hands back.
211 let tys = &Arc::new(Types::new());
212 let root = PathBuf::from(".");
213 let path = in_memory_logical_path(source);
214 let mut overlay = HashMap::new();
215 overlay.insert(path.clone(), source.to_string());
216 let trees = vec![(root.clone(), PathBuf::new())];
217 let run = run_checks(
218 &trees,
219 target,
220 platform,
221 ImportExt::Js,
222 Mode::Analyse,
223 &overlay,
224 &[],
225 Some(vec![vec![path.clone()]]),
226 false,
227 false,
228 false,
229 true,
230 &SchemaLock::Off,
231 None,
232 &root,
233 None,
234 None,
235 None,
236 None,
237 None,
238 false,
239 tys,
240 None,
241 );
242 match run {
243 RunChecks::Bailed {
244 errors,
245 mut exprs,
246 mut locals,
247 ..
248 }
249 | RunChecks::Checked {
250 errors,
251 mut exprs,
252 mut locals,
253 ..
254 } => InMemoryAnalysis {
255 errors: errors.into_all(),
256 expr_types: exprs.take_files().remove(&path).unwrap_or_default(),
257 ty_intern: Arc::clone(tys),
258 locals: locals.take_files().remove(&path).unwrap_or_default(),
259 },
260 }
261}
262
263/// The outcome of [`analyse_in_memory_project`]: every file's diagnostics,
264/// plus each `.bynk` file's expression types and local bindings keyed by its
265/// project-relative path, for a position→type query in any of them.
266pub struct InMemoryProjectAnalysis {
267 pub errors: Vec<AttributedError>,
268 pub expr_types: HashMap<PathBuf, Vec<(bynk_syntax::span::Span, TyId)>>,
269 /// The table every file's `expr_types` ids resolve against.
270 pub ty_intern: std::sync::Arc<bynk_check::checker::Types>,
271 pub locals: HashMap<PathBuf, Vec<bynk_check::locals::LocalBinding>>,
272 /// `bynk.toml` `[paths]` entries that were ignored, as `(key, entry)`
273 /// (`("include", "/abs/src")`): an absolute `include` or `exclude` can't
274 /// name anything in an in-memory project, so rather than silently matching
275 /// nothing it is reported here for the caller to surface. Plain data, not a
276 /// message: wording is the caller's.
277 pub ignored_paths: Vec<(String, String)>,
278}
279
280/// #2102 slice 2: analyse a whole project held in memory, for the VS Code web
281/// extension, which reads the workspace through `vscode.workspace.fs` and has
282/// no filesystem to hand `run_checks`.
283///
284/// `files` maps **project-relative** paths to their text: `bynk.toml` (when the
285/// project has one) and every `.bynk` file, at the paths they have on disk
286/// (`src/app/web.bynk`). The project root is the empty path, so every path
287/// stays relative, in the diagnostics too. `[paths] include`/`exclude` come
288/// from the in-memory `bynk.toml`. With no `include`, the conventional layout
289/// is decided from the files themselves (`src`, `tests`, else the root) rather
290/// than [`ProjectPaths::conventional`](bynk_project::ProjectPaths::conventional)'s disk probe. Non-`.bynk` entries other
291/// than `bynk.toml` are ignored. Pure: no filesystem.
292pub fn analyse_in_memory_project(
293 files: &HashMap<PathBuf, String>,
294 target: BuildTarget,
295 platform: Platform,
296) -> InMemoryProjectAnalysis {
297 let tys = &Arc::new(Types::new());
298 let project_root = PathBuf::new();
299 // Keys are `/`-separated whatever the caller's platform spelling.
300 let files: &HashMap<PathBuf, String> = &files
301 .iter()
302 .map(|(path, text)| (slash_key(path), text.clone()))
303 .collect();
304 let (include, exclude, ignored_paths) = in_memory_project_paths(files);
305
306 // One tree per distinct include, with its prefix (`.` is the empty one —
307 // see `Roots::trees`). Built here rather than through `Roots` so a `.`
308 // root stays the empty path, which every relative key starts with.
309 let mut trees: Vec<(PathBuf, PathBuf)> = Vec::new();
310 for root in include {
311 if !trees.iter().any(|(r, _)| *r == root) {
312 trees.push((root.clone(), root));
313 }
314 }
315 let mut excludes: Vec<PathBuf> = exclude;
316 excludes.extend(["out", "node_modules"].map(PathBuf::from));
317
318 let mut buckets: Vec<Vec<PathBuf>> = vec![Vec::new(); trees.len()];
319 let mut keys: Vec<&PathBuf> = files
320 .keys()
321 .filter(|p| p.extension().is_some_and(|e| e == "bynk"))
322 .filter(|p| !excludes.iter().any(|ex| p.starts_with(ex)))
323 .collect();
324 keys.sort();
325 for p in keys {
326 if let Some(idx) = trees.iter().position(|(root, _)| p.starts_with(root)) {
327 buckets[idx].push(p.clone());
328 }
329 }
330
331 let run = run_checks(
332 &trees,
333 target,
334 platform,
335 ImportExt::Js,
336 Mode::Analyse,
337 files,
338 &[],
339 Some(buckets),
340 false,
341 false,
342 false,
343 true,
344 &SchemaLock::Off,
345 None,
346 &project_root,
347 None,
348 None,
349 None,
350 None,
351 None,
352 false,
353 tys,
354 None,
355 );
356 match run {
357 RunChecks::Bailed {
358 errors,
359 mut exprs,
360 mut locals,
361 ..
362 }
363 | RunChecks::Checked {
364 errors,
365 mut exprs,
366 mut locals,
367 ..
368 } => InMemoryProjectAnalysis {
369 errors: errors
370 .into_all()
371 .into_iter()
372 .map(|mut e| {
373 e.source_path = e.source_path.as_deref().map(slash_key);
374 for label in &mut e.label_files {
375 if let LabelFile::Other(p) = label {
376 *p = slash_key(p);
377 }
378 }
379 e
380 })
381 .collect(),
382 expr_types: exprs
383 .take_files()
384 .into_iter()
385 .map(|(p, v)| (slash_key(&p), v))
386 .collect(),
387 ty_intern: Arc::clone(tys),
388 locals: locals
389 .take_files()
390 .into_iter()
391 .map(|(p, v)| (slash_key(&p), v))
392 .collect(),
393 ignored_paths,
394 },
395 }
396}
397
398/// A path as an in-memory project key: its components joined with `/`.
399///
400/// [`analyse_in_memory_project`]'s keys are `/`-separated on every platform
401/// (they come from the web extension, which speaks URIs). The project model
402/// builds identity paths with `PathBuf::join`, which inserts `\` on Windows
403/// (`src` + `app/web.bynk` is `src\app/web.bynk` there), so every path
404/// handed back is rebuilt this way, and keys taken in are too. On Unix a `\`
405/// is an ordinary file-name character, not a separator, and is kept.
406pub fn slash_key(path: &Path) -> PathBuf {
407 let parts: Vec<String> = path
408 .components()
409 .filter(|c| !matches!(c, Component::CurDir))
410 .map(|c| c.as_os_str().to_string_lossy().into_owned())
411 .collect();
412 PathBuf::from(parts.join("/"))
413}
414
415/// The `[paths]` `include` and `exclude` lists of an in-memory project (see
416/// [`analyse_in_memory_project`]). An absent or unreadable `bynk.toml`, or one
417/// with no `include`, gets the conventional layout, judged by which of `src/`
418/// and `tests/` hold a `.bynk` file. Entries are normalised with [`slash_key`],
419/// so `./src` is `src` and the root (`.`) is the empty path. An absolute entry
420/// is dropped and described in the third list (an `include` left empty by that
421/// falls back to the conventional layout).
422type IgnoredPaths = Vec<(String, String)>;
423
424fn in_memory_project_paths(
425 files: &HashMap<PathBuf, String>,
426) -> (Vec<PathBuf>, Vec<PathBuf>, IgnoredPaths) {
427 let doc = files
428 .get(Path::new("bynk.toml"))
429 .and_then(|text| text.parse::<toml::Table>().ok());
430 let paths = doc
431 .as_ref()
432 .and_then(|d| d.get("paths"))
433 .and_then(|v| v.as_table());
434 // Each entry is normalised like the file keys (`./src` is `src`), so it
435 // prefixes them. The project root itself (`.`, `./`) normalises to the
436 // empty path, which prefixes every key.
437 let mut ignored = Vec::new();
438 let mut list = |key: &str| -> Vec<PathBuf> {
439 let entries: Vec<&str> = match paths.and_then(|t| t.get(key)) {
440 Some(toml::Value::Array(items)) => items.iter().filter_map(|v| v.as_str()).collect(),
441 Some(toml::Value::String(s)) => vec![s.as_str()],
442 _ => Vec::new(),
443 };
444 let mut kept = Vec::new();
445 for entry in entries {
446 if is_absolute_entry(entry) {
447 ignored.push((key.to_string(), entry.to_string()));
448 } else {
449 kept.push(slash_key(Path::new(entry)));
450 }
451 }
452 kept
453 };
454 let mut include = list("include");
455 let exclude = list("exclude");
456 if include.is_empty() {
457 let has = |dir: &str| {
458 files
459 .keys()
460 .any(|p| p.starts_with(dir) && p.extension().is_some_and(|e| e == "bynk"))
461 };
462 include = ["src", "tests"]
463 .into_iter()
464 .filter(|d| has(d))
465 .map(PathBuf::from)
466 .collect();
467 if include.is_empty() {
468 include.push(PathBuf::new());
469 }
470 }
471 (include, exclude, ignored)
472}
473
474/// Whether a `[paths]` entry is absolute on any platform: rooted (`/src`,
475/// `\\src`) or with a drive (`C:/src`), whatever the host's own path rules.
476fn is_absolute_entry(entry: &str) -> bool {
477 let bytes = entry.as_bytes();
478 entry.starts_with('/')
479 || entry.starts_with('\\')
480 || (bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':')
481 || Path::new(entry).has_root()
482}
483
484/// Derive the conventional single-file path for an in-memory source from its
485/// declared unit name (`app.demo` ⇒ `app/demo.bynk`), so `check_path_name_alignment`
486/// is satisfied without a real file tree. Falls back to `main.bynk` when the source
487/// does not parse — `run_checks` then re-parses and reports the error against it.
488fn in_memory_logical_path(source: &str) -> PathBuf {
489 let parts: Option<Vec<String>> = lexer::tokenize(source)
490 .ok()
491 .and_then(|tokens| parser::parse_unit(&tokens, source).ok())
492 .map(|unit| unit.name().parts.iter().map(|i| i.name.clone()).collect());
493 match parts {
494 Some(p) if !p.is_empty() => {
495 let mut path = PathBuf::from(p.join("/"));
496 path.set_extension("bynk");
497 path
498 }
499 _ => PathBuf::from("main.bynk"),
500 }
501}
502
503// -- internals --
504
505#[allow(dead_code)]
506fn _ensure_components_used(_p: &Path) {
507 let _ = Component::CurDir;
508}