1pub 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#[derive(serde::Serialize, Clone, Copy, PartialEq, Eq, Debug)]
45#[serde(rename_all = "lowercase")]
46pub enum FileKind {
47 User,
49 Wiring,
51 Support,
54}
55
56#[derive(serde::Serialize)]
58pub struct EmittedFile {
59 pub kind: FileKind,
61 pub path: String,
63 pub contents: String,
65 #[serde(skip_serializing_if = "Option::is_none")]
71 pub map: Option<String>,
72}
73
74fn with_source_name(map: &str, name: &str) -> Option<String> {
78 let mut v: serde_json::Value = serde_json::from_str(map).ok()?;
79 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#[derive(serde::Serialize)]
89pub struct Diagnostic {
90 pub path: Option<String>,
92 pub line: usize,
93 pub col: usize,
94 pub from: usize,
96 pub to: usize,
97 pub severity: String,
99 pub category: String,
101 pub message: String,
102 pub summary: Option<String>,
105 pub href: String,
110 pub notes: Vec<String>,
116 pub labels: Vec<String>,
117}
118
119#[derive(serde::Serialize)]
121pub struct CompileResult {
122 pub ok: bool,
124 pub files: Vec<EmittedFile>,
126 pub diagnostics: Vec<Diagnostic>,
128 pub entries: Vec<Entry>,
132}
133
134#[derive(serde::Serialize)]
136pub struct Entry {
137 pub unit: String,
139 pub service: String,
140 pub params: Vec<EntryParam>,
141 pub returns: String,
143}
144
145#[derive(serde::Serialize)]
147pub struct EntryParam {
148 pub name: String,
149 #[serde(rename = "type")]
151 pub ty: String,
152 pub base: Option<&'static str>,
155 pub refined: bool,
158 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
239fn 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
250fn 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#[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
292fn summary_of(code: &str) -> Option<String> {
294 bynk_syntax::diagnostics::lookup(code).map(|d| d.summary.to_string())
295}
296
297#[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
312pub 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
325pub 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
335fn 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
372pub 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 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 let diagnostics = to_diagnostics(js.warnings, &HashMap::new(), source);
406 let entries = to_entries(js.entry_handlers);
407 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 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 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
479pub 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#[derive(serde::Serialize)]
492#[serde(untagged)]
493pub enum FormatResult {
494 Ok { ok: bool, formatted: String },
495 Err { ok: bool, error: String },
496}
497
498pub 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 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
527pub 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#[derive(serde::Serialize)]
536pub struct AnalyzeResult {
537 pub diagnostics: Vec<Diagnostic>,
538}
539
540pub 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
554pub 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#[derive(serde::Serialize)]
568pub struct HoverResult {
569 pub ty: Option<String>,
570}
571
572pub 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
584pub 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#[derive(serde::Serialize)]
594pub struct CompletionCandidate {
595 pub label: String,
596 pub kind: &'static str,
599 pub detail: Option<String>,
600 pub insert_text: Option<String>,
601}
602
603#[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
633pub 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
653struct 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
671fn 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 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 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
725pub 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
731pub 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#[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 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
790fn 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
804pub 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
822pub fn complete_project(
826 files: &HashMap<PathBuf, String>,
827 path: &str,
828 offset: usize,
829 platform: Platform,
830) -> CompleteResult {
831 catch_panic(|| {
832 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
856pub 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#[cfg(target_arch = "wasm32")]
879fn install_panic_hook() {
880 console_error_panic_hook::set_once();
881}
882
883#[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#[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#[cfg(target_arch = "wasm32")]
911#[wasm_bindgen]
912pub fn bynk_reference() -> String {
913 install_panic_hook();
914 reference::reference_to_json()
915}
916
917#[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#[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#[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#[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#[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#[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#[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 #[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 #[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 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 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 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 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 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 assert!(r.diagnostics.iter().any(|d| d.line >= 1));
1188 }
1189
1190 #[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 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 #[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 #[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 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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[test]
1735 fn project_paths_are_slash_separated_on_every_platform() {
1736 let misuse = WEB.replace("greeting(\"World\")", "greeting(1)");
1737 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 assert!(d.line > 1, "line/col from web.bynk: {}", d.line);
1754 }
1755 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 #[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 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 let tag = ¶ms[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 let n = ¶ms[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 let pts = ¶ms[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 let shape = ¶ms[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 let next = ¶ms[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 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 = ¶ms[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 assert_eq!(params[1]["shape"]["kind"], "record");
1963 }
1964
1965 #[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 #[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 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}