1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
32use std::path::{Path, PathBuf};
33use std::sync::{Arc, OnceLock};
34
35use crate::checker::{self, Ty, TyId, Types};
36use crate::context_checks::{
37 CAPABILITY_SIGNATURE, RECORD_FIELD, REQUEST_RECORD_PARAM, SUM_PAYLOAD,
38 build_capability_op_info, reject_fn_types, ts_type_ref_display, type_ref_is_held,
39 type_ref_to_display, validate_store_field_value_types,
40};
41use crate::firstparty::{self, Platform};
42use crate::icu;
43use crate::index::{RefSink, SymbolKind};
44use crate::resolver::MethodTable as ResolverMethodTable;
45use crate::symbols::{
46 ConsumedType, ContextMessageBundle, FileDeclIndex, UnitTable, build_file_decl_index,
47 build_unit_table, consumes_span_of, detect_context_message_bundle, parsed_alias_span,
48 uses_span_of,
49};
50use bynk_project::{
51 AttributedError, LabelFile, ParsedFile, UnitKind, check_directory_kind_consistency,
52 check_directory_name_consistency, check_file_directory_conflicts, check_group_kind_consistency,
53 check_group_module_docs, check_path_name_alignment, detect_consumes_cycles,
54 discover_bynk_files, is_unpinned_range, normalize_rel, parse_sources, parse_sources_recovering,
55 read_adapter_binding, read_adapter_include, read_source,
56};
57use bynk_syntax::ast::*;
58pub use bynk_syntax::ast::{FnDecl, TypeDecl, Visibility};
66use bynk_syntax::error::CompileError;
67use bynk_syntax::lexer;
68use bynk_syntax::parser;
69use bynk_syntax::span::{FileId, Span};
70
71#[derive(Clone)]
83pub struct ErrorSink {
84 entries: Vec<AttributedError>,
85 warnings: Vec<AttributedError>,
90 files: HashMap<FileId, PathBuf>,
94 cookie_sources: Vec<(FileId, Arc<str>)>,
98 cookie_key: Vec<(usize, usize)>,
101}
102
103impl Default for ErrorSink {
104 fn default() -> Self {
105 Self::new()
106 }
107}
108
109impl ErrorSink {
110 pub fn new() -> Self {
111 Self {
112 entries: Vec::new(),
113 warnings: Vec::new(),
114 files: HashMap::new(),
115 cookie_sources: Vec::new(),
116 cookie_key: Vec::new(),
117 }
118 }
119 pub fn register_file(&mut self, file: FileId, identity: PathBuf) {
121 self.files.insert(file, identity);
122 }
123 pub fn register_parsed(&mut self, parsed: &[ParsedFile]) {
130 let key: Vec<(usize, usize)> = parsed
131 .iter()
132 .map(|pf| (pf.source().as_ptr() as usize, pf.source().len()))
133 .collect();
134 if key != self.cookie_key {
135 self.cookie_key = key;
136 self.cookie_sources = Self::cookie_sources_of(parsed);
137 }
138 self.register_files(parsed);
139 }
140 fn cookie_sources_of(parsed: &[ParsedFile]) -> Vec<(FileId, Arc<str>)> {
142 if parsed.iter().any(|pf| pf.source().contains("SignedCookie")) {
143 parsed
144 .iter()
145 .filter_map(|pf| {
146 let id = bynk_project::parse_cache::file_id_for(&pf.abs_path()?);
147 Some((id, Arc::from(pf.source())))
148 })
149 .collect()
150 } else {
151 Vec::new()
152 }
153 }
154 fn register_files(&mut self, parsed: &[ParsedFile]) {
155 for pf in parsed {
156 if let Some(abs) = pf.abs_path() {
157 self.register_file(
158 bynk_project::parse_cache::file_id_for(&abs),
159 pf.identity_path(),
160 );
161 }
162 }
163 }
164 pub fn push_for(&mut self, file: Option<&Path>, mut error: CompileError) {
165 display_canonical_names(&mut error);
168 let attributed = AttributedError::new(file.map(Path::to_path_buf), error);
169 match bynk_syntax::Severity::for_error(&attributed.error) {
170 bynk_syntax::Severity::Warning | bynk_syntax::Severity::Hint => {
171 self.warnings.push(attributed)
172 }
173 bynk_syntax::Severity::Error => self.entries.push(attributed),
174 }
175 }
176 pub fn extend_for(
177 &mut self,
178 file: Option<&Path>,
179 errs: impl IntoIterator<Item = CompileError>,
180 ) {
181 for e in errs {
182 self.push_for(file, e);
183 }
184 }
185 pub fn extend_attributed_by_span(
196 &mut self,
197 parsed: &[ParsedFile],
198 errs: impl IntoIterator<Item = CompileError>,
199 ) {
200 self.register_parsed(parsed);
201 self.extend_attributed(errs);
202 }
203 pub fn extend_attributed(&mut self, errs: impl IntoIterator<Item = CompileError>) {
209 for e in errs {
210 let file = self.files.get(&e.span.file).cloned();
211 self.push_for(file.as_deref(), e);
212 }
213 }
214 pub fn absorb(&mut self, other: ErrorSink) {
218 self.entries.extend(other.entries);
219 self.warnings.extend(other.warnings);
220 }
221 pub fn is_empty(&self) -> bool {
224 self.entries.is_empty()
225 }
226 pub fn into_warnings(self) -> Vec<AttributedError> {
228 let mut warnings = self.warnings;
229 attach_cookie_rename_fix(&self.cookie_sources, &mut warnings);
230 attribute_labels(&self.files, &mut warnings);
231 warnings
232 }
233 pub fn into_all(self) -> Vec<AttributedError> {
236 let mut all = self.entries;
237 all.extend(self.warnings);
238 attach_cookie_rename_fix(&self.cookie_sources, &mut all);
239 attribute_labels(&self.files, &mut all);
240 all
241 }
242 pub fn len(&self) -> usize {
244 self.entries.len()
245 }
246}
247
248fn attach_cookie_rename_fix(sources: &[(FileId, Arc<str>)], errors: &mut [AttributedError]) {
256 for ae in errors {
257 let e = &mut ae.error;
258 if e.category != "bynk.actor.signed_cookie_unprefixed" || !e.suggestions.is_empty() {
259 continue;
260 }
261 let Some((_, text)) = sources.iter().find(|(id, _)| *id == e.span.file) else {
262 continue;
263 };
264 let Some(literal) = text.get(e.span.range()) else {
265 continue;
266 };
267 let name = match literal.strip_prefix('"').and_then(|l| l.strip_suffix('"')) {
268 Some(n) if !n.is_empty() && !n.contains(['\\', '"']) => n,
269 _ => continue,
270 };
271 let mentions: usize = sources
272 .iter()
273 .map(|(_, t)| t.matches(literal).count())
274 .sum();
275 if mentions != 1 {
276 continue;
277 }
278 let base = match name.get(..9) {
280 Some(p) if p.eq_ignore_ascii_case("__Secure-") => &name[9..],
281 _ => name,
282 };
283 if base.is_empty() {
284 continue;
285 }
286 e.suggestions.push(bynk_syntax::error::Suggestion {
287 message: format!(
288 "rename the cookie to `__Host-{base}` (no other site in the project names `{name}`; existing users are logged out when the name changes)"
289 ),
290 edits: vec![(e.span, format!("\"__Host-{base}\""))],
291 applicability: bynk_syntax::error::Applicability::MaybeIncorrect,
292 });
293 }
294}
295
296fn attribute_labels(files: &HashMap<FileId, PathBuf>, errors: &mut [AttributedError]) {
306 for ae in errors {
307 let primary = ae.error.span.file;
308 ae.label_files = ae
309 .error
310 .labels
311 .iter()
312 .map(|(span, _)| {
313 if span.file == primary || span.file == FileId::UNKNOWN {
314 return LabelFile::Primary;
315 }
316 match files.get(&span.file) {
317 Some(path) if Some(path) == ae.source_path.as_ref() => LabelFile::Primary,
318 Some(path) => LabelFile::Other(path.clone()),
319 None => match firstparty_unit_for(span.file) {
320 Some(unit) => LabelFile::FirstParty {
321 identity_path: unit.identity_path,
322 source: unit.source,
323 },
324 None => LabelFile::Unavailable,
325 },
326 }
327 })
328 .collect();
329 }
330}
331
332pub struct AdapterBinding {
337 pub output_path: PathBuf,
339 pub content: String,
341 pub includes: Vec<IncludedFile>,
343}
344
345#[derive(Clone)]
347pub struct IncludedFile {
348 pub output_path: PathBuf,
350 pub bytes: Vec<u8>,
351}
352
353#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
359pub enum BuildTarget {
360 #[default]
363 Bundle,
364 Workers,
368}
369
370pub fn normalize_service_defaults(parsed: &mut [ParsedFile]) {
371 for pf in parsed.iter_mut() {
372 let items = match pf.unit_mut() {
373 SourceUnit::Commons(c) => &mut c.items,
374 SourceUnit::Context(c) => &mut c.items,
375 SourceUnit::Adapter(a) => &mut a.items,
376 SourceUnit::Suite(_) => continue,
377 };
378 for item in items.iter_mut() {
379 if let CommonsItem::Service(svc) = item {
380 inject_service_defaults(svc);
381 }
382 }
383 }
384}
385
386pub fn inject_service_defaults(svc: &mut ServiceDecl) {
391 let default_by = svc.default_by.clone();
392 let default_given = svc.default_given.clone();
393 if default_by.is_none() && default_given.is_empty() {
394 return;
395 }
396 for handler in svc.handlers.iter_mut() {
397 if handler.kind == HandlerKind::Rejected {
400 continue;
401 }
402 if handler.by_clause.is_none()
403 && let Some(def) = &default_by
404 {
405 handler.by_clause = Some(def.clone());
406 }
407 if handler.given.is_empty() && !default_given.is_empty() {
408 handler.given = default_given.clone();
409 }
410 }
411}
412
413#[allow(clippy::result_unit_err)]
431pub fn phase_discovery(
432 trees: &[(PathBuf, PathBuf)],
433 excludes: &[PathBuf],
434 errors: &mut ErrorSink,
435) -> Result<Vec<Vec<PathBuf>>, ()> {
436 let mut out = Vec::with_capacity(trees.len());
437 for (i, (root, _prefix)) in trees.iter().enumerate() {
438 match discover_bynk_files(root, excludes) {
439 Ok(f) => out.push(f),
440 Err(e) if i > 0 && e.category == "bynk.project.no_root" => {
446 out.push(Vec::new());
447 }
448 Err(e) => {
449 errors.push_for(None, e);
450 return Err(());
451 }
452 }
453 }
454 Ok(out)
455}
456
457#[allow(clippy::result_unit_err)]
463pub fn check_discovered_files(
464 trees: &[(PathBuf, PathBuf)],
465 file_lists: &[Vec<PathBuf>],
466 errors: &mut ErrorSink,
467) -> Result<(), ()> {
468 if file_lists.iter().all(|f| f.is_empty()) {
469 errors.push_for(
470 None,
471 CompileError::new(
472 "bynk.project.no_sources",
473 Span::default(),
474 format!(
475 "no `.bynk` source files found under {}",
476 trees[0].0.display()
477 ),
478 ),
479 );
480 return Err(());
481 }
482 for ((root, _prefix), files) in trees.iter().zip(file_lists.iter()) {
483 if let Err(e) = check_file_directory_conflicts(root, files) {
484 errors.extend_for(None, e);
485 }
486 }
487 Ok(())
488}
489
490pub const FIRSTPARTY_ID_BLOCK: u32 = 1_000_000;
502pub const FIRSTPARTY_ID_BASE: u32 = 1_000_000_000;
503
504pub const FIRSTPARTY_FILE_ID_BASE: u32 = 0xFFFF_0000;
513
514pub fn firstparty_file_id(unit: &firstparty::Unit) -> FileId {
516 FileId(FIRSTPARTY_FILE_ID_BASE + unit.id_block)
517}
518
519fn firstparty_unit_for(file: FileId) -> Option<&'static firstparty::Unit> {
521 firstparty::UNITS
522 .iter()
523 .find(|unit| firstparty_file_id(unit) == file)
524}
525
526pub fn firstparty_parsed(
527 cache: &'static OnceLock<Result<ParsedFile, Vec<CompileError>>>,
528 identity_path: &'static str,
529 src: &'static str,
530 kind: UnitKind,
531 id_base: u32,
542 file: FileId,
545) -> Result<ParsedFile, Vec<CompileError>> {
546 cache
547 .get_or_init(|| {
548 lexer::tokenize_in(src, file)
549 .map_err(|e| vec![e])
550 .and_then(|toks| {
551 parser::parse_unit_with_warnings_from(&toks, src, &mut { id_base })
552 .map(|(unit, _warnings)| unit)
553 })
554 .map(|unit| {
555 ParsedFile::synthetic(
556 PathBuf::from(identity_path),
557 PathBuf::from(identity_path),
558 src.to_string(),
559 unit,
560 kind,
561 )
562 })
563 })
564 .clone()
565}
566
567fn all_syntax_errors(source: &str, strict: Vec<CompileError>) -> Vec<CompileError> {
571 let (tokens, lex_errors) = bynk_syntax::lexer::tokenize_recovering(source);
572 let recovered = bynk_syntax::parser::parse_units_recovering(&tokens, source).errors;
573 let recovered = bynk_syntax::lexer::without_lex_echoes(&lex_errors, &tokens, recovered);
574 bynk_syntax::parser::merge_syntax_errors(strict, recovered)
575}
576
577#[allow(clippy::too_many_arguments)]
584#[allow(clippy::result_unit_err)]
585pub fn phase_parse(
586 trees: &[(PathBuf, PathBuf)],
589 file_lists: &[Vec<PathBuf>],
590 overlay: &HashMap<PathBuf, String>,
591 errors: &mut ErrorSink,
592 snapshots: &mut Vec<(PathBuf, String)>,
593) -> Result<(Vec<ParsedFile>, InjectedUnits, BrokenDeclNames), ()> {
594 let mut parsed: Vec<ParsedFile> = Vec::new();
595 let mut broken: BrokenDeclNames = HashMap::new();
596 let parse_tree = |root: &Path,
603 prefix: &Path,
604 files: &[PathBuf],
605 parsed: &mut Vec<ParsedFile>,
606 broken: &mut BrokenDeclNames,
607 errors: &mut ErrorSink,
608 snapshots: &mut Vec<(PathBuf, String)>| {
609 for path in files {
610 let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
612 let id = prefix.join(&rel);
615 let source = match read_source(path, overlay) {
616 Ok(s) => s,
617 Err(e) => {
618 errors.push_for(
619 Some(&id),
620 CompileError::new(
621 "bynk.project.read_failed",
622 Span::default(),
623 format!("could not read `{}`: {e}", path.display()),
624 ),
625 );
626 continue;
627 }
628 };
629 snapshots.push((id.clone(), source.clone()));
630 match parse_sources(root, prefix, path, source) {
631 Ok((pfs, warnings)) => {
632 parsed.extend(pfs);
633 errors.extend_for(Some(&id), warnings);
636 }
637 Err(errs) => {
644 let source = snapshots.last().expect("pushed just above").1.clone();
645 match parse_sources_recovering(root, prefix, path, source.clone()) {
646 Some(recovered) => {
647 errors.extend_for(
648 Some(&id),
649 bynk_syntax::parser::merge_syntax_errors(errs, recovered.errors),
650 );
651 for pf in &recovered.files {
656 broken
657 .entry(pf.unit().name().joined())
658 .or_default()
659 .extend(recovered.broken_decl_names.iter().cloned());
660 }
661 parsed.extend(recovered.files);
662 }
663 None => errors.extend_for(Some(&id), all_syntax_errors(&source, errs)),
664 }
665 }
666 }
667 }
668 };
669 for ((root, prefix), files) in trees.iter().zip(file_lists.iter()) {
670 parse_tree(
671 root,
672 prefix,
673 files,
674 &mut parsed,
675 &mut broken,
676 errors,
677 snapshots,
678 );
679 }
680 errors.register_parsed(&parsed);
681 if !errors.is_empty() && parsed.is_empty() {
682 return Err(());
683 }
684
685 let injected = inject_firstparty(&mut parsed, errors);
686 Ok((parsed, injected, broken))
687}
688
689pub type InjectedUnits = Vec<&'static firstparty::Unit>;
696
697fn inject_firstparty(parsed: &mut Vec<ParsedFile>, errors: &mut ErrorSink) -> InjectedUnits {
708 const N: usize = firstparty::UNITS.len();
709 static CACHES: [OnceLock<Result<ParsedFile, Vec<CompileError>>>; N] =
710 [const { OnceLock::new() }; N];
711 let reaches = |pf: &ParsedFile, unit: &firstparty::Unit| match unit.kind {
712 firstparty::UnitKind::Adapter => {
713 pf.consumes().iter().any(|c| c.target.joined() == unit.name)
714 }
715 firstparty::UnitKind::Commons => pf.uses().iter().any(|u| u.target.joined() == unit.name),
716 };
717 let mut reached: Vec<Option<Option<ParsedFile>>> = vec![None; N];
718 loop {
719 let mut grew = false;
720 for (i, unit) in firstparty::UNITS.iter().enumerate() {
721 if reached[i].is_some() {
722 continue;
723 }
724 let injected = reached.iter().flatten().flatten();
725 if !parsed.iter().chain(injected).any(|pf| reaches(pf, unit)) {
726 continue;
727 }
728 let kind = match unit.kind {
729 firstparty::UnitKind::Adapter => UnitKind::Adapter,
730 firstparty::UnitKind::Commons => UnitKind::Commons,
731 };
732 let parse = firstparty_parsed(
733 &CACHES[i],
734 unit.identity_path,
735 unit.source,
736 kind,
737 FIRSTPARTY_ID_BASE + unit.id_block * FIRSTPARTY_ID_BLOCK,
738 firstparty_file_id(unit),
739 );
740 reached[i] = Some(match parse {
741 Ok(pf) => Some(pf),
742 Err(errs) => {
743 errors.extend_for(None, errs);
744 None
745 }
746 });
747 grew = true;
748 }
749 if !grew {
750 break;
751 }
752 }
753 let mut order: Vec<usize> = (0..N).filter(|&i| reached[i].is_some()).collect();
754 order.sort_by_key(|&i| firstparty::UNITS[i].id_block);
755 for &i in &order {
756 if let Some(Some(pf)) = reached[i].take() {
757 parsed.push(pf);
758 }
759 }
760 order.into_iter().map(|i| &firstparty::UNITS[i]).collect()
761}
762
763pub fn phase_resolve_derived(
771 groups: &BTreeMap<String, Vec<usize>>,
772 kinds: &BTreeMap<String, UnitKind>,
773 parsed: &[ParsedFile],
774 layout: &bynk_project::worker_layout::WorkerLayout,
775 unit_tables: &mut HashMap<String, UnitTable>,
776 errors: &mut ErrorSink,
777) {
778 let selections = consume_selections(groups, kinds, parsed);
781 crate::symbols::record_unselected_consumed_types(unit_tables, &selections);
782 for (name, indices) in groups {
783 for &i in indices {
784 if parsed[i].is_synthetic() {
785 continue;
786 }
787 let path = parsed[i].identity_path();
788 for item in parsed[i].items() {
789 let CommonsItem::Capability(c) = item else {
790 continue;
791 };
792 let Some(d) = &c.derived else { continue };
793 if kinds.get(name) != Some(&UnitKind::Context) {
794 errors.push_for(
795 Some(&path),
796 CompileError::new(
797 "bynk.capability.derived_outside_context",
798 c.span,
799 format!(
800 "derived capability `{}` is declared outside a context",
801 c.name.name
802 ),
803 )
804 .with_note("a named instance of a platform resource belongs to the context that owns its data"),
805 );
806 continue;
807 }
808 let Some(table) = unit_tables.get(name) else {
809 continue;
810 };
811 let Some(owner) = table.flattened_caps.get(&d.base.name).cloned() else {
812 errors.push_for(
813 Some(&path),
814 CompileError::new(
815 "bynk.capability.unknown_base",
816 d.base.span,
817 format!(
818 "`{}` is not a capability this context selects with `consumes U {{ … }}`",
819 d.base.name
820 ),
821 )
822 .with_note(format!(
823 "a derived capability's base is a platform capability, selected by name: `consumes bynk.cloudflare {{ {} }}`",
824 d.base.name
825 )),
826 );
827 continue;
828 };
829 let Some(kind) = crate::firstparty::instantiable(&owner, &d.base.name) else {
830 let mut error = CompileError::new(
831 "bynk.capability.base_not_instantiable",
832 d.base.span,
833 format!(
834 "`{owner}.{}` has no named instances: a derived capability's base must be a platform resource kind",
835 d.base.name
836 ),
837 );
838 if crate::firstparty::singleton(&owner, &d.base.name).is_some() {
840 error = error.with_note(format!(
841 "a Worker has one `{0}` binding, so `{0}` is used bare: write `given {0}` where it is needed, not a capability over it",
842 d.base.name
843 ));
844 }
845 errors.push_for(Some(&path), error);
846 continue;
847 };
848 let mut options: Vec<(String, crate::symbols::OptionValue)> = Vec::new();
850 for ann in &d.annotations {
851 if let Some(option_kind) = kind.option_kind(&ann.name.name) {
852 if options.iter().any(|(o, _)| *o == ann.name.name) {
853 errors.push_for(
854 Some(&path),
855 CompileError::new(
856 "bynk.capability.invalid_option",
857 ann.span,
858 format!("`@{}` is given twice", ann.name.name),
859 )
860 .with_note("an instance takes each option once"),
861 );
862 } else if let Some(value) =
863 instance_option_value(ann, option_kind, &d.base.name, &path, errors)
864 {
865 let own = match &value {
870 crate::symbols::OptionValue::Str(value)
871 if ann.name.name == firstparty::SERVICE_WORKER_OPTION =>
872 {
873 kinds.iter().find(|(unit, kind)| {
874 **kind == UnitKind::Context
875 && layout.script_name(unit) == *value
876 })
877 }
878 _ => None,
879 };
880 if let Some((context, _)) = own {
881 errors.push_for(
882 Some(&path),
883 CompileError::new(
884 "bynk.capability.invalid_option",
885 ann.span,
886 format!(
887 "`{}` is this project's context `{context}`, not a Worker outside it",
888 layout.script_name(context)
889 ),
890 )
891 .with_note(format!(
892 "reach a Bynk context with `consumes {context}`, which checks its contract"
893 )),
894 );
895 } else {
896 options.push((ann.name.name.clone(), value));
897 }
898 }
899 }
900 if kind.option_kind(&ann.name.name).is_none() {
901 let allowed = if d.base.name == "Analytics" {
902 "`Analytics` instances take no options: `bynk deploy` names the dataset for the context and the capability".to_string()
904 } else if kind.options.is_empty() {
905 format!("`{}` instances take no options", d.base.name)
906 } else {
907 format!(
908 "`{}` instances take {}",
909 d.base.name,
910 kind.option_names()
911 .map(|o| format!("`@{o}`"))
912 .collect::<Vec<_>>()
913 .join(", ")
914 )
915 };
916 errors.push_for(
917 Some(&path),
918 CompileError::new(
919 "bynk.capability.unknown_option",
920 ann.span,
921 format!(
922 "`@{}` is not an option of a `{}` instance",
923 ann.name.name, d.base.name
924 ),
925 )
926 .with_note(allowed),
927 );
928 }
929 }
930 for required in kind.required {
931 if !d.annotations.iter().any(|a| a.name.name == *required) {
932 errors.push_for(
933 Some(&path),
934 CompileError::new(
935 "bynk.capability.missing_option",
936 c.span,
937 format!("a `{}` instance needs `@{required}(…)`", d.base.name),
938 )
939 .with_note(format!("write `{}`", instance_example(kind))),
940 );
941 }
942 }
943 if table.exported_capabilities.contains(&c.name.name) {
944 errors.push_for(
945 Some(&path),
946 CompileError::new(
947 "bynk.exports.derived_capability",
948 c.span,
949 format!("derived capability `{}` cannot be exported", c.name.name),
950 )
951 .with_note("an instance's data belongs to this context; another context reaches it through this context's services"),
952 );
953 }
954 let ops = unit_tables
955 .get(&owner)
956 .and_then(|t| t.capabilities.get(&d.base.name))
957 .map(|base| base.ops.clone())
958 .unwrap_or_default();
959 let binding = crate::worker_bindings::instance_binding_name(
960 kind.binding_prefix,
961 &c.name.name,
962 );
963 let table = unit_tables.get_mut(name).expect("checked above");
964 if crate::symbols::is_edge_cache_base(&owner, &d.base.name)
967 && let Some((earlier, _)) =
968 table.derived.iter().find(|(_, inst)| inst.is_edge_cache())
969 {
970 errors.push_for(
971 Some(&path),
972 CompileError::new(
973 "bynk.cloudflare.edge_cache_duplicate",
974 c.span,
975 format!(
976 "context `{name}` already declares `EdgeCache` instance `{earlier}`"
977 ),
978 )
979 .with_note(format!(
980 "the edge cache is one setting for the whole Worker, so one instance turns it on and purges it; use `{earlier}`"
981 )),
982 );
983 continue;
984 }
985 if let Some(decl) = table.capabilities.get_mut(&c.name.name) {
986 decl.ops = ops;
987 }
988 table.derived.insert(
989 c.name.name.clone(),
990 crate::symbols::DerivedInstance {
991 base_unit: owner,
992 base_cap: d.base.name.clone(),
993 binding,
994 options,
995 span: c.span,
996 },
997 );
998 }
999 }
1000 }
1001 phase_edge_cache_reach(groups, parsed, unit_tables, errors);
1002}
1003
1004pub fn phase_edge_cache_reach(
1016 groups: &BTreeMap<String, Vec<usize>>,
1017 parsed: &[ParsedFile],
1018 unit_tables: &HashMap<String, UnitTable>,
1019 errors: &mut ErrorSink,
1020) {
1021 for (name, indices) in groups {
1022 let Some(table) = unit_tables.get(name) else {
1023 continue;
1024 };
1025 let mut reaches: BTreeMap<String, String> = table
1028 .derived
1029 .iter()
1030 .filter(|(_, d)| d.is_edge_cache())
1031 .map(|(cap, _)| (cap.clone(), cap.clone()))
1032 .collect();
1033 if reaches.is_empty() {
1034 continue;
1035 }
1036 loop {
1037 let mut grew = false;
1038 for (cap, provider) in &table.providers {
1039 if reaches.contains_key(cap) {
1040 continue;
1041 }
1042 let via = provider
1043 .given
1044 .iter()
1045 .filter(|g| !g.is_cross_context())
1046 .find_map(|g| reaches.get(g.key()).cloned());
1047 if let Some(instance) = via {
1048 reaches.insert(cap.clone(), instance);
1049 grew = true;
1050 }
1051 }
1052 if !grew {
1053 break;
1054 }
1055 }
1056 for &i in indices {
1057 let path = parsed[i].identity_path();
1058 for item in parsed[i].items() {
1059 if let CommonsItem::Capability(c) = item
1062 && c.derived.is_none()
1063 && table.exported_capabilities.contains(&c.name.name)
1064 && let Some(instance) = reaches.get(&c.name.name)
1065 {
1066 errors.push_for(
1067 Some(&path),
1068 CompileError::new(
1069 "bynk.cloudflare.edge_cache_exported",
1070 c.span,
1071 format!(
1072 "exported capability `{}` reaches `EdgeCache` instance `{instance}`, which purges only from this context's own Worker",
1073 c.name.name
1074 ),
1075 )
1076 .with_note(
1077 "a context that consumes it would build its provider in its own Worker, whose purge misses this Worker's cache; export a service that purges instead",
1078 ),
1079 );
1080 }
1081 if let CommonsItem::Service(svc) = item
1087 && matches!(svc.protocol, ServiceProtocol::Http)
1088 {
1089 for h in &svc.handlers {
1090 let public = h.annotations.iter().any(|a| {
1091 a.name.name == "cache"
1092 && a.args.iter().any(|arg| {
1093 arg.label.as_ref().is_some_and(|l| l.name == "scope")
1094 && matches!(&arg.value.kind, ExprKind::Ident(id) if id.name == "public")
1095 })
1096 });
1097 let Some(by) = h.by_clause.as_ref().or(svc.default_by.as_ref()) else {
1098 continue;
1099 };
1100 let closed = by.actors.iter().find(|a| {
1101 let single = ByClause {
1102 binder: None,
1103 actors: vec![(*a).clone()],
1104 span: by.span,
1105 };
1106 !crate::actors::sum_has_open_member(&single, &table.actors)
1107 });
1108 if let (true, Some(actor)) = (public, closed) {
1109 errors.push_for(
1110 Some(&path),
1111 CompileError::new(
1112 "bynk.cloudflare.edge_cache_public_authenticated",
1113 by.span,
1114 format!(
1115 "a `@cache(scope: public)` route by `{}` would share one caller's response with every caller at Cloudflare's edge",
1116 actor.name
1117 ),
1118 )
1119 .with_note(format!(
1120 "context `{name}` declares `EdgeCache`, and the edge cache keys a response by its URL alone; use `scope: private`, or serve the route `by Visitor`"
1121 )),
1122 );
1123 }
1124 }
1125 }
1126 let (handlers, code, place, note) = match item {
1127 CommonsItem::Agent(a) => (
1128 &a.handlers,
1129 "bynk.cloudflare.edge_cache_in_agent",
1130 format!("agent `{}`", a.name.name),
1131 "an agent runs in a Durable Object, whose purge would not reach this Worker's cache; purge from the service handler that calls the agent",
1132 ),
1133 CommonsItem::Service(svc)
1134 if matches!(svc.protocol, ServiceProtocol::Queue { .. }) =>
1135 {
1136 (
1137 &svc.handlers,
1138 "bynk.cloudflare.edge_cache_in_queue",
1139 format!("queue consumer `{}`", svc.name.name),
1140 "a queue consumer is not the entrypoint the cache serves, and its purge is not known to reach that cache; purge from a service handler",
1141 )
1142 }
1143 CommonsItem::Service(svc) if matches!(svc.protocol, ServiceProtocol::Cron) => (
1144 &svc.handlers,
1145 "bynk.cloudflare.edge_cache_in_schedule",
1146 format!("`on schedule` service `{}`", svc.name.name),
1147 "Cloudflare accepts a purge from a cron run but it clears nothing from the cache the Worker's `fetch` serves; purge from a service handler",
1148 ),
1149 _ => continue,
1150 };
1151 for h in handlers {
1152 for g in h.given.iter().filter(|g| !g.is_cross_context()) {
1153 let Some(instance) = reaches.get(g.key()) else {
1154 continue;
1155 };
1156 let how = if g.key() == instance {
1157 String::new()
1158 } else {
1159 format!(" (through `{}`)", g.key())
1160 };
1161 errors.push_for(
1162 Some(&path),
1163 CompileError::new(
1164 code,
1165 g.span,
1166 format!(
1167 "{place} reaches `EdgeCache` instance `{instance}`{how}, which purges only from the Worker's `fetch`"
1168 ),
1169 )
1170 .with_note(note),
1171 );
1172 }
1173 }
1174 }
1175 }
1176 }
1177}
1178
1179pub(crate) fn instance_example(kind: &firstparty::Instantiable) -> String {
1183 let name = match kind.capability {
1184 "Service" => "Billing",
1185 "RateLimit" => "LoginLimit",
1186 "EdgeCache" => "Edge",
1187 "Queue" => "OrderEvents",
1188 "Analytics" => "Signups",
1189 "D1" => "Orders",
1190 "StoredSecret" => "StripeKey",
1191 "Email" => "Mail",
1192 "Postgres" => "Main",
1193 "MySql" => "Legacy",
1194 "Vectorize" => "Docs",
1195 "Container" => "Renderer",
1196 "AiSearch" => "Kb",
1197 "MtlsCertificate" => "Backend",
1198 _ => "Archives",
1199 };
1200 let mut out = format!("capability {name} = {}", kind.capability);
1201 for required in kind.required {
1202 out.push_str(&format!(" @{required}({})", option_sample(required)));
1203 }
1204 out
1205}
1206
1207fn option_sample(option: &str) -> &'static str {
1209 match option {
1210 firstparty::R2_JURISDICTION_OPTION => "\"eu\"",
1211 firstparty::RATELIMIT_LIMIT_OPTION => "100",
1212 firstparty::RATELIMIT_PERIOD_OPTION => "60.seconds",
1213 firstparty::QUEUE_NAME_OPTION => "\"order-events\"",
1214 firstparty::STORED_SECRET_STORE_OPTION => "\"payments\"",
1215 firstparty::STORED_SECRET_SECRET_OPTION => "\"stripe-live\"",
1216 firstparty::EMAIL_TO_OPTION => "\"[email protected]\"",
1217 firstparty::EMAIL_ALLOWED_RECIPIENTS_OPTION | firstparty::EMAIL_ALLOWED_SENDERS_OPTION => {
1218 "[\"[email protected]\"]"
1219 }
1220 firstparty::AI_SEARCH_INSTANCE_OPTION => "\"support-docs\"",
1221 firstparty::MTLS_CERTIFICATE_OPTION => "\"acme-client\"",
1222 firstparty::VECTORIZE_DIMENSIONS_OPTION => "768",
1223 firstparty::VECTORIZE_METRIC_OPTION => "\"cosine\"",
1224 firstparty::VECTORIZE_INDEXED_OPTION => "[\"category:string\"]",
1225 firstparty::CONTAINER_BUILD_OPTION => "\"containers/renderer\"",
1226 firstparty::CONTAINER_PORT_OPTION => "8080",
1227 firstparty::CONTAINER_SLEEP_AFTER_OPTION => "5.minutes",
1228 firstparty::CONTAINER_INSTANCE_TYPE_OPTION => "\"lite\"",
1229 firstparty::CONTAINER_FORWARD_OPTION => "[\"API_KEY\"]",
1230 _ => "\"legacy-billing\"",
1231 }
1232}
1233
1234fn vectorize_dimensions_problem(value: i64) -> Option<(&'static str, i64)> {
1238 if value > firstparty::VECTORIZE_MAX_DIMENSIONS {
1239 Some(("most", firstparty::VECTORIZE_MAX_DIMENSIONS))
1240 } else if value > 0 && value < firstparty::VECTORIZE_MIN_DIMENSIONS {
1241 Some(("least", firstparty::VECTORIZE_MIN_DIMENSIONS))
1242 } else {
1243 None
1244 }
1245}
1246
1247fn mtls_certificate_error(
1251 base: &str,
1252 option: &str,
1253 text: &str,
1254 span: bynk_syntax::span::Span,
1255) -> Option<CompileError> {
1256 (base == "MtlsCertificate"
1257 && option == crate::firstparty::MTLS_CERTIFICATE_OPTION
1258 && (text.trim().is_empty() || text.chars().any(char::is_control)))
1259 .then(|| {
1260 CompileError::new(
1261 "bynk.capability.invalid_option",
1262 span,
1263 format!("{text:?} is not a certificate name a `{base}` can reach"),
1264 )
1265 .with_note(
1266 "name the certificate as it was uploaded to the account (`wrangler mtls-certificate list` shows it), for example `@certificate(\"acme-client\")`",
1267 )
1268 })
1269}
1270
1271fn ai_search_instance_error(
1276 base: &str,
1277 option: &str,
1278 text: &str,
1279 span: bynk_syntax::span::Span,
1280) -> Option<CompileError> {
1281 (base == "AiSearch"
1282 && option == crate::firstparty::AI_SEARCH_INSTANCE_OPTION
1283 && !is_ai_search_instance_name(text))
1284 .then(|| {
1285 CompileError::new(
1286 "bynk.capability.invalid_option",
1287 span,
1288 format!("`{text}` is not an instance name a `{base}` can reach"),
1289 )
1290 .with_note(
1291 "an instance name is 1 to 64 lowercase letters, digits, `-` or `_`, the form Cloudflare's API documents",
1292 )
1293 })
1294}
1295
1296fn vectorize_metric_error(
1298 base: &str,
1299 option: &str,
1300 text: &str,
1301 span: bynk_syntax::span::Span,
1302) -> Option<CompileError> {
1303 (base == "Vectorize"
1304 && option == crate::firstparty::VECTORIZE_METRIC_OPTION
1305 && !crate::firstparty::VECTORIZE_METRICS.contains(&text))
1306 .then(|| {
1307 CompileError::new(
1308 "bynk.capability.invalid_option",
1309 span,
1310 format!("`{text}` is not a distance metric a `{base}` index can use"),
1311 )
1312 .with_note(format!(
1313 "the metrics are {}",
1314 crate::firstparty::VECTORIZE_METRICS
1315 .iter()
1316 .map(|m| format!("`\"{m}\"`"))
1317 .collect::<Vec<_>>()
1318 .join(", ")
1319 ))
1320 })
1321}
1322
1323fn instance_option_value(
1332 ann: &bynk_syntax::ast::Annotation,
1333 kind: firstparty::OptionKind,
1334 base: &str,
1335 path: &std::path::Path,
1336 errors: &mut ErrorSink,
1337) -> Option<crate::symbols::OptionValue> {
1338 use crate::symbols::OptionValue;
1339 let option = ann.name.name.as_str();
1340 let invalid = |span, message: String| {
1341 CompileError::new("bynk.capability.invalid_option", span, message).with_note(format!(
1342 "write `@{option}({})`, for example",
1343 option_sample(option)
1344 ))
1345 };
1346 let [arg] = ann.args.as_slice() else {
1347 errors.push_for(
1348 Some(path),
1349 invalid(
1350 ann.span,
1351 format!("`@{option}` takes one positional argument"),
1352 ),
1353 );
1354 return None;
1355 };
1356 if arg.label.is_some() {
1357 errors.push_for(
1358 Some(path),
1359 invalid(
1360 ann.span,
1361 format!("`@{option}` takes one positional argument"),
1362 ),
1363 );
1364 return None;
1365 }
1366 let value = match (kind, &arg.value.kind) {
1367 (firstparty::OptionKind::Str, ExprKind::StrLit(value)) => OptionValue::Str(value.clone()),
1368 (firstparty::OptionKind::Str, _) => {
1369 errors.push_for(
1370 Some(path),
1371 invalid(arg.span, format!("`@{option}` takes a string literal")),
1372 );
1373 return None;
1374 }
1375 (firstparty::OptionKind::StrList, ExprKind::ListLit(items, ..)) => {
1376 let mut out = Vec::new();
1377 for item in items {
1378 let ExprKind::StrLit(text) = &item.kind else {
1379 errors.push_for(
1380 Some(path),
1381 invalid(
1382 item.span,
1383 format!("`@{option}` takes a list of string literals"),
1384 ),
1385 );
1386 return None;
1387 };
1388 out.push(text.clone());
1389 }
1390 if out.is_empty() {
1391 errors.push_for(
1392 Some(path),
1393 invalid(
1394 arg.span,
1395 format!(
1396 "`@{option}` takes at least one {}",
1397 if base == "Container" {
1398 "entry"
1399 } else {
1400 "address"
1401 }
1402 ),
1403 ),
1404 );
1405 return None;
1406 }
1407 OptionValue::List(out)
1408 }
1409 (firstparty::OptionKind::StrList, _) => {
1410 errors.push_for(
1411 Some(path),
1412 invalid(
1413 arg.span,
1414 format!("`@{option}` takes a list of string literals"),
1415 ),
1416 );
1417 return None;
1418 }
1419 (firstparty::OptionKind::PositiveInt, ExprKind::IntLit { value, .. })
1420 if base == "Vectorize"
1421 && option == firstparty::VECTORIZE_DIMENSIONS_OPTION
1422 && vectorize_dimensions_problem(*value).is_some() =>
1423 {
1424 let (bound, limit) = vectorize_dimensions_problem(*value).unwrap_or_default();
1425 errors.push_for(
1426 Some(path),
1427 CompileError::new(
1428 "bynk.capability.invalid_option",
1429 arg.span,
1430 format!("`@{option}` is at {bound} {limit} for a `{base}` index"),
1431 )
1432 .with_note("Cloudflare creates an index only with a dimension count in its supported range, 32 to 1536"),
1433 );
1434 return None;
1435 }
1436 (firstparty::OptionKind::PositiveInt, ExprKind::IntLit { value, .. })
1437 if base == "Container"
1438 && option == firstparty::CONTAINER_PORT_OPTION
1439 && crate::containers::port_problem(*value).is_some() =>
1440 {
1441 errors.push_for(
1442 Some(path),
1443 CompileError::new(
1444 "bynk.capability.invalid_option",
1445 arg.span,
1446 format!("`@{option}` is not a port a `{base}` can listen on"),
1447 )
1448 .with_note("a port is a TCP port, 1 to 65535"),
1449 );
1450 return None;
1451 }
1452 (firstparty::OptionKind::PositiveInt, ExprKind::IntLit { value, .. }) if *value > 0 => {
1453 OptionValue::Int(*value)
1454 }
1455 (firstparty::OptionKind::PositiveInt, _) => {
1456 errors.push_for(
1457 Some(path),
1458 invalid(
1459 arg.span,
1460 format!("`@{option}` takes a positive `Int` literal"),
1461 ),
1462 );
1463 return None;
1464 }
1465 (firstparty::OptionKind::Duration, _) if base == "Container" => OptionValue::Seconds(
1466 container_sleep_after(&arg.value.kind, arg.span, path, errors)?,
1467 ),
1468 (firstparty::OptionKind::Duration, ExprKind::DurationLit { millis, .. })
1469 if *millis % 1000 == 0 && firstparty::RATELIMIT_PERIODS.contains(&(*millis / 1000)) =>
1470 {
1471 OptionValue::Seconds(*millis / 1000)
1472 }
1473 (firstparty::OptionKind::Duration, _) => {
1474 errors.push_for(
1475 Some(path),
1476 CompileError::new(
1477 "bynk.capability.invalid_option",
1478 arg.span,
1479 format!("`@{option}` must be a window a `{base}` offers"),
1480 )
1481 .with_note(format!(
1482 "the windows are {}",
1483 firstparty::RATELIMIT_PERIODS
1484 .iter()
1485 .map(|s| format!("`{s}.seconds`"))
1486 .collect::<Vec<_>>()
1487 .join(" and ")
1488 )),
1489 );
1490 return None;
1491 }
1492 };
1493 if let OptionValue::List(items) = &value {
1494 if base == "Container" {
1496 return container_forward_ok(items, ann, path, errors).then_some(value);
1497 }
1498 if base == "Vectorize" {
1500 return vectorize_indexed_ok(items, ann, path, errors).then_some(value);
1501 }
1502 if !email_list_ok(items, base, ann, path, errors) {
1504 return None;
1505 }
1506 return Some(value);
1507 }
1508 let OptionValue::Str(text) = &value else {
1509 return Some(value);
1510 };
1511 if base == "Email" && option == crate::firstparty::EMAIL_TO_OPTION && !is_email_address(text) {
1512 errors.push_for(
1513 Some(path),
1514 invalid(
1515 ann.span,
1516 format!(
1517 "`{}` is not an email address a `{base}` can use",
1518 text.escape_debug()
1519 ),
1520 )
1521 .with_note("an address is `name@domain`, with no spaces or control characters"),
1522 );
1523 return None;
1524 }
1525 if option == crate::firstparty::R2_JURISDICTION_OPTION
1526 && !r2_jurisdiction_ok(text, base, ann, path, errors)
1527 {
1528 return None;
1529 }
1530 if let Some(error) = vectorize_metric_error(base, option, text, ann.span) {
1531 errors.push_for(Some(path), error);
1532 return None;
1533 }
1534 if base == "Container" && !container_str_ok(text, option, ann, path, errors) {
1536 return None;
1537 }
1538 if option == crate::firstparty::MYSQL_TLS_OPTION
1540 && !crate::firstparty::MYSQL_TLS_MODES
1541 .iter()
1542 .any(|(mode, _)| mode == text)
1543 {
1544 errors.push_for(
1545 Some(path),
1546 CompileError::new(
1547 "bynk.capability.invalid_option",
1548 ann.span,
1549 format!("`{text}` is not a TLS mode a `{base}` can use"),
1550 )
1551 .with_note(format!(
1552 "the modes are {}; `\"required\"` is the default",
1553 crate::firstparty::MYSQL_TLS_MODES
1554 .iter()
1555 .map(|(m, _)| format!("`\"{m}\"`"))
1556 .collect::<Vec<_>>()
1557 .join(", ")
1558 )),
1559 );
1560 return None;
1561 }
1562 if option == crate::firstparty::SERVICE_WORKER_OPTION && !is_worker_name(text) {
1563 errors.push_for(
1564 Some(path),
1565 CompileError::new(
1566 "bynk.capability.invalid_option",
1567 ann.span,
1568 format!("`{text}` is not a Worker name a `{base}` can reach"),
1569 )
1570 .with_note(
1571 "a Worker name is 1 to 63 lowercase letters, digits, `-` or `_`, and does not start or end with `-`",
1572 ),
1573 );
1574 return None;
1575 }
1576 if let Some(error) = ai_search_instance_error(base, option, text, ann.span) {
1577 errors.push_for(Some(path), error);
1578 return None;
1579 }
1580 if let Some(error) = mtls_certificate_error(base, option, text, ann.span) {
1581 errors.push_for(Some(path), error);
1582 return None;
1583 }
1584 if base == "StoredSecret"
1585 && matches!(
1586 option,
1587 crate::firstparty::STORED_SECRET_STORE_OPTION
1588 | crate::firstparty::STORED_SECRET_SECRET_OPTION
1589 )
1590 && !is_secrets_store_name(text)
1591 {
1592 let what = if option == crate::firstparty::STORED_SECRET_STORE_OPTION {
1593 "store"
1594 } else {
1595 "secret"
1596 };
1597 errors.push_for(
1598 Some(path),
1599 CompileError::new(
1600 "bynk.capability.invalid_option",
1601 ann.span,
1602 format!("`{text}` is not a {what} name a `{base}` can read"),
1603 )
1604 .with_note("a Secrets Store name is 1 to 255 letters, digits, `-` or `_`"),
1605 );
1606 return None;
1607 }
1608 if option == crate::firstparty::QUEUE_NAME_OPTION && base == "Queue" && !is_queue_name(text) {
1609 errors.push_for(
1610 Some(path),
1611 CompileError::new(
1612 "bynk.capability.invalid_option",
1613 ann.span,
1614 format!("`{text}` is not a queue name a `{base}` can send to"),
1615 )
1616 .with_note(
1617 "a queue name is 1 to 63 lowercase letters, digits or `-`, and starts and ends with a letter or digit",
1618 ),
1619 );
1620 return None;
1621 }
1622 Some(value)
1623}
1624
1625fn email_list_ok(
1628 items: &[String],
1629 base: &str,
1630 ann: &bynk_syntax::ast::Annotation,
1631 path: &std::path::Path,
1632 errors: &mut ErrorSink,
1633) -> bool {
1634 let option = ann.name.name.as_str();
1635 let Some(item) = items.iter().find(|item| !is_email_address(item)) else {
1636 return true;
1637 };
1638 errors.push_for(
1639 Some(path),
1640 CompileError::new(
1641 "bynk.capability.invalid_option",
1642 ann.span,
1643 format!(
1644 "`{}` is not an email address a `{base}` can use",
1645 item.escape_debug()
1646 ),
1647 )
1648 .with_note(format!(
1649 "write `@{option}({})`, for example",
1650 option_sample(option)
1651 ))
1652 .with_note("an address is `name@domain`, with no spaces or control characters"),
1653 );
1654 false
1655}
1656
1657fn r2_jurisdiction_ok(
1660 text: &str,
1661 base: &str,
1662 ann: &bynk_syntax::ast::Annotation,
1663 path: &std::path::Path,
1664 errors: &mut ErrorSink,
1665) -> bool {
1666 if crate::firstparty::R2_JURISDICTIONS.contains(&text) {
1667 return true;
1668 }
1669 errors.push_for(
1670 Some(path),
1671 CompileError::new(
1672 "bynk.capability.invalid_option",
1673 ann.span,
1674 format!("`{text}` is not a jurisdiction a `{base}` bucket can be pinned to"),
1675 )
1676 .with_note(format!(
1677 "the jurisdictions are {}",
1678 crate::firstparty::R2_JURISDICTIONS
1679 .iter()
1680 .map(|j| format!("`\"{j}\"`"))
1681 .collect::<Vec<_>>()
1682 .join(" and ")
1683 )),
1684 );
1685 false
1686}
1687
1688fn container_str_ok(
1692 text: &str,
1693 option: &str,
1694 ann: &bynk_syntax::ast::Annotation,
1695 path: &std::path::Path,
1696 errors: &mut ErrorSink,
1697) -> bool {
1698 let error = if option == firstparty::CONTAINER_BUILD_OPTION {
1699 crate::containers::build_path_problem(text).map(|problem| {
1700 CompileError::new(
1701 "bynk.container.build_path",
1702 ann.span,
1703 format!("`@build(\"{}\")` {problem}", text.escape_debug()),
1704 )
1705 .with_note(
1706 "`@build` names the directory that holds the `Dockerfile`, relative to the project root, for example `@build(\"containers/renderer\")`",
1707 )
1708 })
1709 } else if option == firstparty::CONTAINER_INSTANCE_TYPE_OPTION
1710 && !firstparty::CONTAINER_INSTANCE_TYPES.contains(&text)
1711 {
1712 Some(
1713 CompileError::new(
1714 "bynk.capability.invalid_option",
1715 ann.span,
1716 format!("`{text}` is not an instance type a `Container` can start with"),
1717 )
1718 .with_note(format!(
1719 "the instance types are {}",
1720 firstparty::CONTAINER_INSTANCE_TYPES
1721 .iter()
1722 .map(|t| format!("`\"{t}\"`"))
1723 .collect::<Vec<_>>()
1724 .join(", ")
1725 )),
1726 )
1727 } else {
1728 None
1729 };
1730 let Some(error) = error else {
1731 return true;
1732 };
1733 errors.push_for(Some(path), error);
1734 false
1735}
1736
1737fn container_sleep_after(
1740 kind: &ExprKind,
1741 span: bynk_syntax::span::Span,
1742 path: &std::path::Path,
1743 errors: &mut ErrorSink,
1744) -> Option<i64> {
1745 let seconds = match kind {
1746 ExprKind::DurationLit { millis, .. } => crate::containers::sleep_after_seconds(*millis),
1747 _ => None,
1748 };
1749 if seconds.is_none() {
1750 errors.push_for(
1751 Some(path),
1752 CompileError::new(
1753 "bynk.capability.invalid_option",
1754 span,
1755 "`@sleepAfter` is not a time a `Container` can sleep after".to_string(),
1756 )
1757 .with_note(
1758 "write a whole number of seconds, more than zero and at most 6 hours, for example `5.minutes`",
1759 ),
1760 );
1761 }
1762 seconds
1763}
1764
1765fn container_forward_ok(
1769 items: &[String],
1770 ann: &bynk_syntax::ast::Annotation,
1771 path: &std::path::Path,
1772 errors: &mut ErrorSink,
1773) -> bool {
1774 let Some(message) = crate::containers::forward_problem(items) else {
1775 return true;
1776 };
1777 errors.push_for(
1778 Some(path),
1779 CompileError::new("bynk.capability.invalid_option", ann.span, message).with_note(
1780 "write `@forward([\"API_KEY\"])`: the names of Worker secrets, each a letter or `_` then letters, digits or `_`; their values are never written into source or config",
1781 ),
1782 );
1783 false
1784}
1785
1786fn vectorize_indexed_ok(
1791 items: &[String],
1792 ann: &bynk_syntax::ast::Annotation,
1793 path: &std::path::Path,
1794 errors: &mut ErrorSink,
1795) -> bool {
1796 let types = firstparty::VECTORIZE_INDEXED_TYPES;
1797 let problem = if items.len() > firstparty::VECTORIZE_MAX_INDEXED {
1798 Some(format!(
1799 "an index has at most {} metadata indexes, and `@indexed` lists {}",
1800 firstparty::VECTORIZE_MAX_INDEXED,
1801 items.len()
1802 ))
1803 } else {
1804 items.iter().enumerate().find_map(|(i, item)| {
1805 let Some((name, ty)) = item.split_once(':') else {
1806 return Some(format!("`{}` is not `name:type`", item.escape_debug()));
1807 };
1808 if !types.contains(&ty) {
1809 return Some(format!(
1810 "`{}` is not a type a metadata index holds",
1811 ty.escape_debug()
1812 ));
1813 }
1814 if !is_metadata_property(name) {
1815 return Some(format!(
1816 "`{}` is not a metadata property a filter can name",
1817 name.escape_debug()
1818 ));
1819 }
1820 items[..i]
1821 .iter()
1822 .any(|p| p.split_once(':').is_some_and(|(n, _)| n == name))
1823 .then(|| format!("`{name}` is listed twice"))
1824 })
1825 };
1826 let Some(message) = problem else {
1827 return true;
1828 };
1829 errors.push_for(
1830 Some(path),
1831 CompileError::new("bynk.capability.invalid_option", ann.span, message).with_note(format!(
1832 "write `@indexed([\"category:string\", \"year:number\"])`: at most {} entries, each `name:type` with the type {}",
1833 firstparty::VECTORIZE_MAX_INDEXED,
1834 types
1835 .iter()
1836 .map(|t| format!("`{t}`"))
1837 .collect::<Vec<_>>()
1838 .join(", ")
1839 )),
1840 );
1841 false
1842}
1843
1844fn is_metadata_property(name: &str) -> bool {
1848 name.chars().count() <= 512
1849 && name
1850 .split('.')
1851 .all(|seg| !seg.is_empty() && !seg.starts_with('$') && !seg.contains(['"', '|']))
1852}
1853
1854pub(crate) fn is_queue_name(name: &str) -> bool {
1861 let alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit();
1862 (1..=63).contains(&name.len())
1863 && name.bytes().all(|b| alnum(b) || b == b'-')
1864 && name.bytes().next().is_some_and(alnum)
1865 && name.bytes().last().is_some_and(alnum)
1866}
1867
1868pub(crate) fn is_email_address(text: &str) -> bool {
1873 let Some((local, domain)) = text.split_once('@') else {
1874 return false;
1875 };
1876 !local.is_empty()
1877 && !domain.is_empty()
1878 && domain
1880 .bytes()
1881 .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-')
1882 && !text
1883 .chars()
1884 .any(|c| c.is_whitespace() || c.is_control() || matches!(c, '<' | '>' | '"' | ','))
1885}
1886
1887pub(crate) fn is_secrets_store_name(name: &str) -> bool {
1891 (1..=255).contains(&name.len())
1892 && name
1893 .bytes()
1894 .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
1895}
1896
1897fn is_ai_search_instance_name(name: &str) -> bool {
1899 (1..=64).contains(&name.len())
1900 && name
1901 .bytes()
1902 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
1903}
1904
1905fn is_worker_name(name: &str) -> bool {
1907 (1..=63).contains(&name.len())
1908 && name
1909 .bytes()
1910 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
1911 && !name.starts_with('-')
1912 && !name.ends_with('-')
1913}
1914
1915pub type BrokenDeclNames = HashMap<String, Vec<String>>;
1920
1921pub fn tree_root_for<'a>(trees: &'a [(PathBuf, PathBuf)], pf: &ParsedFile) -> &'a Path {
1939 let Some(abs) = pf.abs_path() else {
1940 return trees[0].0.as_path();
1941 };
1942 trees
1943 .iter()
1944 .filter_map(|(root, _)| {
1945 std::path::absolute(root)
1946 .ok()
1947 .map(|abs_root| (root, abs_root))
1948 })
1949 .filter(|(_, abs_root)| abs.starts_with(abs_root))
1950 .max_by_key(|(root, _)| root.as_os_str().len())
1951 .map(|(root, _)| root.as_path())
1952 .unwrap_or_else(|| trees[0].0.as_path())
1953}
1954
1955fn resolve_binding_includes(
1962 pf: &ParsedFile,
1963 a: &AdapterDecl,
1964 b: &BindingDecl,
1965 adapter_dir: &Path,
1966 adapter_src_dir: &Path,
1967 errors: &mut ErrorSink,
1968) -> Vec<IncludedFile> {
1969 let adapter = a.name.joined();
1970 let mut seen: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
1971 let mut out = Vec::new();
1972 for inc in &b.includes {
1973 let raw = Path::new(&inc.path);
1974 let escapes = raw.is_absolute()
1975 || raw.components().any(|c| {
1976 matches!(
1977 c,
1978 std::path::Component::ParentDir
1979 | std::path::Component::RootDir
1980 | std::path::Component::Prefix(_)
1981 )
1982 });
1983 if escapes {
1984 errors.push_for(
1985 Some(&pf.identity_path()),
1986 CompileError::new(
1987 "bynk.adapter.include_outside",
1988 inc.span,
1989 format!(
1990 "adapter `{adapter}` includes `{}`, which is outside the adapter's directory",
1991 inc.path
1992 ),
1993 )
1994 .with_note("an included path is relative to the adapter's file and may not be absolute or contain `..`"),
1995 );
1996 continue;
1997 }
1998 let rel = normalize_rel(raw);
1999 if rel.extension().and_then(|e| e.to_str()) != Some("wasm") {
2000 errors.push_for(
2001 Some(&pf.identity_path()),
2002 CompileError::new(
2003 "bynk.adapter.include_kind",
2004 inc.span,
2005 format!(
2006 "adapter `{adapter}` includes `{}`, which is not a `.wasm` file",
2007 inc.path
2008 ),
2009 )
2010 .with_note("only WebAssembly modules (`.wasm`) can be included beside a binding"),
2011 );
2012 continue;
2013 }
2014 if !seen.insert(rel.clone()) {
2015 errors.push_for(
2016 Some(&pf.identity_path()),
2017 CompileError::new(
2018 "bynk.adapter.include_duplicate",
2019 inc.span,
2020 format!("adapter `{adapter}` includes `{}` more than once", inc.path),
2021 )
2022 .with_note("remove the repeated entry"),
2023 );
2024 continue;
2025 }
2026 match read_adapter_include(&adapter_src_dir.join(&rel)) {
2027 Ok(bytes) => out.push(IncludedFile {
2028 output_path: normalize_rel(&adapter_dir.join(&rel)),
2029 bytes,
2030 }),
2031 Err(e) => errors.push_for(
2032 Some(&pf.identity_path()),
2033 CompileError::new(
2034 "bynk.adapter.include_missing",
2035 inc.span,
2036 format!(
2037 "adapter `{adapter}` includes `{}`, which could not be read ({e})",
2038 inc.path
2039 ),
2040 )
2041 .with_note("the path is resolved relative to the adapter's source file"),
2042 ),
2043 }
2044 }
2045 out
2046}
2047
2048#[allow(clippy::type_complexity)]
2056#[allow(clippy::too_many_arguments)]
2057pub fn phase_group(
2058 parsed: &[ParsedFile],
2059 trees: &[(PathBuf, PathBuf)],
2060 platform: Platform,
2061 injected: &[&'static firstparty::Unit],
2062 overlay: &HashMap<PathBuf, String>,
2063 errors: &mut ErrorSink,
2064) -> (
2065 BTreeMap<String, Vec<usize>>,
2066 BTreeMap<String, UnitKind>,
2067 BTreeMap<String, Vec<usize>>,
2068 BTreeMap<String, Vec<usize>>,
2069 HashMap<String, AdapterBinding>,
2070 std::collections::BTreeMap<String, String>,
2071) {
2072 let mut groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();
2076 let mut kinds: BTreeMap<String, UnitKind> = BTreeMap::new();
2077 let mut test_groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();
2078 let mut integration_groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();
2081 for (i, pf) in parsed.iter().enumerate() {
2082 let name = pf.unit().name().joined();
2083 if pf.kind() == UnitKind::Integration {
2084 integration_groups.entry(name).or_default().push(i);
2085 } else if pf.kind() == UnitKind::Test {
2086 test_groups.entry(name).or_default().push(i);
2087 } else {
2088 groups.entry(name.clone()).or_default().push(i);
2089 kinds.entry(name).or_insert(pf.kind());
2090 }
2091 }
2092 if let Err(e) = check_directory_name_consistency(parsed) {
2096 for (path, err) in e {
2097 errors.push_for(Some(&path), err);
2098 }
2099 }
2100 if let Err(e) = check_directory_kind_consistency(parsed) {
2101 errors.extend_for(None, e);
2102 }
2103 if let Err(e) = check_group_kind_consistency(parsed, &groups) {
2106 for (path, err) in e {
2107 errors.push_for(Some(&path), err);
2108 }
2109 }
2110 if let Err(e) = check_group_module_docs(parsed, &groups) {
2113 for (path, err) in e {
2114 errors.push_for(Some(&path), err);
2115 }
2116 }
2117 if let Err(e) = check_path_name_alignment(parsed) {
2121 for (path, err) in e {
2122 errors.push_for(Some(&path), err);
2123 }
2124 }
2125
2126 phase_function_type_boundaries(parsed, errors);
2133
2134 for pf in parsed {
2137 if pf.is_synthetic() {
2138 continue;
2139 }
2140 let qn = pf.unit().name();
2141 if qn.parts.first().is_some_and(|p| p.name == "bynk") {
2142 errors.push_for(Some(&pf.identity_path()),
2143 CompileError::new(
2144 "bynk.namespace.reserved",
2145 qn.span,
2146 format!(
2147 "`{}` uses the reserved `bynk` namespace — the `bynk` root is reserved for the toolchain's conformance surface",
2148 qn.joined()
2149 ),
2150 )
2151 .with_note("rename the unit so its first segment is not `bynk`"),
2152 );
2153 }
2154 }
2155
2156 for pf in parsed {
2160 if pf.is_synthetic() {
2161 continue;
2162 }
2163 if let Some(a) = pf.adapter() {
2164 let has_external = a
2165 .items
2166 .iter()
2167 .any(|it| matches!(it, CommonsItem::Provider(p) if p.external));
2168 if has_external && a.binding.is_none() {
2169 errors.push_for(Some(&pf.identity_path()),
2170 CompileError::new(
2171 "bynk.adapter.no_binding",
2172 a.span,
2173 format!(
2174 "adapter `{}` declares an external provider but has no `binding` clause to supply its implementation",
2175 a.name.joined()
2176 ),
2177 )
2178 .with_note(
2179 "add a `binding \"<module>\"` clause naming the TypeScript module that exports the provider symbols",
2180 ),
2181 );
2182 }
2183 }
2184 }
2185
2186 let mut adapter_bindings: HashMap<String, AdapterBinding> = HashMap::new();
2190 for unit in injected {
2194 if let Some((output_path, content)) = unit.binding_for(platform) {
2195 adapter_bindings.insert(
2196 unit.name.to_string(),
2197 AdapterBinding {
2198 output_path: PathBuf::from(output_path),
2199 content: content.to_string(),
2200 includes: Vec::new(),
2201 },
2202 );
2203 }
2204 }
2205 for pf in parsed {
2206 let Some(a) = pf.adapter() else { continue };
2207 let Some(b) = &a.binding else { continue };
2208 let pf_source_path = pf.source_path();
2209 let adapter_dir = pf_source_path.parent().unwrap_or(Path::new(""));
2210 let out_rel = normalize_rel(&adapter_dir.join(&b.module));
2211 let src_abs = match (pf.package(), pf.abs_path()) {
2215 (Some(_), Some(abs)) => {
2216 let dir = abs.parent().unwrap_or(Path::new("")).to_path_buf();
2217 dir.join(normalize_rel(Path::new(&b.module)))
2218 }
2219 _ => tree_root_for(trees, pf).join(&out_rel),
2220 };
2221 match read_adapter_binding(&src_abs, overlay) {
2222 Ok(content) => {
2223 let adapter_src_dir = match (pf.package(), pf.abs_path()) {
2226 (Some(_), Some(abs)) => abs.parent().unwrap_or(Path::new("")).to_path_buf(),
2227 _ => tree_root_for(trees, pf).join(adapter_dir),
2228 };
2229 let includes =
2230 resolve_binding_includes(pf, a, b, adapter_dir, &adapter_src_dir, errors);
2231 adapter_bindings.insert(
2232 a.name.joined(),
2233 AdapterBinding {
2234 output_path: out_rel,
2235 content,
2236 includes,
2237 },
2238 );
2239 }
2240 Err(e) => {
2241 errors.push_for(Some(&pf.identity_path()),
2242 CompileError::new(
2243 "bynk.adapter.no_binding",
2244 b.module_span,
2245 format!(
2246 "adapter `{}` names binding module `{}`, which could not be read ({e})",
2247 a.name.joined(),
2248 b.module
2249 ),
2250 )
2251 .with_note(
2252 "the binding path is resolved relative to the adapter's source file; author the `.binding.ts` there",
2253 ),
2254 );
2255 }
2256 }
2257 }
2258
2259 let mut npm_deps: std::collections::BTreeMap<String, String> =
2264 std::collections::BTreeMap::new();
2265 let mut first_dep: HashMap<String, (String, PathBuf, Span)> = HashMap::new();
2267 for pf in parsed {
2268 let Some(a) = pf.adapter() else { continue };
2269 let Some(b) = &a.binding else { continue };
2270 for dep in &b.requires {
2271 if is_unpinned_range(&dep.range) {
2272 errors.push_for(Some(&pf.identity_path()),
2273 CompileError::new(
2274 "bynk.requires.unpinned_dependency",
2275 dep.span,
2276 format!(
2277 "dependency `{}` has an unpinned version range `{}` — pin a concrete range (e.g. `^1.2.0`)",
2278 dep.package, dep.range
2279 ),
2280 )
2281 .with_note(
2282 "unpinned ranges (`*`, `latest`, …) make builds irreproducible and are rejected",
2283 ),
2284 );
2285 continue;
2286 }
2287 let adapter = a.name.joined();
2288 let identity = pf.identity_path();
2289 if conflicts_with_first_party_pin(dep, &adapter, &identity, errors) {
2290 continue;
2291 }
2292 if let Some(range) = npm_deps.get(&dep.package) {
2293 if *range != dep.range {
2294 let (first_adapter, first_path, first_span) = &first_dep[&dep.package];
2295 let message = if *first_adapter == adapter {
2296 format!(
2297 "adapter `{adapter}` requires `{}` at both `{range}` and `{}`",
2298 dep.package, dep.range
2299 )
2300 } else {
2301 format!(
2302 "adapter `{adapter}` requires `{}` at `{}`, but adapter `{first_adapter}` requires it at `{range}`",
2303 dep.package, dep.range
2304 )
2305 };
2306 let mut err =
2307 CompileError::new("bynk.requires.conflicting_range", dep.span, message);
2308 if *first_path == identity {
2309 err = err.with_label(*first_span, "first required here");
2310 }
2311 errors.push_for(
2312 Some(&identity),
2313 err.with_note(format!(
2314 "`{}` is first required at `{range}` by adapter `{first_adapter}` (in `{}`); the project installs one version of each package, so every adapter must state the same range",
2315 dep.package,
2316 first_path
2317 .components()
2318 .map(|c| c.as_os_str().to_string_lossy())
2319 .collect::<Vec<_>>()
2320 .join("/")
2321 )),
2322 );
2323 }
2324 continue;
2325 }
2326 first_dep.insert(dep.package.clone(), (adapter, identity, dep.span));
2327 npm_deps.insert(dep.package.clone(), dep.range.clone());
2328 }
2329 }
2330
2331 (
2332 groups,
2333 kinds,
2334 test_groups,
2335 integration_groups,
2336 adapter_bindings,
2337 npm_deps,
2338 )
2339}
2340
2341fn conflicts_with_first_party_pin(
2345 dep: &bynk_syntax::ast::RequiresDep,
2346 adapter: &str,
2347 identity: &Path,
2348 errors: &mut ErrorSink,
2349) -> bool {
2350 let Some(pin) = crate::firstparty::FIRST_PARTY_NPM
2351 .iter()
2352 .find(|p| p.package == dep.package && p.version != dep.range)
2353 else {
2354 return false;
2355 };
2356 errors.push_for(
2357 Some(identity),
2358 CompileError::new(
2359 "bynk.requires.conflicting_range",
2360 dep.span,
2361 format!(
2362 "adapter `{adapter}` requires `{}` at `{}`, but the toolchain pins it at `{}`",
2363 dep.package, dep.range, pin.version
2364 ),
2365 )
2366 .with_note(
2367 "the toolchain's own binding uses this package at an exact version; an adapter that needs it must require that version",
2368 ),
2369 );
2370 true
2371}
2372
2373pub fn phase_function_type_boundaries(parsed: &[ParsedFile], errors: &mut ErrorSink) {
2395 let types = collect_type_decls(parsed.iter().flat_map(|pf| pf.items()));
2400 for pf in parsed {
2401 let mut file_errors: Vec<CompileError> = Vec::new();
2402 check_function_type_boundary_items(pf.items(), &types, &mut file_errors);
2403 for err in file_errors {
2404 errors.push_for(Some(&pf.identity_path()), err);
2405 }
2406 }
2407}
2408
2409pub fn collect_type_decls<'a>(
2415 items: impl Iterator<Item = &'a CommonsItem>,
2416) -> HashMap<String, Arc<TypeDecl>> {
2417 let mut out = HashMap::new();
2418 for item in items {
2419 match item {
2420 CommonsItem::Type(t) => {
2421 out.entry(t.name.name.clone())
2422 .or_insert_with(|| Arc::new(t.clone()));
2423 }
2424 CommonsItem::Event(e) => {
2428 out.entry(e.name.name.clone())
2429 .or_insert_with(|| Arc::new(e.as_type_decl()));
2430 }
2431 _ => {}
2432 }
2433 }
2434 out
2435}
2436
2437fn check_polymorphic_recursion(
2442 decl: &TypeDecl,
2443 types: &HashMap<String, Arc<TypeDecl>>,
2444 errors: &mut Vec<CompileError>,
2445) {
2446 for (callee, span) in bynk_syntax::ast::polymorphic_recursion_edges(decl, types) {
2447 let name = &decl.name.name;
2448 let params = decl
2449 .type_params
2450 .iter()
2451 .map(|p| p.name.name.as_str())
2452 .collect::<Vec<_>>()
2453 .join(", ");
2454 let note = if callee == *name {
2455 format!(
2456 "a recursive generic type must pass its parameters through unchanged, as `{callee}[{params}]`"
2457 )
2458 } else {
2459 format!(
2460 "a mutually recursive generic may be applied only to `{name}`'s own type parameters ({params}) or to types that mention none; wrapping a parameter (`List[T]`) makes the set of instantiations unbounded"
2461 )
2462 };
2463 errors.push(
2464 CompileError::new(
2465 "bynk.generics.polymorphic_recursion",
2466 span,
2467 format!(
2468 "`{name}` refers to `{callee}` with arguments other than its own type parameters — polymorphic recursion generates an unbounded set of instantiations"
2469 ),
2470 )
2471 .with_note(note),
2472 );
2473 }
2474}
2475
2476pub fn check_function_type_boundary_items(
2480 items: &[CommonsItem],
2481 types: &HashMap<String, Arc<TypeDecl>>,
2482 errors: &mut Vec<CompileError>,
2483) {
2484 for item in items {
2485 match item {
2486 CommonsItem::Type(t) => match &t.body {
2487 TypeBody::Record(r) => {
2488 check_polymorphic_recursion(t, types, errors);
2489 for f in &r.fields {
2490 reject_fn_types(&f.type_ref, RECORD_FIELD, types, errors);
2491 }
2492 }
2493 TypeBody::Sum(s) => {
2494 check_polymorphic_recursion(t, types, errors);
2495 for v in &s.variants {
2496 for p in &v.payload {
2497 reject_fn_types(&p.type_ref, SUM_PAYLOAD, types, errors);
2498 }
2499 }
2500 }
2501 TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
2502 },
2503 CommonsItem::Event(e) => {
2507 for f in &e.body.fields {
2508 reject_fn_types(&f.type_ref, "an event field", types, errors);
2509 }
2510 }
2511 CommonsItem::Capability(c) => {
2512 for op in &c.ops {
2513 for p in &op.params {
2514 reject_fn_types(&p.type_ref, CAPABILITY_SIGNATURE, types, errors);
2515 }
2516 if !type_ref_is_held(&op.return_type) {
2520 reject_fn_types(&op.return_type, CAPABILITY_SIGNATURE, types, errors);
2521 }
2522 }
2523 }
2524 CommonsItem::Service(s) => {
2525 for h in &s.handlers {
2526 for p in &h.params {
2527 let http_headers = matches!(h.kind, HandlerKind::Http { .. })
2530 && ((p.name.name == "headers"
2531 && matches!(p.type_ref, TypeRef::RequestHeaders(_)))
2532 || (p.name.name == "query"
2534 && matches!(p.type_ref, TypeRef::RequestQuery(_)))
2535 || (p.name.name == "cookies"
2537 && matches!(p.type_ref, TypeRef::RequestCookies(_))));
2538 let http_headers = http_headers
2541 || (h.kind == HandlerKind::Rejected
2542 && matches!(p.type_ref, TypeRef::BoundaryRejection(_)));
2543 if matches!(p.type_ref, TypeRef::RequestQuery(_))
2550 && !matches!(h.kind, HandlerKind::Http { .. })
2551 {
2552 errors.push(
2553 CompileError::new(
2554 "bynk.http.query_not_http",
2555 p.type_ref.span(),
2556 "`RequestQuery` is the query string of an HTTP request, so only an `on http` handler's `query` parameter can have it",
2557 )
2558 .with_note("a handler that is not an HTTP route has no query string to read"),
2559 );
2560 continue;
2561 }
2562 if matches!(p.type_ref, TypeRef::RequestCookies(_))
2565 && !matches!(h.kind, HandlerKind::Http { .. })
2566 {
2567 errors.push(
2568 CompileError::new(
2569 "bynk.http.cookies_not_http",
2570 p.type_ref.span(),
2571 "`RequestCookies` is the cookies of an HTTP request, so only an `on http` handler's `cookies` parameter can have it",
2572 )
2573 .with_note("a handler that is not an HTTP route has no cookies to read"),
2574 );
2575 continue;
2576 }
2577 let multipart_body = p.name.name == "body"
2580 && h.annotations.iter().any(|a| a.name.name == "multipart");
2581 let request_record = matches!(h.kind, HandlerKind::Http { .. })
2584 && (matches!(p.name.name.as_str(), "cookies" | "query")
2585 || (p.name.name == "body"
2586 && h.annotations.iter().any(|a| a.name.name == "form")));
2587 let is_http_body = matches!(h.kind, HandlerKind::Http { .. })
2592 && p.name.name == "body";
2593 let has_raw = h.annotations.iter().any(|a| a.name.name == "raw");
2594 let streamed_body = is_http_body
2597 && matches!(p.type_ref, TypeRef::Stream(..))
2598 && has_raw;
2599 if is_http_body
2600 && crate::context_checks::is_byte_stream(&p.type_ref)
2601 && !has_raw
2602 {
2603 errors.push(
2604 CompileError::new(
2605 "bynk.http.stream_body_not_raw",
2606 p.type_ref.span(),
2607 "a `Stream[Bytes]` `body` needs `@raw`",
2608 )
2609 .with_note(
2610 "a request body has a JSON wire form unless the route says otherwise; write `@raw(contentType: \"…\")` and a `@limit` to receive it as a stream",
2611 ),
2612 );
2613 continue;
2614 }
2615 if streamed_body {
2616 continue;
2617 }
2618 if !type_ref_is_held(&p.type_ref) && !http_headers && !multipart_body {
2619 let what = if request_record {
2622 REQUEST_RECORD_PARAM
2623 } else {
2624 "a service handler signature"
2625 };
2626 reject_fn_types(&p.type_ref, what, types, errors);
2627 }
2628 }
2629 reject_fn_types(&h.return_type, "a service handler signature", types, errors);
2630 }
2631 }
2632 CommonsItem::Agent(a) => {
2633 reject_fn_types(&a.key_type, "an agent key", types, errors);
2634 for f in &a.store_fields {
2635 validate_store_field_value_types(f, types, errors);
2636 }
2637 for h in &a.handlers {
2638 for p in &h.params {
2639 if !type_ref_is_held(&p.type_ref) {
2642 reject_fn_types(
2643 &p.type_ref,
2644 "an agent handler signature",
2645 types,
2646 errors,
2647 );
2648 }
2649 }
2650 reject_fn_types(&h.return_type, "an agent handler signature", types, errors);
2651 }
2652 }
2653 CommonsItem::Actor(a) => {
2654 if let Some(id) = &a.identity {
2655 reject_fn_types(id, "an actor identity type", types, errors);
2656 }
2657 }
2658 CommonsItem::Fn(_)
2661 | CommonsItem::Provider(_)
2662 | CommonsItem::Messages(_)
2663 | CommonsItem::Asset(_)
2664 | CommonsItem::Embed(_)
2665 | CommonsItem::Const(_) => {}
2668 }
2669 }
2670}
2671
2672pub fn phase_symbol_tables(
2675 groups: &BTreeMap<String, Vec<usize>>,
2676 kinds: &BTreeMap<String, UnitKind>,
2677 parsed: &[ParsedFile],
2678 errors: &mut ErrorSink,
2679) -> HashMap<String, UnitTable> {
2680 let mut unit_tables: HashMap<String, UnitTable> = HashMap::new();
2681 for (name, indices) in groups {
2682 let kind = *kinds.get(name).expect("every group has a kind");
2683 let mut table_errors: Vec<(PathBuf, CompileError)> = Vec::new();
2685 let table = build_unit_table(name, kind, indices, parsed, &mut table_errors);
2686 for (path, err) in table_errors {
2687 errors.push_for(Some(&path), err);
2688 }
2689 unit_tables.insert(name.clone(), table);
2690 }
2691 unit_tables
2692}
2693
2694pub fn uses_first_order<'a, I>(
2704 names: I,
2705 unit_uses: &HashMap<String, Vec<String>>,
2706) -> Vec<&'a String>
2707where
2708 I: IntoIterator<Item = &'a String>,
2709{
2710 let names: BTreeSet<&String> = names.into_iter().collect();
2711 let mut placed: HashSet<&String> = HashSet::new();
2712 let mut order = Vec::with_capacity(names.len());
2713 loop {
2714 let ready: Vec<&String> = names
2715 .iter()
2716 .copied()
2717 .filter(|n| !placed.contains(n))
2718 .filter(|n| {
2719 unit_uses.get(*n).is_none_or(|deps| {
2720 deps.iter()
2721 .all(|d| !names.contains(d) || placed.iter().any(|p| *p == d))
2722 })
2723 })
2724 .collect();
2725 if ready.is_empty() {
2726 break;
2727 }
2728 for n in ready {
2729 placed.insert(n);
2730 order.push(n);
2731 }
2732 }
2733 order.extend(names.iter().copied().filter(|n| !placed.contains(n)));
2734 order
2735}
2736
2737pub fn phase_tables_uses_consts(
2742 groups: &BTreeMap<String, Vec<usize>>,
2743 kinds: &BTreeMap<String, UnitKind>,
2744 parsed: &mut [ParsedFile],
2745 policy: &crate::stability::StabilityPolicy,
2746 errors: &mut ErrorSink,
2747 refs: &mut RefSink,
2748) -> (HashMap<String, UnitTable>, HashMap<String, Vec<String>>) {
2749 let mut unit_tables = phase_symbol_tables(groups, kinds, parsed, errors);
2750 let unit_uses = phase_resolve_uses(groups, kinds, parsed, &unit_tables, policy, errors);
2751 crate::annotation_consts::resolve_annotation_consts(
2752 groups,
2753 kinds,
2754 parsed,
2755 &mut unit_tables,
2756 &unit_uses,
2757 refs,
2758 );
2759 (unit_tables, unit_uses)
2760}
2761
2762pub fn phase_resolve_uses(
2763 groups: &BTreeMap<String, Vec<usize>>,
2764 kinds: &BTreeMap<String, UnitKind>,
2765 parsed: &[ParsedFile],
2766 unit_tables: &HashMap<String, UnitTable>,
2767 policy: &crate::stability::StabilityPolicy,
2769 errors: &mut ErrorSink,
2770) -> HashMap<String, Vec<String>> {
2771 let mut unit_uses: HashMap<String, Vec<String>> = HashMap::new();
2772 for (name, indices) in groups {
2773 let mut uses_targets: Vec<String> = Vec::new();
2774 for &i in indices {
2775 for u in parsed[i].uses() {
2776 let target = u.target.joined();
2777 if !unit_tables.contains_key(&target) {
2778 errors.push_for(
2779 Some(&parsed[i].identity_path()),
2780 CompileError::new(
2781 "bynk.uses.unknown_commons",
2782 u.span,
2783 format!("unknown commons `{target}`"),
2784 )
2785 .with_note(
2786 "the target of a `uses` clause must be a commons in the project",
2787 ),
2788 );
2789 continue;
2790 }
2791 if !parsed[i].is_synthetic()
2794 && let Some(err) = policy.check(&target, u.target.span)
2795 {
2796 errors.push_for(Some(&parsed[i].identity_path()), err);
2797 }
2798 let target_kind = *kinds.get(&target).unwrap();
2799 if target_kind != UnitKind::Commons {
2800 errors.push_for(Some(&parsed[i].identity_path()),
2801 CompileError::new(
2802 "bynk.uses.target_is_context",
2803 u.span,
2804 format!(
2805 "`uses {target}` targets a context — `uses` may only target a commons"
2806 ),
2807 )
2808 .with_note(
2809 "to declare a dependency on a context, use `consumes` instead",
2810 ),
2811 );
2812 continue;
2813 }
2814 if target == *name {
2815 errors.push_for(
2816 Some(&parsed[i].identity_path()),
2817 CompileError::new(
2818 "bynk.uses.self_reference",
2819 u.span,
2820 format!("`{name}` cannot `uses` itself"),
2821 ),
2822 );
2823 continue;
2824 }
2825 if !uses_targets.contains(&target) {
2826 uses_targets.push(target);
2827 }
2828 }
2829 }
2830 unit_uses.insert(name.clone(), uses_targets);
2831 }
2832 unit_uses
2833}
2834
2835pub fn consume_selections(
2840 groups: &BTreeMap<String, Vec<usize>>,
2841 kinds: &BTreeMap<String, UnitKind>,
2842 parsed: &[ParsedFile],
2843) -> crate::symbols::ConsumeSelections {
2844 let mut out = HashMap::new();
2845 for (name, indices) in groups {
2846 if !matches!(kinds.get(name), Some(UnitKind::Context | UnitKind::Adapter)) {
2847 continue;
2848 }
2849 let clauses: Vec<(String, Option<Vec<String>>)> = indices
2850 .iter()
2851 .flat_map(|&i| parsed[i].consumes())
2852 .map(|c| {
2853 let names = c
2854 .selected
2855 .as_ref()
2856 .map(|items| items.iter().map(|n| n.name.name.clone()).collect());
2857 (c.target.joined(), names)
2858 })
2859 .collect();
2860 out.insert(name.clone(), clauses);
2861 }
2862 out
2863}
2864
2865#[allow(clippy::type_complexity)]
2871pub fn phase_resolve_consumes(
2872 groups: &BTreeMap<String, Vec<usize>>,
2873 kinds: &BTreeMap<String, UnitKind>,
2874 parsed: &[ParsedFile],
2875 unit_tables: &HashMap<String, UnitTable>,
2876 policy: &crate::stability::StabilityPolicy,
2879 errors: &mut ErrorSink,
2880 refs: &mut RefSink,
2881) -> (
2882 HashMap<String, Vec<String>>,
2883 HashMap<String, HashMap<String, String>>,
2884 HashMap<String, HashMap<String, crate::symbols::ConsumedTypeAlias>>,
2885) {
2886 let mut unit_consumes: HashMap<String, Vec<String>> = HashMap::new();
2887 let mut unit_type_aliases: HashMap<String, HashMap<String, crate::symbols::ConsumedTypeAlias>> =
2889 HashMap::new();
2890 let mut unit_flattened: HashMap<String, HashMap<String, String>> = HashMap::new();
2893 let exports_type = |target: &str, name: &str| {
2895 groups.get(target).is_some_and(|files| {
2896 files.iter().any(|&j| {
2897 parsed[j].exports().iter().any(|clause| {
2898 matches!(clause.kind, ExportKind::Type(_))
2899 && clause.names.iter().any(|e| e.name.name == name)
2900 })
2901 })
2902 })
2903 };
2904 let mut type_selected: HashSet<(usize, String, String)> = HashSet::new();
2907 for (name, indices) in groups {
2908 let kind = *kinds.get(name).unwrap();
2909 let mut consumes_targets: Vec<String> = Vec::new();
2910 let mut flattened: HashMap<String, String> = HashMap::new();
2911 let mut flattened_in: HashMap<String, usize> = HashMap::new();
2914 let mut type_aliases: HashMap<String, crate::symbols::ConsumedTypeAlias> = HashMap::new();
2919 let mut alias_of: HashMap<(String, String), (String, usize)> = HashMap::new();
2920 let mut bare_types: HashSet<(String, String)> = HashSet::new();
2921 let mut alias_sites: HashMap<String, (usize, Span)> = HashMap::new();
2922 let local_caps: HashSet<String> = unit_tables
2923 .get(name)
2924 .map(|t| t.capabilities.keys().cloned().collect())
2925 .unwrap_or_default();
2926 for &i in indices {
2927 refs.enter_file(&parsed[i].identity_path(), name, parsed[i].is_synthetic());
2928 for c in parsed[i].consumes() {
2929 let target = c.target.joined();
2930 let selects_only_types = c.selected.as_ref().is_some_and(|names| {
2936 let caps = unit_tables.get(&target).map(|t| &t.exported_capabilities);
2937 !names.is_empty()
2938 && names.iter().all(|n| {
2939 !caps.is_some_and(|c| c.contains(&n.name.name))
2940 && exports_type(&target, &n.name.name)
2941 })
2942 });
2943 if kind == UnitKind::Adapter && (c.selected.is_none() || selects_only_types) {
2944 errors.push_for(Some(&parsed[i].identity_path()),
2945 CompileError::new(
2946 "bynk.adapter.consumes_requires_selection",
2947 c.span,
2948 format!(
2949 "an adapter's `consumes` must select capabilities — write `consumes {target} {{ Cap, … }}`",
2950 ),
2951 )
2952 .with_note(
2953 "adapters depend on capabilities, never on services; the whole-unit and aliased forms are context-only",
2954 ),
2955 );
2956 continue;
2957 }
2958 if !unit_tables.contains_key(&target) {
2959 errors.push_for(
2960 Some(&parsed[i].identity_path()),
2961 CompileError::new(
2962 "bynk.consumes.unknown_context",
2963 c.span,
2964 format!("unknown context `{target}`"),
2965 )
2966 .with_note(
2967 "the target of a `consumes` clause must be a context in the project",
2968 ),
2969 );
2970 continue;
2971 }
2972 let target_kind = *kinds.get(&target).unwrap();
2973 if target_kind != UnitKind::Context && target_kind != UnitKind::Adapter {
2976 errors.push_for(Some(&parsed[i].identity_path()),
2977 CompileError::new(
2978 "bynk.consumes.target_is_commons",
2979 c.span,
2980 format!(
2981 "`consumes {target}` targets a commons — `consumes` may only target a context or adapter"
2982 ),
2983 )
2984 .with_note(
2985 "to mix in declarations from a commons, use `uses` instead",
2986 ),
2987 );
2988 continue;
2989 }
2990 if kind == UnitKind::Adapter && target_kind == UnitKind::Context {
2994 errors.push_for(Some(&parsed[i].identity_path()),
2995 CompileError::new(
2996 "bynk.adapter.consumes_context",
2997 c.span,
2998 format!(
2999 "adapter `{name}` cannot `consumes` the context `{target}` — adapter dependencies are adapter-to-adapter"
3000 ),
3001 )
3002 .with_note(
3003 "an adapter may only depend on capabilities exported by other adapters (e.g. the `bynk` surface)",
3004 ),
3005 );
3006 continue;
3007 }
3008 if target == *name {
3009 let kind_word = if kind == UnitKind::Adapter {
3010 "adapter"
3011 } else {
3012 "context"
3013 };
3014 errors.push_for(
3015 Some(&parsed[i].identity_path()),
3016 CompileError::new(
3017 "bynk.consumes.self_reference",
3018 c.span,
3019 format!("{kind_word} `{name}` cannot `consumes` itself"),
3020 ),
3021 );
3022 continue;
3023 }
3024 if !parsed[i].is_synthetic()
3025 && let Some(err) = policy.check(&target, c.target.span)
3026 {
3027 errors.push_for(Some(&parsed[i].identity_path()), err);
3028 }
3029 if let Some(names) = &c.selected {
3033 let exported = unit_tables
3034 .get(&target)
3035 .map(|t| &t.exported_capabilities)
3036 .cloned()
3037 .unwrap_or_default();
3038 for item in names {
3039 let cap = &item.name;
3040 if !parsed[i].is_synthetic()
3041 && let Some(err) =
3042 policy.check(&format!("{target}.{}", cap.name), cap.span)
3043 {
3044 errors.push_for(Some(&parsed[i].identity_path()), err);
3045 }
3046 if let Some(alias) = &item.alias {
3052 let key = (target.clone(), cap.name.clone());
3053 let refuse =
3054 |code: &'static str, span: Span, msg: String, note: String| {
3055 CompileError::new(code, span, msg).with_note(note)
3056 };
3057 if exported.contains(&cap.name) {
3058 errors.push_for(
3059 Some(&parsed[i].identity_path()),
3060 refuse(
3061 "bynk.consumes.type_alias_capability",
3062 alias.span,
3063 format!(
3064 "`{}` is a capability of `{target}`; only exported types can be aliased",
3065 cap.name
3066 ),
3067 "a capability keeps its own name: select it bare (`consumes U { Cap }`), or qualify it as `given U.Cap`".to_string(),
3068 ),
3069 );
3070 continue;
3071 }
3072 if !exports_type(&target, &cap.name) {
3073 errors.push_for(
3074 Some(&parsed[i].identity_path()),
3075 refuse(
3076 "bynk.consumes.type_alias_unknown_export",
3077 cap.span,
3078 format!(
3079 "`{target}` does not export a type named `{}`, so there is nothing to alias",
3080 cap.name
3081 ),
3082 "only an exported type can be aliased: `consumes U { Type as Alias }`".to_string(),
3083 ),
3084 );
3085 continue;
3086 }
3087 if !type_selected.insert((i, target.clone(), cap.name.clone())) {
3088 errors.push_for(
3089 Some(&parsed[i].identity_path()),
3090 refuse(
3091 "bynk.consumes.type_alias_repeated",
3092 cap.span,
3093 format!(
3094 "`{}` is selected from `{target}` more than once in this file",
3095 cap.name
3096 ),
3097 "a type is aliased once; remove the repeat".to_string(),
3098 ),
3099 );
3100 continue;
3101 }
3102 if let Some((prev, prev_file)) = alias_of.get(&key)
3103 && (*prev != alias.name || *prev_file == i)
3104 {
3105 errors.push_for(
3106 Some(&parsed[i].identity_path()),
3107 refuse(
3108 "bynk.consumes.type_alias_repeated",
3109 alias.span,
3110 format!(
3111 "`{}` from `{target}` is already aliased as `{prev}`",
3112 cap.name
3113 ),
3114 "a type is in scope under one alias; remove one of them"
3115 .to_string(),
3116 ),
3117 );
3118 continue;
3119 }
3120 if bare_types.contains(&key) {
3121 errors.push_for(
3122 Some(&parsed[i].identity_path()),
3123 refuse(
3124 "bynk.consumes.type_alias_repeated",
3125 alias.span,
3126 format!(
3127 "`{}` from `{target}` is selected both bare and aliased",
3128 cap.name
3129 ),
3130 "the type is in scope as the alias only; drop the bare selection".to_string(),
3131 ),
3132 );
3133 continue;
3134 }
3135 let this = crate::symbols::ConsumedTypeAlias {
3136 target: target.clone(),
3137 original: cap.name.clone(),
3138 };
3139 if let Some(other) = type_aliases.get(&alias.name)
3140 && *other != this
3141 {
3142 errors.push_for(
3143 Some(&parsed[i].identity_path()),
3144 refuse(
3145 "bynk.consumes.type_alias_conflict",
3146 alias.span,
3147 format!(
3148 "alias `{}` already names `{}` from `{}`",
3149 alias.name, other.original, other.target
3150 ),
3151 "give each aliased type its own name".to_string(),
3152 ),
3153 );
3154 continue;
3155 }
3156 alias_sites
3157 .entry(alias.name.clone())
3158 .or_insert((i, alias.span));
3159 alias_of.insert(key, (alias.name.clone(), i));
3160 type_aliases.insert(alias.name.clone(), this);
3161 refs.record_in_unit(cap.span, SymbolKind::Type, &cap.name, &target);
3163 refs.record_in_unit(alias.span, SymbolKind::Type, &cap.name, &target);
3164 continue;
3165 }
3166 if !exported.contains(&cap.name) && exports_type(&target, &cap.name) {
3167 if alias_of.contains_key(&(target.clone(), cap.name.clone())) {
3168 errors.push_for(
3169 Some(&parsed[i].identity_path()),
3170 CompileError::new(
3171 "bynk.consumes.type_alias_repeated",
3172 cap.span,
3173 format!(
3174 "`{}` from `{target}` is selected both bare and aliased",
3175 cap.name
3176 ),
3177 )
3178 .with_note("the type is in scope as the alias only; drop the bare selection"),
3179 );
3180 continue;
3181 }
3182 bare_types.insert((target.clone(), cap.name.clone()));
3183 if !type_selected.insert((i, target.clone(), cap.name.clone())) {
3184 errors.push_for(
3185 Some(&parsed[i].identity_path()),
3186 CompileError::new(
3187 "bynk.consumes.capability_name_clash",
3188 cap.span,
3189 format!(
3190 "`{}` is selected from `{target}` more than once in this file",
3191 cap.name
3192 ),
3193 ),
3194 );
3195 continue;
3196 }
3197 refs.record_in_unit(cap.span, SymbolKind::Type, &cap.name, &target);
3198 continue;
3199 }
3200 if !exported.contains(&cap.name) {
3201 errors.push_for(
3202 Some(&parsed[i].identity_path()),
3203 CompileError::new(
3204 "bynk.given.cross_context_unknown_capability",
3205 cap.span,
3206 format!(
3207 "`{target}` does not export a capability named `{}`",
3208 cap.name
3209 ),
3210 ),
3211 );
3212 continue;
3213 }
3214 if local_caps.contains(&cap.name) {
3215 errors.push_for(Some(&parsed[i].identity_path()), CompileError::new(
3216 "bynk.consumes.capability_name_clash",
3217 cap.span,
3218 format!(
3219 "flattened capability `{}` clashes with a capability declared locally — use qualified `given {target}.{}` instead",
3220 cap.name, cap.name
3221 ),
3222 ));
3223 continue;
3224 }
3225 if let Some(prev) = flattened.get(&cap.name) {
3226 if *prev == target && flattened_in.get(&cap.name) != Some(&i) {
3229 refs.record_in_unit(
3230 cap.span,
3231 SymbolKind::Capability,
3232 &cap.name,
3233 &target,
3234 );
3235 continue;
3236 }
3237 errors.push_for(Some(&parsed[i].identity_path()), CompileError::new(
3238 "bynk.consumes.capability_name_clash",
3239 cap.span,
3240 format!(
3241 "capability `{}` is flattened from both `{prev}` and `{target}` — qualify one with `given U.{}`",
3242 cap.name, cap.name
3243 ),
3244 ));
3245 continue;
3246 }
3247 refs.record_in_unit(cap.span, SymbolKind::Capability, &cap.name, &target);
3250 flattened.insert(cap.name.clone(), target.clone());
3251 flattened_in.insert(cap.name.clone(), i);
3252 }
3253 }
3254 if !consumes_targets.contains(&target) {
3255 consumes_targets.push(target);
3256 }
3257 }
3258 }
3259 unit_consumes.insert(name.clone(), consumes_targets);
3260 let mut clashing: Vec<&String> = type_aliases
3264 .keys()
3265 .filter(|a| flattened.contains_key(*a) || local_caps.contains(*a))
3266 .collect();
3267 clashing.sort();
3268 for alias in clashing {
3269 let (file, span) = alias_sites[alias];
3270 errors.push_for(
3271 Some(&parsed[file].identity_path()),
3272 CompileError::new(
3273 "bynk.consumes.type_alias_conflict",
3274 span,
3275 format!("alias `{alias}` is also the name of a capability in this context"),
3276 )
3277 .with_note("choose an alias that is not a capability's name"),
3278 );
3279 }
3280 unit_flattened.insert(name.clone(), flattened);
3281 if !type_aliases.is_empty() {
3282 unit_type_aliases.insert(name.clone(), type_aliases);
3283 }
3284 }
3285 (unit_consumes, unit_flattened, unit_type_aliases)
3286}
3287
3288pub fn phase_consumes_aliases(
3293 groups: &BTreeMap<String, Vec<usize>>,
3294 kinds: &BTreeMap<String, UnitKind>,
3295 parsed: &[ParsedFile],
3296 unit_tables: &HashMap<String, UnitTable>,
3297 errors: &mut ErrorSink,
3298) -> HashMap<String, HashMap<String, String>> {
3299 let mut unit_consumes_aliases: HashMap<String, HashMap<String, String>> = HashMap::new();
3300 for (name, indices) in groups {
3301 let kind = *kinds.get(name).unwrap();
3302 if kind != UnitKind::Context {
3303 continue;
3304 }
3305 let mut aliases: HashMap<String, String> = HashMap::new();
3306 let mut by_alias: HashMap<String, (String, usize, Span)> = HashMap::new();
3312 let mut by_target: HashMap<String, (String, usize, Span)> = HashMap::new();
3313 for &i in indices {
3314 for c in parsed[i].consumes() {
3315 let Some(alias) = &c.alias else { continue };
3316 let target = c.target.joined();
3317 if !unit_tables.contains_key(&target) {
3318 continue;
3320 }
3321 let first = by_alias
3324 .get(&alias.name)
3325 .filter(|(t, f, _)| *t != target || *f == i)
3326 .map(|(t, f, sp)| {
3327 let what = if *t == target {
3328 "the same clause appears earlier in this file".to_string()
3329 } else {
3330 format!("alias `{}` already names `{t}`", alias.name)
3331 };
3332 (what, *f, *sp)
3333 })
3334 .or_else(|| {
3335 by_target
3336 .get(&target)
3337 .filter(|(a, _, _)| *a != alias.name)
3338 .map(|(a, f, sp)| {
3339 (format!("`{target}` is already consumed as `{a}`"), *f, *sp)
3340 })
3341 });
3342 if let Some((what, prev_file, prev_span)) = first {
3343 let where_ = if prev_file == i {
3346 String::new()
3347 } else {
3348 format!(
3351 " (first stated in `{}`)",
3352 parsed[prev_file]
3353 .identity_path()
3354 .components()
3355 .map(|c| c.as_os_str().to_string_lossy())
3356 .collect::<Vec<_>>()
3357 .join("/")
3358 )
3359 };
3360 let mut err = CompileError::new(
3361 "bynk.consumes.alias_conflict",
3362 alias.span,
3363 format!(
3364 "`consumes {target} as {}` conflicts with another `consumes` clause in context `{name}`: {what}{where_}",
3365 alias.name
3366 ),
3367 );
3368 if prev_file == i {
3369 err = err.with_label(prev_span, "previously defined here");
3370 }
3371 errors.push_for(
3372 Some(&parsed[i].identity_path()),
3373 err.with_note(
3374 "a context may consume a unit under one alias, and an alias may name one unit; repeating the same clause in another file is fine",
3375 ),
3376 );
3377 continue;
3378 }
3379 if by_alias.contains_key(&alias.name) {
3380 continue;
3382 }
3383 aliases.insert(alias.name.clone(), target.clone());
3384 by_alias.insert(alias.name.clone(), (target.clone(), i, alias.span));
3385 by_target.insert(target, (alias.name.clone(), i, alias.span));
3386 }
3387 }
3388 unit_consumes_aliases.insert(name.clone(), aliases);
3389 }
3390
3391 for (name, aliases) in &unit_consumes_aliases {
3394 let Some(local) = unit_tables.get(name) else {
3395 continue;
3396 };
3397 for alias in aliases.keys() {
3398 let alias_site = parsed_alias_span(parsed, &groups[name], alias);
3399 let alias_span = alias_site.map(|(_, s)| s).unwrap_or_default();
3400 let alias_file = alias_site.map(|(i, _)| parsed[i].identity_path());
3401 let conflict_kind = if local.types.contains_key(alias) {
3402 Some("type")
3403 } else if local.fns.contains_key(alias) {
3404 Some("function")
3405 } else if local.capabilities.contains_key(alias) {
3406 Some("capability")
3407 } else if local.services.contains_key(alias) {
3408 Some("service")
3409 } else if local.agents.contains_key(alias) {
3410 Some("agent")
3411 } else {
3412 None
3413 };
3414 if let Some(kind) = conflict_kind {
3415 errors.push_for(alias_file.as_deref(),
3416 CompileError::new(
3417 "bynk.consumes.alias_conflict",
3418 alias_span,
3419 format!(
3420 "alias `{alias}` conflicts with a local {kind} of the same name in context `{name}`",
3421 ),
3422 )
3423 .with_note(
3424 "pick a different alias for the `consumes` clause, or rename the local declaration",
3425 ),
3426 );
3427 }
3428 }
3429 }
3430 unit_consumes_aliases
3431}
3432
3433pub fn phase_private_in_public(
3446 parsed: &[ParsedFile],
3447 groups: &BTreeMap<String, Vec<usize>>,
3448 errors: &mut ErrorSink,
3449) {
3450 for (unit, indices) in groups {
3451 let mut private_types: HashSet<String> = HashSet::new();
3452 let mut type_params: HashMap<String, Vec<TypeParam>> = HashMap::new();
3453 for &i in indices {
3454 for item in parsed[i].items() {
3455 if let CommonsItem::Type(t) = item {
3456 if t.private.is_some() {
3457 private_types.insert(t.name.name.clone());
3458 }
3459 type_params.insert(t.name.name.clone(), t.type_params.clone());
3460 }
3461 }
3462 }
3463 if private_types.is_empty() {
3464 continue;
3465 }
3466 for &i in indices {
3467 let file = parsed[i].identity_path();
3468 let mut report = |at: Span, decl: &str, ty: &str| {
3469 errors.push_for(
3470 Some(&file),
3471 CompileError::new(
3472 "bynk.visibility.private_in_public",
3473 at,
3474 format!("public {decl} names `{ty}`, a private type of `{unit}`"),
3475 )
3476 .with_note(format!(
3477 "a unit that uses `{unit}` could neither name nor build a `{ty}`; make `{ty}` public, or mark the declaration `private` too"
3478 )),
3479 );
3480 };
3481 let first_private = |r: &TypeRef, vars: &HashSet<&str>| -> Option<String> {
3482 let mut names = Vec::new();
3483 type_ref_names(r, vars, &mut names);
3484 names.into_iter().find(|n| private_types.contains(n))
3485 };
3486 for item in parsed[i].items() {
3487 match item {
3488 CommonsItem::Fn(f) if f.private.is_none() => {
3489 let (decl, attached) = match &f.name {
3490 FnName::Free(id) => (format!("function `{}`", id.name), &[][..]),
3491 FnName::Method {
3492 type_name,
3493 method_name,
3494 } => {
3495 if private_types.contains(&type_name.name) {
3496 continue;
3497 }
3498 (
3499 format!("method `{}.{}`", type_name.name, method_name.name),
3500 type_params
3501 .get(&type_name.name)
3502 .map(Vec::as_slice)
3503 .unwrap_or_default(),
3504 )
3505 }
3506 };
3507 let vars: HashSet<&str> = f
3508 .type_params
3509 .iter()
3510 .chain(attached)
3511 .map(|p| p.name.name.as_str())
3512 .collect();
3513 let positions = f
3514 .params
3515 .iter()
3516 .map(|p| &p.type_ref)
3517 .chain(std::iter::once(&f.return_type));
3518 for r in positions {
3519 if let Some(ty) = first_private(r, &vars) {
3520 report(r.span(), &decl, &ty);
3521 }
3522 }
3523 }
3524 CommonsItem::Type(t) if t.private.is_none() => {
3525 let vars: HashSet<&str> =
3526 t.type_params.iter().map(|p| p.name.name.as_str()).collect();
3527 let decl = format!("type `{}`", t.name.name);
3528 let positions: Vec<&TypeRef> = match &t.body {
3529 TypeBody::Record(r) => r.fields.iter().map(|f| &f.type_ref).collect(),
3530 TypeBody::Sum(s) => s
3531 .variants
3532 .iter()
3533 .flat_map(|v| v.payload.iter().map(|p| &p.type_ref))
3534 .collect(),
3535 TypeBody::Refined { .. } | TypeBody::Opaque { .. } => Vec::new(),
3536 };
3537 for r in positions {
3538 if let Some(ty) = first_private(r, &vars) {
3539 report(r.span(), &decl, &ty);
3540 }
3541 }
3542 }
3543 CommonsItem::Const(c) if c.private.is_none() => {
3546 if let Some(ty) = first_private(&c.ty, &HashSet::new()) {
3547 report(c.ty.span(), &format!("constant `{}`", c.name.name), &ty);
3548 }
3549 }
3550 _ => {}
3551 }
3552 }
3553 for e in parsed[i].exports() {
3554 for n in &e.names {
3555 if private_types.contains(&n.name.name) {
3556 report(n.name.span, "`exports` list", &n.name.name);
3557 }
3558 }
3559 }
3560 }
3561 }
3562}
3563
3564pub fn phase_uses_name_conflicts(
3568 unit_uses: &HashMap<String, Vec<String>>,
3569 unit_tables: &HashMap<String, UnitTable>,
3570 parsed: &[ParsedFile],
3571 groups: &BTreeMap<String, Vec<usize>>,
3572 errors: &mut ErrorSink,
3573) {
3574 for (name, targets) in unit_uses {
3575 let local = unit_tables.get(name).expect("unit table present");
3576 let mut imported: HashMap<String, String> = HashMap::new();
3577 for t in targets {
3578 let used = unit_tables
3580 .get(t)
3581 .expect("used unit table present")
3582 .importable();
3583 for type_name in used.types.keys() {
3584 if local.types.contains_key(type_name) || local.fns.contains_key(type_name) {
3591 continue;
3592 }
3593 if let Some(prev) = imported.get(type_name) {
3594 let site = uses_span_of(parsed, &groups[name], t);
3595 let span = site.map(|(_, s)| s).unwrap_or_default();
3596 let file = site.map(|(i, _)| parsed[i].identity_path());
3597 errors.push_for(file.as_deref(),
3598 CompileError::new(
3599 "bynk.uses.name_conflict",
3600 span,
3601 format!(
3602 "`{name}` uses two commons that both declare `{type_name}`: `{prev}` and `{t}`",
3603 ),
3604 )
3605 .with_note(
3606 "name conflicts at the use site are not yet renamable; remove or restructure one of the imports",
3607 ),
3608 );
3609 } else {
3610 imported.insert(type_name.clone(), t.clone());
3611 }
3612 }
3613 for fn_name in used.fns.keys() {
3614 if crate::symbols::local_value_kind(local, fn_name).is_some() {
3617 continue;
3618 }
3619 if let Some(prev) = imported.get(fn_name) {
3620 let site = uses_span_of(parsed, &groups[name], t);
3621 let span = site.map(|(_, s)| s).unwrap_or_default();
3622 let file = site.map(|(i, _)| parsed[i].identity_path());
3623 errors.push_for(file.as_deref(),
3624 CompileError::new(
3625 "bynk.uses.name_conflict",
3626 span,
3627 format!(
3628 "`{name}` uses two commons that both declare `{fn_name}`: `{prev}` and `{t}`",
3629 ),
3630 )
3631 .with_note(
3632 "name conflicts at the use site are not yet renamable; remove or restructure one of the imports",
3633 ),
3634 );
3635 } else {
3636 imported.insert(fn_name.clone(), t.clone());
3637 }
3638 }
3639 for asset_name in used.assets.keys() {
3642 if crate::symbols::local_value_kind(local, asset_name).is_some() {
3644 continue;
3645 }
3646 if let Some(prev) = imported.get(asset_name) {
3647 let site = uses_span_of(parsed, &groups[name], t);
3648 let span = site.map(|(_, s)| s).unwrap_or_default();
3649 let file = site.map(|(i, _)| parsed[i].identity_path());
3650 errors.push_for(file.as_deref(),
3651 CompileError::new(
3652 "bynk.uses.name_conflict",
3653 span,
3654 format!(
3655 "`{name}` uses two commons that both declare `{asset_name}`: `{prev}` and `{t}`",
3656 ),
3657 )
3658 .with_note(
3659 "name conflicts at the use site are not yet renamable; remove or restructure one of the imports",
3660 ),
3661 );
3662 } else {
3663 imported.insert(asset_name.clone(), t.clone());
3664 }
3665 }
3666 for embed_name in used.embeds.keys() {
3669 if crate::symbols::local_value_kind(local, embed_name).is_some() {
3670 continue;
3671 }
3672 if let Some(prev) = imported.get(embed_name) {
3673 let site = uses_span_of(parsed, &groups[name], t);
3674 let span = site.map(|(_, s)| s).unwrap_or_default();
3675 let file = site.map(|(i, _)| parsed[i].identity_path());
3676 errors.push_for(file.as_deref(),
3677 CompileError::new(
3678 "bynk.uses.name_conflict",
3679 span,
3680 format!(
3681 "`{name}` uses two commons that both declare `{embed_name}`: `{prev}` and `{t}`",
3682 ),
3683 )
3684 .with_note(
3685 "name conflicts at the use site are not yet renamable; remove or restructure one of the imports",
3686 ),
3687 );
3688 } else {
3689 imported.insert(embed_name.clone(), t.clone());
3690 }
3691 }
3692 for const_name in used.consts.keys() {
3694 if crate::symbols::local_value_kind(local, const_name).is_some() {
3695 continue;
3696 }
3697 if let Some(prev) = imported.get(const_name) {
3698 let site = uses_span_of(parsed, &groups[name], t);
3699 let span = site.map(|(_, s)| s).unwrap_or_default();
3700 let file = site.map(|(i, _)| parsed[i].identity_path());
3701 errors.push_for(file.as_deref(),
3702 CompileError::new(
3703 "bynk.uses.name_conflict",
3704 span,
3705 format!(
3706 "`{name}` uses two commons that both declare `{const_name}`: `{prev}` and `{t}`",
3707 ),
3708 )
3709 .with_note(
3710 "name conflicts at the use site are not yet renamable; remove or restructure one of the imports",
3711 ),
3712 );
3713 } else {
3714 imported.insert(const_name.clone(), t.clone());
3715 }
3716 }
3717 }
3718 }
3719}
3720
3721pub fn phase_messages_bundles(
3741 parsed: &[ParsedFile],
3742 groups: &BTreeMap<String, Vec<usize>>,
3743 kinds: &BTreeMap<String, UnitKind>,
3744 unit_uses: &HashMap<String, Vec<String>>,
3745 errors: &mut ErrorSink,
3746) {
3747 for (name, indices) in groups {
3748 let mut first_messages: Option<(usize, Span)> = None;
3749 let mut reference_sites: Vec<(usize, Span)> = Vec::new();
3750 let mut reference_block: Option<(usize, &MessagesDecl)> = None;
3751 let mut by_tag: HashMap<&str, (usize, &MessagesDecl)> = HashMap::new();
3752 for &i in indices {
3753 for item in parsed[i].items() {
3754 let CommonsItem::Messages(m) = item else {
3755 continue;
3756 };
3757 if first_messages.is_none() {
3758 first_messages = Some((i, m.span));
3759 }
3760 if kinds.get(name) != Some(&UnitKind::Commons) {
3761 errors.push_for(
3762 Some(&parsed[i].identity_path()),
3763 CompileError::new(
3764 "bynk.messages.outside_commons",
3765 m.span,
3766 "`messages` declarations are only allowed inside a commons, not a context or adapter",
3767 ),
3768 );
3769 continue;
3770 }
3771 if !checker::locale_tag_accepts(&m.tag) {
3778 let pattern = checker::locale_tag_pattern().unwrap_or("");
3779 errors.push_for(
3780 Some(&parsed[i].identity_path()),
3781 CompileError::new(
3782 "bynk.messages.invalid_locale_tag",
3783 m.tag_span,
3784 format!(
3785 "\"{}\" is not a valid `LocaleTag` — it must match the pattern `{}`",
3786 m.tag, pattern
3787 ),
3788 ),
3789 );
3790 }
3791 if let Some(&(_, prev)) = by_tag.get(m.tag.as_str()) {
3800 errors.push_for(
3801 Some(&parsed[i].identity_path()),
3802 CompileError::new(
3803 "bynk.resolve.duplicate_message_locale",
3804 m.tag_span,
3805 format!("locale \"{}\" is already declared in this bundle", m.tag),
3806 )
3807 .with_label(prev.tag_span, "previously declared here"),
3808 );
3809 } else {
3810 by_tag.insert(m.tag.as_str(), (i, m));
3811 }
3812 for ann in &m.annotations {
3813 if ann.name.name == "reference" {
3814 reference_sites.push((i, ann.span));
3815 reference_block = Some((i, m));
3816 }
3817 }
3818 let mut seen: HashMap<&str, Span> = HashMap::new();
3819 for entry in &m.entries {
3820 if let Some(prev) = seen.get(entry.code.as_str()) {
3821 errors.push_for(
3822 Some(&parsed[i].identity_path()),
3823 CompileError::new(
3824 "bynk.resolve.duplicate_message_code",
3825 entry.code_span,
3826 format!(
3827 "message code \"{}\" is already declared in this block",
3828 entry.code
3829 ),
3830 )
3831 .with_label(*prev, "previously declared here"),
3832 );
3833 } else {
3834 seen.insert(entry.code.as_str(), entry.code_span);
3835 }
3836 check_entry_icu_syntax(entry, Some(&parsed[i].identity_path()), errors);
3841 }
3842 }
3843 }
3844 let Some((first_i, first_span)) = first_messages else {
3845 continue;
3846 };
3847 if kinds.get(name) != Some(&UnitKind::Commons) {
3848 continue;
3851 }
3852 match reference_sites.len() {
3853 0 => {
3854 errors.push_for(
3855 Some(&parsed[first_i].identity_path()),
3856 CompileError::new(
3857 "bynk.messages.missing_reference",
3858 first_span,
3859 "a message bundle must have exactly one `@reference` block; none found",
3860 ),
3861 );
3862 }
3863 1 => {
3864 let (_, reference) = reference_block
3869 .expect("reference_sites.len() == 1 implies reference_block is Some");
3870 let mut sorted_tags: Vec<&&str> = by_tag.keys().collect();
3873 sorted_tags.sort();
3874 for &&tag in &sorted_tags {
3875 let &(locale_i, locale_m) = &by_tag[tag];
3876 if tag == reference.tag.as_str() {
3877 continue;
3878 }
3879 for ref_entry in &reference.entries {
3880 let Some(locale_entry) =
3881 locale_m.entries.iter().find(|e| e.code == ref_entry.code)
3882 else {
3883 errors.push_for(
3884 Some(&parsed[locale_i].identity_path()),
3885 CompileError::new(
3886 "bynk.messages.incomplete",
3887 locale_m.span,
3888 format!(
3889 "locale \"{tag}\" is missing code \"{}\", declared by the reference locale \"{}\"",
3890 ref_entry.code, reference.tag
3891 ),
3892 ),
3893 );
3894 continue;
3895 };
3896 let ref_names = icu::placeholder_names(&ref_entry.template);
3897 let locale_names = icu::placeholder_names(&locale_entry.template);
3898 if ref_names != locale_names {
3899 errors.push_for(
3900 Some(&parsed[locale_i].identity_path()),
3901 CompileError::new(
3902 "bynk.messages.placeholder_mismatch",
3903 locale_entry.template_span,
3904 format!(
3905 "locale \"{tag}\"'s template for code \"{}\" uses placeholders {locale_names:?}, but the reference locale \"{}\"'s uses {ref_names:?}",
3906 ref_entry.code, reference.tag
3907 ),
3908 ),
3909 );
3910 }
3911 let ref_kinds = icu::template_format_kinds(&ref_entry.template);
3921 let locale_kinds = icu::template_format_kinds(&locale_entry.template);
3922 for (pname, ref_kind) in &ref_kinds {
3923 let Some(locale_kind) = locale_kinds.get(pname) else {
3924 continue;
3925 };
3926 if locale_kind != ref_kind {
3927 errors.push_for(
3928 Some(&parsed[locale_i].identity_path()),
3929 CompileError::new(
3930 "bynk.messages.format_mismatch",
3931 locale_entry.template_span,
3932 format!(
3933 "locale \"{tag}\"'s placeholder \"{pname}\" in code \"{}\" is formatted as {}, but the reference locale \"{}\"'s is {}",
3934 ref_entry.code,
3935 locale_kind.as_str(),
3936 reference.tag,
3937 ref_kind.as_str(),
3938 ),
3939 ),
3940 );
3941 }
3942 }
3943 }
3944 }
3945 }
3946 _ => {
3947 let (_, first_ref_span) = reference_sites[0];
3948 for &(i, span) in &reference_sites[1..] {
3949 errors.push_for(
3950 Some(&parsed[i].identity_path()),
3951 CompileError::new(
3952 "bynk.messages.multiple_reference",
3953 span,
3954 "a message bundle must have exactly one `@reference` block; found more than one",
3955 )
3956 .with_label(first_ref_span, "first `@reference` here"),
3957 );
3958 }
3959 }
3960 }
3961 if let (Some((_, reference)), [_]) = (reference_block, reference_sites.as_slice()) {
3972 for &i in indices {
3973 for item in parsed[i].items() {
3974 let CommonsItem::Messages(m) = item else {
3975 continue;
3976 };
3977 let Some(private_span) = m.private else {
3978 continue;
3979 };
3980 let is_reference = std::ptr::eq(m, reference);
3981 let (message, note) = if is_reference {
3982 (
3983 format!(
3984 "a `private` messages bundle is never negotiated by a context that uses `{name}`"
3985 ),
3986 format!(
3987 "remove `private` so that a context that uses `{name}` negotiates its locale against this bundle; this commons' own `render` reads the bundle either way"
3988 ),
3989 )
3990 } else if reference.private.is_some() {
3991 continue;
3993 } else {
3994 (
3995 format!(
3996 "`private` has no effect on this `messages` block: the bundle's `@reference` block is public, so a context that uses `{name}` still negotiates locale \"{}\"",
3997 m.tag
3998 ),
3999 "remove `private`: a bundle's visibility follows its `@reference` block"
4000 .to_string(),
4001 )
4002 };
4003 errors.push_for(
4004 Some(&parsed[i].identity_path()),
4005 CompileError::new(
4006 "bynk.visibility.private_messages",
4007 private_span,
4008 message,
4009 )
4010 .with_note(note),
4011 );
4012 }
4013 }
4014 }
4015 let targets = unit_uses.get(name);
4024 let has_locale_uses =
4025 targets.is_some_and(|targets| targets.iter().any(|t| t == firstparty::LOCALE_UNIT));
4026 let has_locale_types_uses = targets
4027 .is_some_and(|targets| targets.iter().any(|t| t == firstparty::LOCALE_TYPES_UNIT));
4028 if !has_locale_uses || !has_locale_types_uses {
4029 let missing = match (has_locale_uses, has_locale_types_uses) {
4030 (false, false) => "`bynk.locale` and `bynk.locale.types`",
4031 (false, true) => "`bynk.locale`",
4032 (true, false) => "`bynk.locale.types`",
4033 (true, true) => unreachable!("at least one of the two is missing here"),
4034 };
4035 errors.push_for(
4036 Some(&parsed[first_i].identity_path()),
4037 CompileError::new(
4038 "bynk.messages.missing_locale_dependency",
4039 first_span,
4040 format!("a commons declaring `messages` must also `uses` {missing}"),
4041 ),
4042 );
4043 }
4044 }
4045}
4046
4047pub fn phase_locale_bundle_ambiguity(
4059 parsed: &[ParsedFile],
4060 groups: &BTreeMap<String, Vec<usize>>,
4061 kinds: &BTreeMap<String, UnitKind>,
4062 unit_uses: &HashMap<String, Vec<String>>,
4063 unit_flattened: &HashMap<String, HashMap<String, String>>,
4064 errors: &mut ErrorSink,
4065) {
4066 for (name, indices) in groups {
4067 if kinds.get(name) != Some(&UnitKind::Context) {
4068 continue;
4069 }
4070 let ContextMessageBundle::Many(bundles) =
4071 detect_context_message_bundle(name, unit_uses, groups, kinds, parsed)
4072 else {
4073 continue;
4074 };
4075 let consumes_locale = unit_flattened
4076 .get(name)
4077 .and_then(|m| m.get("Locale"))
4078 .is_some_and(|owner| owner == firstparty::BYNK_UNIT);
4079 if !consumes_locale {
4080 continue;
4081 }
4082 for &i in indices {
4083 for c in parsed[i].consumes() {
4084 if c.target.joined() != firstparty::BYNK_UNIT {
4085 continue;
4086 }
4087 let Some(locale_ident) = c
4088 .selected
4089 .iter()
4090 .flatten()
4091 .map(|i| &i.name)
4092 .find(|id| id.name == "Locale")
4093 else {
4094 continue;
4095 };
4096 let mut err = CompileError::new(
4097 "bynk.locale.multiple_message_bundles",
4098 locale_ident.span,
4099 format!(
4100 "context `{name}` uses {} message bundles ({}) — `Locale.current()` has no single bundle to negotiate against",
4101 bundles.len(),
4102 bundles.join(", "),
4103 ),
4104 );
4105 for &j in indices {
4106 for u in parsed[j].uses() {
4107 if bundles.contains(&u.target.joined()) {
4108 err = err
4109 .with_label(u.span, format!("`{}` used here", u.target.joined()));
4110 }
4111 }
4112 }
4113 errors.push_for(Some(&parsed[i].identity_path()), err);
4114 }
4115 }
4116 }
4117}
4118
4119fn check_entry_icu_syntax(entry: &MessageEntry, file: Option<&Path>, errors: &mut ErrorSink) {
4123 for (inner_offset, inner) in icu::icu_dispatch_placeholders(&entry.template) {
4124 if let Err(e) = icu::parse_icu_placeholder(inner) {
4125 let decoded_start = inner_offset + e.offset;
4126 let decoded_span = Span::new(decoded_start, decoded_start + e.len);
4127 let raw_span = decoded_span.offset(entry.template_span.start + 1);
4128 errors.push_for(
4129 file,
4130 CompileError::new(
4131 "bynk.messages.malformed_icu_syntax",
4132 raw_span,
4133 e.kind.message(),
4134 ),
4135 );
4136 }
4137 }
4138}
4139
4140pub fn phase_event_subscriptions(
4154 parsed: &[ParsedFile],
4155 groups: &BTreeMap<String, Vec<usize>>,
4156 kinds: &BTreeMap<String, UnitKind>,
4157 unit_tables: &HashMap<String, UnitTable>,
4158 unit_consumes: &HashMap<String, Vec<String>>,
4159 unit_uses: &HashMap<String, Vec<String>>,
4160 errors: &mut ErrorSink,
4161) {
4162 for (name, indices) in groups {
4163 if kinds.get(name) != Some(&UnitKind::Context) {
4164 continue;
4165 }
4166 let consumed = unit_consumes.get(name).cloned().unwrap_or_default();
4167 for &i in indices {
4168 for item in parsed[i].items() {
4169 let CommonsItem::Service(s) = item else {
4170 continue;
4171 };
4172 let ServiceProtocol::Events {
4173 event_type,
4174 pattern,
4175 schema_dispatch,
4176 } = &s.protocol
4177 else {
4178 continue;
4179 };
4180 if let Some(dispatch) = schema_dispatch {
4185 check_schema_dispatch(dispatch, &parsed[i].identity_path(), errors);
4186 }
4187 let TypeRef::Named(id) = event_type else {
4188 continue;
4189 };
4190 let owner_locally = unit_tables
4191 .get(name)
4192 .filter(|t| t.events.contains_key(&id.name))
4193 .map(|_| name.clone());
4194 let owner_consumed = consumed.iter().find(|c| {
4195 unit_tables
4196 .get(*c)
4197 .is_some_and(|t| t.events.contains_key(&id.name))
4198 });
4199 let owner = owner_locally
4200 .as_deref()
4201 .or(owner_consumed.map(String::as_str));
4202 let Some(owner) = owner else {
4203 errors.push_for(
4204 Some(&parsed[i].identity_path()),
4205 CompileError::new(
4206 "bynk.event.unknown_subscription",
4207 id.span,
4208 format!(
4209 "`{}` is not a declared event in this context or any consumed context",
4210 id.name
4211 ),
4212 )
4213 .with_note(
4214 "check the spelling, or add `consumes <context>` for the context whose `event` this names — an unresolvable subscription never receives anything, silently",
4215 ),
4216 );
4217 continue;
4218 };
4219 let Some(pattern) = pattern else {
4224 continue;
4225 };
4226 let Some(event_decl) = unit_tables.get(owner).and_then(|t| t.events.get(&id.name))
4227 else {
4228 continue;
4229 };
4230 check_event_pattern(
4231 pattern,
4232 event_decl,
4233 owner,
4234 unit_tables,
4235 unit_uses,
4236 &parsed[i].identity_path(),
4237 errors,
4238 );
4239 }
4240 }
4241 }
4242}
4243
4244fn check_event_pattern(
4253 pattern: &EventPattern,
4254 event_decl: &EventDecl,
4255 owner: &str,
4256 unit_tables: &HashMap<String, UnitTable>,
4257 unit_uses: &HashMap<String, Vec<String>>,
4258 identity_path: &std::path::Path,
4259 errors: &mut ErrorSink,
4260) {
4261 let mut seen: HashSet<String> = HashSet::new();
4262 for field in &pattern.fields {
4263 if !seen.insert(field.name.name.clone()) {
4264 errors.push_for(
4265 Some(identity_path),
4266 CompileError::new(
4267 "bynk.event.pattern_duplicate_field",
4268 field.name.span,
4269 format!(
4270 "field `{}` is matched more than once in this subscription pattern",
4271 field.name.name
4272 ),
4273 ),
4274 );
4275 continue;
4276 }
4277 let Some(record_field) = event_decl
4278 .body
4279 .fields
4280 .iter()
4281 .find(|f| f.name.name == field.name.name)
4282 else {
4283 let known: Vec<&str> = event_decl
4284 .body
4285 .fields
4286 .iter()
4287 .map(|f| f.name.name.as_str())
4288 .collect();
4289 errors.push_for(
4290 Some(identity_path),
4291 CompileError::new(
4292 "bynk.event.pattern_unknown_field",
4293 field.name.span,
4294 format!(
4295 "`{}` has no field named `{}`",
4296 event_decl.name.name, field.name.name
4297 ),
4298 )
4299 .with_note(format!(
4300 "declared fields: {}",
4301 if known.is_empty() {
4302 "(none)".to_string()
4303 } else {
4304 known.join(", ")
4305 }
4306 )),
4307 );
4308 continue;
4309 };
4310 check_event_pattern_value(
4311 &field.value,
4312 record_field,
4313 owner,
4314 unit_tables,
4315 unit_uses,
4316 identity_path,
4317 errors,
4318 );
4319 }
4320}
4321
4322fn check_schema_dispatch(
4328 dispatch: &SchemaDispatch,
4329 identity_path: &std::path::Path,
4330 errors: &mut ErrorSink,
4331) {
4332 let (lo, hi) = match &dispatch.pattern {
4335 SchemaVersionPattern::Literal(n) => (Some(*n), Some(*n)),
4336 SchemaVersionPattern::Range(r) => (r.lo, r.hi),
4337 SchemaVersionPattern::Wildcard => return,
4338 };
4339 if lo.into_iter().chain(hi).any(|n| n <= 0) {
4340 errors.push_for(
4341 Some(identity_path),
4342 CompileError::new(
4343 "bynk.event.bad_schema_dispatch",
4344 dispatch.span,
4345 "`via schema(...)`'s version bounds must be positive `Int` literals",
4346 ),
4347 );
4348 return;
4349 }
4350 if let SchemaVersionPattern::Range(r) = &dispatch.pattern
4351 && let Some(err) = crate::checker::empty_range_error(r, "`via schema(...)`")
4352 {
4353 errors.push_for(Some(identity_path), err);
4354 }
4355}
4356
4357fn check_event_pattern_value(
4361 value: &EventPatternValue,
4362 record_field: &RecordField,
4363 owner: &str,
4364 unit_tables: &HashMap<String, UnitTable>,
4365 unit_uses: &HashMap<String, Vec<String>>,
4366 identity_path: &std::path::Path,
4367 errors: &mut ErrorSink,
4368) {
4369 match value {
4370 EventPatternValue::Literal {
4371 value: lit, span, ..
4372 } => {
4373 let base = match &record_field.type_ref {
4381 TypeRef::Base(b, _) => Some(*b),
4382 TypeRef::Named(field_type_name) => {
4383 resolve_type_decl(unit_tables, unit_uses, owner, &field_type_name.name)
4384 .and_then(|d| match &d.body {
4385 TypeBody::Refined { base, .. } | TypeBody::Opaque { base, .. } => {
4386 Some(*base)
4387 }
4388 _ => None,
4389 })
4390 }
4391 _ => None,
4392 };
4393 let Some(base) = base else {
4394 errors.push_for(
4395 Some(identity_path),
4396 CompileError::new(
4397 "bynk.event.pattern_type_mismatch",
4398 *span,
4399 format!(
4400 "field `{}` is not a literal-kind type — a literal pattern value cannot match it",
4401 record_field.name.name
4402 ),
4403 ),
4404 );
4405 return;
4406 };
4407 let kind_matches = matches!(
4408 (lit, base),
4409 (LiteralValue::Int(_), BaseType::Int)
4410 | (LiteralValue::Str(_), BaseType::String)
4411 | (LiteralValue::Bool(_), BaseType::Bool)
4412 );
4413 if !kind_matches {
4414 errors.push_for(
4415 Some(identity_path),
4416 CompileError::new(
4417 "bynk.event.pattern_type_mismatch",
4418 *span,
4419 format!(
4420 "this literal does not match the type of field `{}` (`{}`)",
4421 record_field.name.name,
4422 type_ref_to_display(&record_field.type_ref)
4423 ),
4424 ),
4425 );
4426 }
4427 }
4428 EventPatternValue::Variant {
4429 type_name,
4430 variant,
4431 span,
4432 } => {
4433 let TypeRef::Named(field_type_name) = &record_field.type_ref else {
4434 errors.push_for(
4435 Some(identity_path),
4436 CompileError::new(
4437 "bynk.event.pattern_type_mismatch",
4438 *span,
4439 format!(
4440 "field `{}` is not a sum type — a variant pattern value cannot match it",
4441 record_field.name.name
4442 ),
4443 ),
4444 );
4445 return;
4446 };
4447 if let Some(qualifier) = type_name
4448 && qualifier.name != field_type_name.name
4449 {
4450 errors.push_for(
4451 Some(identity_path),
4452 CompileError::new(
4453 "bynk.event.pattern_type_mismatch",
4454 qualifier.span,
4455 format!(
4456 "field `{}` has type `{}`, not `{}`",
4457 record_field.name.name, field_type_name.name, qualifier.name
4458 ),
4459 ),
4460 );
4461 return;
4462 }
4463 let Some(decl) =
4464 resolve_type_decl(unit_tables, unit_uses, owner, &field_type_name.name)
4465 else {
4466 return;
4470 };
4471 let TypeBody::Sum(sum) = &decl.body else {
4472 errors.push_for(
4473 Some(identity_path),
4474 CompileError::new(
4475 "bynk.event.pattern_type_mismatch",
4476 *span,
4477 format!(
4478 "field `{}` has type `{}`, which is not a sum type",
4479 record_field.name.name, field_type_name.name
4480 ),
4481 ),
4482 );
4483 return;
4484 };
4485 let Some(member) = sum.variants.iter().find(|v| v.name.name == variant.name) else {
4486 errors.push_for(
4487 Some(identity_path),
4488 CompileError::new(
4489 "bynk.event.pattern_unknown_variant",
4490 variant.span,
4491 format!(
4492 "`{}` has no variant named `{}`",
4493 field_type_name.name, variant.name
4494 ),
4495 ),
4496 );
4497 return;
4498 };
4499 if !member.payload.is_empty() {
4500 errors.push_for(
4501 Some(identity_path),
4502 CompileError::new(
4503 "bynk.event.pattern_variant_payload",
4504 variant.span,
4505 format!(
4506 "`{}.{}` carries a payload — only a nullary variant may be matched here, since testing the tag alone would silently ignore the payload",
4507 field_type_name.name, variant.name
4508 ),
4509 ),
4510 );
4511 }
4512 }
4513 }
4514}
4515
4516fn resolve_type_decl<'a>(
4522 unit_tables: &'a HashMap<String, UnitTable>,
4523 unit_uses: &HashMap<String, Vec<String>>,
4524 owner: &str,
4525 name: &str,
4526) -> Option<&'a Arc<TypeDecl>> {
4527 if let Some(t) = unit_tables.get(owner).and_then(|t| t.types.get(name)) {
4528 return Some(t);
4529 }
4530 for used in unit_uses.get(owner).into_iter().flatten() {
4531 if let Some(t) = unit_tables.get(used).and_then(|t| t.types.get(name)) {
4532 return Some(t);
4533 }
4534 }
4535 None
4536}
4537
4538pub fn phase_validate_type_exports(
4544 groups: &BTreeMap<String, Vec<usize>>,
4545 kinds: &BTreeMap<String, UnitKind>,
4546 parsed: &[ParsedFile],
4547 unit_tables: &HashMap<String, UnitTable>,
4548 errors: &mut ErrorSink,
4549 refs: &mut RefSink,
4550) -> HashMap<String, HashMap<String, Visibility>> {
4551 let mut exports_visibility: HashMap<String, HashMap<String, Visibility>> = HashMap::new();
4552 for (name, indices) in groups {
4553 let kind = *kinds.get(name).unwrap();
4554 if kind != UnitKind::Context && kind != UnitKind::Adapter {
4555 continue;
4558 }
4559 let local = unit_tables.get(name).unwrap();
4560 let mut seen: HashMap<String, (Visibility, Span)> = HashMap::new();
4561 for &i in indices {
4562 refs.enter_file(&parsed[i].identity_path(), name, parsed[i].is_synthetic());
4563 for clause in parsed[i].exports() {
4564 let ExportKind::Type(clause_vis) = clause.kind else {
4567 continue;
4568 };
4569 let mut within: HashMap<String, Span> = HashMap::new();
4570 for n in clause.names.iter().map(|e| &e.name) {
4571 if let Some(prev) = within.get(&n.name) {
4572 errors.push_for(
4573 Some(&parsed[i].identity_path()),
4574 CompileError::new(
4575 "bynk.exports.duplicate_in_clause",
4576 n.span,
4577 format!(
4578 "type `{}` appears more than once in this exports clause",
4579 n.name
4580 ),
4581 )
4582 .with_label(*prev, "previously listed here"),
4583 );
4584 continue;
4585 }
4586 within.insert(n.name.clone(), n.span);
4587
4588 if !local.types.contains_key(&n.name) {
4589 errors.push_for(Some(&parsed[i].identity_path()),
4590 CompileError::new(
4591 "bynk.exports.undeclared_type",
4592 n.span,
4593 format!(
4594 "exports clause references `{}`, which is not a type declared in context `{}`",
4595 n.name, name
4596 ),
4597 )
4598 .with_note(
4599 "only types declared in the same context can appear in `exports` clauses",
4600 ),
4601 );
4602 continue;
4603 }
4604 refs.record(n.span, SymbolKind::Type, &n.name);
4606
4607 if let Some((prev_vis, prev_span)) = seen.get(&n.name) {
4608 if *prev_vis == clause_vis {
4609 errors.push_for(
4610 Some(&parsed[i].identity_path()),
4611 CompileError::new(
4612 "bynk.exports.duplicate_export",
4613 n.span,
4614 format!("type `{}` is exported more than once", n.name),
4615 )
4616 .with_label(*prev_span, "previously exported here"),
4617 );
4618 } else {
4619 errors.push_for(Some(&parsed[i].identity_path()),
4620 CompileError::new(
4621 "bynk.exports.conflicting_visibility",
4622 n.span,
4623 format!(
4624 "type `{}` is exported with conflicting visibilities — pick `opaque` or `transparent`",
4625 n.name,
4626 ),
4627 )
4628 .with_label(*prev_span, "previously exported here"),
4629 );
4630 }
4631 continue;
4632 }
4633 seen.insert(n.name.clone(), (clause_vis, n.span));
4634 }
4635 }
4636 }
4637 let mut visibility_map: HashMap<String, Visibility> = HashMap::new();
4638 for (n, (v, _)) in seen {
4639 visibility_map.insert(n, v);
4640 }
4641 exports_visibility.insert(name.clone(), visibility_map);
4642 }
4643 exports_visibility
4644}
4645
4646pub fn phase_validate_capability_exports(
4651 groups: &BTreeMap<String, Vec<usize>>,
4652 kinds: &BTreeMap<String, UnitKind>,
4653 parsed: &[ParsedFile],
4654 unit_tables: &HashMap<String, UnitTable>,
4655 errors: &mut ErrorSink,
4656 refs: &mut RefSink,
4657) {
4658 for (name, indices) in groups {
4659 if kinds.get(name) != Some(&UnitKind::Context)
4660 && kinds.get(name) != Some(&UnitKind::Adapter)
4661 {
4662 continue;
4663 }
4664 let local = unit_tables.get(name).unwrap();
4665 let mut seen: HashMap<String, Span> = HashMap::new();
4666 for &i in indices {
4667 refs.enter_file(&parsed[i].identity_path(), name, parsed[i].is_synthetic());
4668 for clause in parsed[i].exports() {
4669 if !matches!(clause.kind, ExportKind::Capability) {
4670 continue;
4671 }
4672 for n in clause.names.iter().map(|e| &e.name) {
4673 if let Some(prev) = seen.get(&n.name) {
4674 errors.push_for(
4675 Some(&parsed[i].identity_path()),
4676 CompileError::new(
4677 "bynk.exports.duplicate_export",
4678 n.span,
4679 format!("capability `{}` is exported more than once", n.name),
4680 )
4681 .with_label(*prev, "previously exported here"),
4682 );
4683 continue;
4684 }
4685 seen.insert(n.name.clone(), n.span);
4686 if local.capabilities.contains_key(&n.name) {
4687 refs.record(n.span, SymbolKind::Capability, &n.name);
4690 }
4691 if !local.capabilities.contains_key(&n.name) {
4692 errors.push_for(Some(&parsed[i].identity_path()),
4693 CompileError::new(
4694 "bynk.exports.undeclared_capability",
4695 n.span,
4696 format!(
4697 "`exports capability` references `{}`, which is not a capability declared in context `{}`",
4698 n.name, name
4699 ),
4700 )
4701 .with_note(
4702 "only capabilities declared in the same context can appear in `exports capability` clauses",
4703 ),
4704 );
4705 continue;
4706 }
4707 let derived = local
4711 .capabilities
4712 .get(&n.name)
4713 .is_some_and(|c| c.derived.is_some());
4714 if !derived && !local.providers.contains_key(&n.name) {
4715 errors.push_for(Some(&parsed[i].identity_path()),
4716 CompileError::new(
4717 "bynk.exports.capability_not_provided",
4718 n.span,
4719 format!(
4720 "exported capability `{}` has no provider in context `{}` — a consumer cannot instantiate it",
4721 n.name, name
4722 ),
4723 )
4724 .with_note(format!(
4725 "add a `provides {} = …` declaration so the capability can be wired into consumers",
4726 n.name
4727 )),
4728 );
4729 }
4730 }
4731 }
4732 }
4733 }
4734}
4735
4736pub fn phase_validate_providers(
4741 unit_tables: &HashMap<String, UnitTable>,
4742 groups: &BTreeMap<String, Vec<usize>>,
4746 parsed: &[ParsedFile],
4747 broken: &BrokenDeclNames,
4749 errors: &mut ErrorSink,
4750 tys: &Arc<Types>,
4751) {
4752 for (name, table) in unit_tables {
4753 let provider_files: HashMap<&str, PathBuf> = groups
4757 .get(name)
4758 .map(|indices| {
4759 indices
4760 .iter()
4761 .flat_map(|&i| {
4762 parsed[i].items().iter().filter_map(move |item| match item {
4763 CommonsItem::Provider(p) => {
4764 Some((p.capability.name.as_str(), parsed[i].identity_path()))
4765 }
4766 _ => None,
4767 })
4768 })
4769 .collect()
4770 })
4771 .unwrap_or_default();
4772 for (cap_name, provider) in &table.providers {
4773 let provider_file = provider_files.get(cap_name.as_str()).map(|p| p.as_path());
4774 if provider.external {
4777 continue;
4778 }
4779 let Some(cap) = table.capabilities.get(cap_name) else {
4780 if broken.get(name).is_some_and(|b| b.contains(cap_name)) {
4784 continue;
4785 }
4786 errors.push_for(provider_file,
4787 CompileError::new(
4788 "bynk.provider.unknown_capability",
4789 provider.capability.span,
4790 format!(
4791 "provider targets unknown capability `{}` — declare the capability in the same context",
4792 cap_name
4793 ),
4794 ),
4795 );
4796 continue;
4797 };
4798 for cap_op in &cap.ops {
4806 if !cap_op.type_params.is_empty() {
4807 errors.push_for(
4808 provider_file,
4809 CompileError::new(
4810 "bynk.provider.generic_op_requires_external",
4811 provider.span,
4812 format!(
4813 "provider `{}` for capability `{}` has a Bynk body, but operation `{}` declares its own type parameter(s) (`[{}]`) — a generic capability operation requires an external (bodiless) provider",
4814 provider.provider_name.name,
4815 cap_name,
4816 cap_op.name.name,
4817 cap_op
4818 .type_params
4819 .iter()
4820 .map(|p| p.name.name.as_str())
4821 .collect::<Vec<_>>()
4822 .join(", "),
4823 ),
4824 )
4825 .with_note(
4826 "write `provides Cap = Name` with no `{ … }` block, and supply the implementation as a hand-authored class in the adapter's binding file",
4827 ),
4828 );
4829 }
4830 }
4831 for cap_op in &cap.ops {
4833 if !provider.ops.iter().any(|o| o.name.name == cap_op.name.name) {
4834 errors.push_for(
4835 provider_file,
4836 CompileError::new(
4837 "bynk.provider.missing_operation",
4838 provider.span,
4839 format!(
4840 "provider `{}` for capability `{}` is missing operation `{}`",
4841 provider.provider_name.name, cap_name, cap_op.name.name
4842 ),
4843 ),
4844 );
4845 }
4846 }
4847 for prov_op in &provider.ops {
4850 let Some(cap_op) = cap.ops.iter().find(|o| o.name.name == prov_op.name.name) else {
4851 errors.push_for(provider_file, CompileError::new(
4852 "bynk.provider.extra_operation",
4853 prov_op.span,
4854 format!(
4855 "provider operation `{}.{}` does not match any operation in capability `{}`",
4856 provider.provider_name.name, prov_op.name.name, cap_name
4857 ),
4858 ));
4859 continue;
4860 };
4861 if cap_op.params.len() != prov_op.params.len() {
4862 errors.push_for(provider_file, CompileError::new(
4863 "bynk.provider.signature_mismatch",
4864 prov_op.span,
4865 format!(
4866 "provider operation `{}.{}` has {} parameter(s), but capability operation expects {}",
4867 provider.provider_name.name,
4868 prov_op.name.name,
4869 prov_op.params.len(),
4870 cap_op.params.len()
4871 ),
4872 ));
4873 continue;
4874 }
4875 let cap_info = build_capability_op_info(cap_op, &table.types, tys);
4886 let no_vars = HashSet::new();
4887 let prov_params: Vec<TyId> = prov_op
4888 .params
4889 .iter()
4890 .map(|p| {
4891 checker::resolve_type_ref_in(&p.type_ref, &table.types, &no_vars, tys)
4892 .unwrap_or(tys.intern(Ty::Unit))
4893 })
4894 .collect();
4895 let prov_return_ty =
4896 checker::resolve_type_ref_in(&prov_op.return_type, &table.types, &no_vars, tys)
4897 .unwrap_or(tys.intern(Ty::Unit));
4898 for (i, (cap_ty, (prov_p, prov_ty))) in cap_info
4899 .params
4900 .iter()
4901 .zip(prov_op.params.iter().zip(prov_params.iter()))
4902 .enumerate()
4903 {
4904 if cap_ty != prov_ty {
4905 errors.push_for(provider_file, CompileError::new(
4906 "bynk.provider.signature_mismatch",
4907 prov_p.span,
4908 format!(
4909 "provider operation `{}.{}` parameter {} has type `{}`, but capability declares `{}`",
4910 provider.provider_name.name,
4911 prov_op.name.name,
4912 i + 1,
4913 ts_type_ref_display(&prov_p.type_ref),
4914 ts_type_ref_display(&cap_op.params[i].type_ref)
4915 ),
4916 ));
4917 }
4918 }
4919 if cap_info.return_ty != prov_return_ty {
4920 errors.push_for(provider_file, CompileError::new(
4921 "bynk.provider.signature_mismatch",
4922 prov_op.return_type.span(),
4923 format!(
4924 "provider operation `{}.{}` returns `{}`, but capability declares `{}`",
4925 provider.provider_name.name,
4926 prov_op.name.name,
4927 ts_type_ref_display(&prov_op.return_type),
4928 ts_type_ref_display(&cap_op.return_type)
4929 ),
4930 ));
4931 }
4932 }
4933 }
4934 }
4935}
4936
4937fn lock_violation(
4946 native: &BTreeMap<Platform, String>,
4947 selected: Platform,
4948) -> Option<LockViolation> {
4949 let mut platforms = native.iter();
4950 let (first, first_unit) = platforms.next()?;
4951 if let Some((second, second_unit)) = platforms.next() {
4952 return Some(LockViolation::Conflict {
4953 a: (*first, first_unit.clone()),
4954 b: (*second, second_unit.clone()),
4955 });
4956 }
4957 if *first != selected {
4958 return Some(LockViolation::Required {
4959 needed: *first,
4960 unit: first_unit.clone(),
4961 });
4962 }
4963 None
4964}
4965
4966#[derive(Debug, PartialEq, Eq)]
4969struct LockUnit {
4970 group: Option<String>,
4972 members: Vec<String>,
4974 native: BTreeMap<Platform, String>,
4976}
4977
4978fn lock_units(
4983 target: BuildTarget,
4984 per_context: Vec<(String, BTreeMap<Platform, String>)>,
4985 worker_groups: &bynk_project::worker_groups::WorkerGroups,
4986) -> Vec<LockUnit> {
4987 let union_of = |natives: Vec<&BTreeMap<Platform, String>>| {
4988 let mut union = BTreeMap::new();
4989 for native in natives {
4990 for (p, unit) in native {
4991 union.entry(*p).or_insert_with(|| unit.clone());
4992 }
4993 }
4994 union
4995 };
4996 match target {
4997 BuildTarget::Workers => {
4998 let mut units = Vec::new();
4999 for (key, group) in worker_groups {
5000 let found: Vec<_> = per_context
5001 .iter()
5002 .filter(|(ctx, _)| group.contexts.contains(ctx))
5003 .collect();
5004 let native = union_of(found.iter().map(|(_, n)| n).collect());
5005 if !native.is_empty() {
5006 units.push(LockUnit {
5007 group: Some(key.clone()),
5008 members: found.iter().map(|(ctx, _)| ctx.clone()).collect(),
5009 native,
5010 });
5011 }
5012 }
5013 let grouped = |ctx: &str| {
5014 worker_groups
5015 .values()
5016 .any(|g| g.contexts.iter().any(|c| c == ctx))
5017 };
5018 units.extend(
5019 per_context
5020 .into_iter()
5021 .filter(|(ctx, _)| !grouped(ctx))
5022 .map(|(ctx, native)| LockUnit {
5023 group: None,
5024 members: vec![ctx],
5025 native,
5026 }),
5027 );
5028 units
5029 }
5030 BuildTarget::Bundle => {
5031 let native = union_of(per_context.iter().map(|(_, n)| n).collect());
5032 match per_context.into_iter().next() {
5033 Some((owner, _)) if !native.is_empty() => vec![LockUnit {
5034 group: None,
5035 members: vec![owner],
5036 native,
5037 }],
5038 _ => Vec::new(),
5039 }
5040 }
5041 }
5042}
5043
5044#[derive(Debug, PartialEq, Eq)]
5046enum LockViolation {
5047 Required { needed: Platform, unit: String },
5049 Conflict {
5051 a: (Platform, String),
5052 b: (Platform, String),
5053 },
5054}
5055
5056pub fn resolve_consume_prefix(
5067 prefix: &str,
5068 consumed: &[String],
5069 aliases: &HashMap<String, String>,
5070) -> Option<String> {
5071 if let Some(q) = aliases.get(prefix) {
5072 return Some(q.clone());
5073 }
5074 if consumed.iter().any(|c| c == prefix) {
5075 return Some(prefix.to_string());
5076 }
5077 None
5078}
5079
5080pub fn handler_cross_caps(
5084 table: &UnitTable,
5085 declaring_unit: &str,
5086 consumed: &[String],
5087 aliases: &HashMap<String, String>,
5088 flattened: &HashMap<String, String>,
5089) -> BTreeMap<String, String> {
5090 let mut out = BTreeMap::new();
5091 for s in table.services.values() {
5092 for h in &s.handlers {
5093 scan_cross_caps(
5094 &mut out,
5095 &h.given,
5096 declaring_unit,
5097 consumed,
5098 aliases,
5099 flattened,
5100 );
5101 }
5102 }
5103 for a in table.agents.values() {
5104 for h in &a.handlers {
5105 scan_cross_caps(
5106 &mut out,
5107 &h.given,
5108 declaring_unit,
5109 consumed,
5110 aliases,
5111 flattened,
5112 );
5113 }
5114 }
5115 out
5116}
5117
5118pub fn provider_cross_caps(
5124 table: &UnitTable,
5125 declaring_unit: &str,
5126 consumed: &[String],
5127 aliases: &HashMap<String, String>,
5128 flattened: &HashMap<String, String>,
5129) -> BTreeMap<String, String> {
5130 let mut out = BTreeMap::new();
5131 for p in table.providers.values() {
5132 scan_cross_caps(
5133 &mut out,
5134 &p.given,
5135 declaring_unit,
5136 consumed,
5137 aliases,
5138 flattened,
5139 );
5140 }
5141 out
5142}
5143
5144fn scan_cross_caps(
5146 out: &mut BTreeMap<String, String>,
5147 given: &[CapRef],
5148 declaring_unit: &str,
5149 consumed: &[String],
5150 aliases: &HashMap<String, String>,
5151 flattened: &HashMap<String, String>,
5152) {
5153 for c in given {
5154 if firstparty::resolve(c.key(), declaring_unit, flattened)
5162 == Some(firstparty::FirstPartyCap::Events)
5163 {
5164 continue;
5165 }
5166 if let Some(p) = c.prefix() {
5167 if let Some(ctx) = resolve_consume_prefix(&p, consumed, aliases) {
5168 out.entry(c.key().to_string()).or_insert(ctx);
5169 }
5170 } else if let Some(unit) = flattened.get(c.key()) {
5171 out.entry(c.key().to_string())
5174 .or_insert_with(|| unit.clone());
5175 }
5176 }
5177}
5178
5179fn collect_given_closure(
5190 provider_ctx: &str,
5191 cap: &str,
5192 unit_tables: &HashMap<String, UnitTable>,
5193 unit_consumes: &HashMap<String, Vec<String>>,
5194 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5195 unit_flattened: &HashMap<String, HashMap<String, String>>,
5196 reached: &mut BTreeSet<(String, String)>,
5197) {
5198 if !reached.insert((provider_ctx.to_string(), cap.to_string())) {
5202 return;
5203 }
5204 let Some(provider) = unit_tables
5205 .get(provider_ctx)
5206 .and_then(|t| t.providers.get(cap))
5207 else {
5208 return;
5209 };
5210 if provider.given.is_empty() {
5211 return;
5212 }
5213 let consumed = unit_consumes.get(provider_ctx).cloned().unwrap_or_default();
5214 let aliases = unit_consumes_aliases
5215 .get(provider_ctx)
5216 .cloned()
5217 .unwrap_or_default();
5218 let flattened = unit_flattened
5219 .get(provider_ctx)
5220 .cloned()
5221 .unwrap_or_default();
5222 for g in &provider.given {
5223 let target_ctx = match g.prefix() {
5224 Some(p) => resolve_consume_prefix(&p, &consumed, &aliases)
5225 .unwrap_or_else(|| provider_ctx.to_string()),
5226 None => flattened
5227 .get(g.key())
5228 .cloned()
5229 .unwrap_or_else(|| provider_ctx.to_string()),
5230 };
5231 collect_given_closure(
5232 &target_ctx,
5233 g.key(),
5234 unit_tables,
5235 unit_consumes,
5236 unit_consumes_aliases,
5237 unit_flattened,
5238 reached,
5239 );
5240 }
5241}
5242
5243fn native_platforms_of_context(
5255 ctx: &str,
5256 table: &UnitTable,
5257 unit_tables: &HashMap<String, UnitTable>,
5258 unit_consumes: &HashMap<String, Vec<String>>,
5259 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5260 unit_flattened: &HashMap<String, HashMap<String, String>>,
5261) -> BTreeMap<Platform, String> {
5262 let mut reached: BTreeSet<(String, String)> = BTreeSet::new();
5263 for cap in table.providers.keys() {
5264 collect_given_closure(
5265 ctx,
5266 cap,
5267 unit_tables,
5268 unit_consumes,
5269 unit_consumes_aliases,
5270 unit_flattened,
5271 &mut reached,
5272 );
5273 }
5274 let consumed = unit_consumes.get(ctx).cloned().unwrap_or_default();
5275 let aliases = unit_consumes_aliases.get(ctx).cloned().unwrap_or_default();
5276 let flattened = unit_flattened.get(ctx).cloned().unwrap_or_default();
5277 for (key, cctx) in handler_cross_caps(table, ctx, &consumed, &aliases, &flattened) {
5278 collect_given_closure(
5279 &cctx,
5280 &key,
5281 unit_tables,
5282 unit_consumes,
5283 unit_consumes_aliases,
5284 unit_flattened,
5285 &mut reached,
5286 );
5287 }
5288 let mut referenced: BTreeSet<String> = reached.into_iter().map(|(unit, _)| unit).collect();
5289 referenced.extend(table.derived.values().map(|d| d.base_unit.clone()));
5292 if table
5295 .services
5296 .values()
5297 .any(|s| matches!(s.protocol, ServiceProtocol::Email { .. }))
5298 {
5299 referenced.insert(crate::firstparty::CLOUDFLARE_UNIT.to_string());
5300 }
5301 let mut out = BTreeMap::new();
5302 for unit in referenced {
5303 if let Some(p) = firstparty::platform_of(&unit) {
5304 out.entry(p).or_insert(unit);
5305 }
5306 }
5307 out
5308}
5309
5310#[allow(clippy::too_many_arguments)]
5323pub fn phase_platform_lock(
5324 target: BuildTarget,
5325 selected: Platform,
5326 parsed: &[ParsedFile],
5327 groups: &BTreeMap<String, Vec<usize>>,
5328 kinds: &BTreeMap<String, UnitKind>,
5329 unit_tables: &HashMap<String, UnitTable>,
5330 unit_consumes: &HashMap<String, Vec<String>>,
5331 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5332 unit_flattened: &HashMap<String, HashMap<String, String>>,
5333 worker_groups: &bynk_project::worker_groups::WorkerGroups,
5334 errors: &mut ErrorSink,
5335) {
5336 if selected == Platform::Browser && target == BuildTarget::Workers {
5341 errors.push_for(
5342 None,
5343 CompileError::new(
5344 "bynk.target.browser_bundle_only",
5345 Span::default(),
5346 "`--platform browser` builds only the in-process `Bundle` topology, but `--target workers` was selected; a browser cannot run the Workers wire-call model",
5347 )
5348 .with_note("build the browser target with `--target bundle` (the default)"),
5349 );
5350 return;
5351 }
5352 let mut per_context: Vec<(String, BTreeMap<Platform, String>)> = Vec::new();
5357 let mut names: Vec<&String> = groups.keys().collect();
5358 names.sort();
5359 for name in names {
5360 if kinds.get(name.as_str()) != Some(&UnitKind::Context) {
5361 continue;
5362 }
5363 let Some(table) = unit_tables.get(name.as_str()) else {
5364 continue;
5365 };
5366 let native = native_platforms_of_context(
5367 name,
5368 table,
5369 unit_tables,
5370 unit_consumes,
5371 unit_consumes_aliases,
5372 unit_flattened,
5373 );
5374 if !native.is_empty() {
5375 per_context.push((name.clone(), native));
5376 }
5377 }
5378 let units = lock_units(target, per_context, worker_groups);
5379 for LockUnit {
5380 group,
5381 members,
5382 native,
5383 } in units
5384 {
5385 let Some(violation) = lock_violation(&native, selected) else {
5386 continue;
5387 };
5388 let ctx = match &group {
5390 Some(key) => format!("Worker group `{key}`"),
5391 None => format!("context `{}`", members[0]),
5392 };
5393 let span_for = |unit: &str| {
5394 members
5395 .iter()
5396 .find_map(|m| {
5397 groups
5398 .get(m)
5399 .and_then(|idx| consumes_span_of(parsed, idx, unit))
5400 })
5401 .map(|(_, s)| s)
5402 .unwrap_or_default()
5403 };
5404 match violation {
5405 LockViolation::Required { needed, unit } => {
5406 errors.push_for(
5407 None,
5408 CompileError::new(
5409 "bynk.target.vendor_required",
5410 span_for(&unit),
5411 format!(
5412 "{ctx} uses the platform-native capabilities of `{unit}`, which run only on the `{}` platform, but the build selects `--platform {}`",
5413 needed.as_str(),
5414 selected.as_str(),
5415 ),
5416 )
5417 .with_note(
5418 "build with the matching `--platform`, or remove the platform-native dependency to stay portable",
5419 ),
5420 );
5421 }
5422 LockViolation::Conflict { a, b } => {
5423 errors.push_for(
5424 None,
5425 CompileError::new(
5426 "bynk.target.vendor_conflict",
5427 span_for(&a.1),
5428 format!(
5429 "one deployment unit (via {ctx}) uses platform-native capabilities from two mutually-exclusive platforms: `{}` (from `{}`) and `{}` (from `{}`)",
5430 a.0.as_str(),
5431 a.1,
5432 b.0.as_str(),
5433 b.1,
5434 ),
5435 )
5436 .with_note(if group.is_some() {
5437 "the members of a `[deploy.workers]` group share one Worker: move the conflicting contexts into different groups (or out of any group), or remove one of the platform-native dependencies"
5438 } else {
5439 "split the consumers into separate deployment units (`--target workers`), or remove one of the platform-native dependencies"
5440 }),
5441 );
5442 }
5443 }
5444 }
5445}
5446
5447pub fn phase_secrets_computed_name(
5470 target: BuildTarget,
5471 parsed: &[ParsedFile],
5472 groups: &BTreeMap<String, Vec<usize>>,
5473 kinds: &BTreeMap<String, UnitKind>,
5474 unit_flattened: &HashMap<String, HashMap<String, String>>,
5475 errors: &mut ErrorSink,
5476) {
5477 if target != BuildTarget::Workers {
5478 return;
5479 }
5480 for (name, indices) in groups {
5481 if kinds.get(name) != Some(&UnitKind::Context) {
5482 continue;
5483 }
5484 let Some(flattened) = unit_flattened.get(name) else {
5485 continue;
5486 };
5487 for &i in indices {
5488 let SourceUnit::Context(ctx) = &parsed[i].unit() else {
5489 continue;
5490 };
5491 let items = &ctx.items;
5494 let handlers = items.iter().filter_map(|item| match item {
5495 CommonsItem::Service(s) => Some(s.handlers.iter()),
5496 CommonsItem::Agent(a) => Some(a.handlers.iter()),
5497 _ => None,
5498 });
5499 let providers = items.iter().filter_map(|item| match item {
5500 CommonsItem::Provider(p) => Some(p),
5501 _ => None,
5502 });
5503 let (_, mut warnings) = crate::secrets::secret_reads_of(handlers.flatten(), flattened);
5504 warnings.extend(crate::secrets::provider_secret_reads_of(providers, flattened).1);
5505 let rel = parsed[i].identity_path();
5506 errors.extend_for(Some(&rel), warnings);
5507 }
5508 }
5509}
5510
5511pub fn phase_topology(
5518 target: BuildTarget,
5519 parsed: &[ParsedFile],
5520 groups: &BTreeMap<String, Vec<usize>>,
5521 kinds: &BTreeMap<String, UnitKind>,
5522 unit_tables: &HashMap<String, UnitTable>,
5523 errors: &mut ErrorSink,
5524) {
5525 phase_workers_unprovided_capabilities(target, parsed, groups, kinds, unit_tables, errors);
5526 crate::email::phase_duplicate_addresses(parsed, groups, kinds, errors);
5527 crate::queue_consumers::phase_duplicate_queue_consumers(parsed, groups, kinds, errors);
5528 phase_workers_ws_open_split(target, parsed, groups, kinds, unit_tables, errors);
5529}
5530
5531pub fn phase_workers_unprovided_capabilities(
5542 target: BuildTarget,
5543 parsed: &[ParsedFile],
5544 groups: &BTreeMap<String, Vec<usize>>,
5545 kinds: &BTreeMap<String, UnitKind>,
5546 unit_tables: &HashMap<String, UnitTable>,
5547 errors: &mut ErrorSink,
5548) {
5549 if target != BuildTarget::Workers {
5550 return;
5551 }
5552 phase_unprovided_capabilities(
5553 &UnprovidedReason::Workers,
5554 parsed,
5555 groups,
5556 kinds,
5557 unit_tables,
5558 errors,
5559 );
5560}
5561
5562pub enum UnprovidedReason {
5565 Workers,
5568 BundleComposition { trigger: String, because: String },
5576}
5577
5578pub fn composed_in_bundle_root(table: &UnitTable) -> bool {
5585 !table.services.is_empty()
5586}
5587
5588pub fn phase_unprovided_capabilities(
5593 reason: &UnprovidedReason,
5594 parsed: &[ParsedFile],
5595 groups: &BTreeMap<String, Vec<usize>>,
5596 kinds: &BTreeMap<String, UnitKind>,
5597 unit_tables: &HashMap<String, UnitTable>,
5598 errors: &mut ErrorSink,
5599) {
5600 for (name, indices) in groups {
5601 if kinds.get(name) != Some(&UnitKind::Context) {
5602 continue;
5603 }
5604 let Some(table) = unit_tables.get(name) else {
5605 continue;
5606 };
5607 if matches!(reason, UnprovidedReason::BundleComposition { .. })
5608 && !composed_in_bundle_root(table)
5609 {
5610 continue;
5611 }
5612 let mut reported: HashSet<String> = HashSet::new();
5615 for &i in indices {
5616 let SourceUnit::Context(ctx) = &parsed[i].unit() else {
5617 continue;
5618 };
5619 let mut givens: Vec<&CapRef> = Vec::new();
5620 for item in &ctx.items {
5621 match item {
5622 CommonsItem::Service(s) => {
5623 givens.extend(s.handlers.iter().flat_map(|h| &h.given));
5624 }
5625 CommonsItem::Agent(a) => {
5626 givens.extend(a.handlers.iter().flat_map(|h| &h.given));
5627 }
5628 CommonsItem::Provider(p) => givens.extend(&p.given),
5629 _ => {}
5630 }
5631 }
5632 for cap in givens {
5633 if cap.context.is_some()
5637 || !table.capabilities.contains_key(&cap.name.name)
5638 || table.providers.contains_key(&cap.name.name)
5639 || table.derived.contains_key(&cap.name.name)
5641 || table.exported_capabilities.contains(&cap.name.name)
5642 || !reported.insert(cap.name.name.clone())
5643 {
5644 continue;
5645 }
5646 let cap_name = &cap.name.name;
5647 let error = match reason {
5648 UnprovidedReason::Workers => CompileError::new(
5649 "bynk.capability.not_provided",
5650 cap.span,
5651 format!(
5652 "capability `{cap_name}` is required here but has no provider in context `{name}`; a Worker builds every capability its handlers are given"
5653 ),
5654 )
5655 .with_note(format!(
5656 "add `provides {cap_name} = …` to `{name}`, or build for `--target bundle`, where the host supplies it"
5657 )),
5658 UnprovidedReason::BundleComposition { trigger, because } => {
5659 CompileError::new(
5660 "bynk.capability.not_provided",
5661 cap.span,
5662 format!(
5663 "capability `{cap_name}` is required here but has no provider in context `{name}`; this program's composition root builds every context, so nothing else can supply it"
5664 ),
5665 )
5666 .with_note(format!(
5667 "`{trigger}` {because}, so the bundle has a composition root (`composeApp`), which builds `{name}` with the providers it declares"
5668 ))
5669 .with_note(format!(
5670 "add `provides {cap_name} = …` to `{name}`; a test `stub` replaces it in the cases that stub it, but the program still needs one"
5671 ))
5672 }
5673 };
5674 errors.push_for(Some(&parsed[i].identity_path()), error);
5675 }
5676 }
5677 }
5678}
5679
5680pub type UnitCallees = HashMap<String, HashMap<ExprId, checker::Callee>>;
5686
5687pub fn is_events_emit(callee: &checker::Callee) -> bool {
5691 matches!(
5692 callee,
5693 checker::Callee::Capability {
5694 op,
5695 first_party: Some(firstparty::FirstPartyCap::Events),
5696 ..
5697 } if op == "emit"
5698 )
5699}
5700
5701pub fn unit_table_uses_emit(
5712 table: &UnitTable,
5713 callees: Option<&HashMap<ExprId, checker::Callee>>,
5714) -> bool {
5715 let Some(callees) = callees else {
5716 debug_assert!(
5717 false,
5718 "unit_table_uses_emit: no Callee map for a checked unit"
5719 );
5720 return false;
5721 };
5722 let bodies = table
5723 .services
5724 .values()
5725 .flat_map(|s| s.handlers.iter().map(|h| &h.body))
5726 .chain(
5727 table
5728 .agents
5729 .values()
5730 .flat_map(|a| a.handlers.iter().map(|h| &h.body)),
5731 )
5732 .chain(
5733 table
5734 .providers
5735 .values()
5736 .flat_map(|p| p.ops.iter().map(|op| &op.body)),
5737 );
5738 let mut stack: Vec<&Expr> = Vec::new();
5739 for body in bodies {
5740 for s in &body.statements {
5741 statement_exprs(s, &mut stack);
5742 }
5743 stack.push(&body.tail);
5744 }
5745 while let Some(e) = stack.pop() {
5746 if callees.get(&e.id).is_some_and(is_events_emit) {
5747 return true;
5748 }
5749 stack.extend(expr_children(e));
5750 }
5751 false
5752}
5753
5754pub fn composition_root_trigger(
5764 kinds: &BTreeMap<String, UnitKind>,
5765 unit_consumes: &HashMap<String, Vec<String>>,
5766 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5767 unit_tables: &HashMap<String, UnitTable>,
5768 unit_callees: &UnitCallees,
5769 unit_flattened: &HashMap<String, HashMap<String, String>>,
5770) -> Option<(String, String)> {
5771 let mut consumers: Vec<(&String, &Vec<String>)> = unit_consumes.iter().collect();
5774 consumers.sort();
5775 for (name, targets) in consumers {
5776 if kinds.get(name) != Some(&UnitKind::Context) {
5777 continue;
5778 }
5779 if let Some(t) = targets.iter().find(|t| {
5780 unit_tables
5781 .get(*t)
5782 .is_some_and(|other| !other.services.is_empty())
5783 }) {
5784 return Some((name.clone(), format!("consumes `{t}`, which has services")));
5785 }
5786 }
5787 for (name, kind) in kinds {
5791 if *kind != UnitKind::Context {
5792 continue;
5793 }
5794 let Some(table) = unit_tables.get(name) else {
5795 continue;
5796 };
5797 let consumed = unit_consumes.get(name).cloned().unwrap_or_default();
5798 let aliases = unit_consumes_aliases.get(name).cloned().unwrap_or_default();
5799 let flattened = unit_flattened.get(name).cloned().unwrap_or_default();
5800 let uses_cross_cap = !handler_cross_caps(table, name, &consumed, &aliases, &flattened)
5801 .is_empty()
5802 || table.providers.values().any(|p| {
5803 p.given.iter().any(|g| {
5804 g.is_cross_context()
5805 || (g.prefix().is_none() && flattened.contains_key(g.key()))
5809 })
5810 });
5811 let because = if uses_cross_cap {
5821 "is given a capability another unit provides"
5822 } else if unit_table_uses_emit(table, unit_callees.get(name)) {
5823 "emits events"
5824 } else if !table.derived.is_empty() {
5825 "derives a capability"
5826 } else {
5827 continue;
5828 };
5829 return Some((name.clone(), because.to_string()));
5830 }
5831 None
5832}
5833
5834#[allow(clippy::too_many_arguments)]
5846pub fn phase_bundle_composition_unprovided(
5847 target: BuildTarget,
5848 parsed: &[ParsedFile],
5849 groups: &BTreeMap<String, Vec<usize>>,
5850 kinds: &BTreeMap<String, UnitKind>,
5851 unit_consumes: &HashMap<String, Vec<String>>,
5852 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
5853 unit_tables: &HashMap<String, UnitTable>,
5854 unit_callees: &UnitCallees,
5855 unit_flattened: &HashMap<String, HashMap<String, String>>,
5856 errors: &mut ErrorSink,
5857) {
5858 crate::caller_admission::phase_caller_admission(
5863 parsed,
5864 groups,
5865 kinds,
5866 unit_tables,
5867 unit_callees,
5868 errors,
5869 );
5870 if target != BuildTarget::Bundle || !errors.is_empty() {
5871 return;
5872 }
5873 let Some((trigger, because)) = composition_root_trigger(
5874 kinds,
5875 unit_consumes,
5876 unit_consumes_aliases,
5877 unit_tables,
5878 unit_callees,
5879 unit_flattened,
5880 ) else {
5881 return;
5882 };
5883 phase_unprovided_capabilities(
5884 &UnprovidedReason::BundleComposition { trigger, because },
5885 parsed,
5886 groups,
5887 kinds,
5888 unit_tables,
5889 errors,
5890 );
5891}
5892
5893pub fn phase_workers_ws_open_split(
5903 target: BuildTarget,
5904 parsed: &[ParsedFile],
5905 groups: &BTreeMap<String, Vec<usize>>,
5906 kinds: &BTreeMap<String, UnitKind>,
5907 unit_tables: &HashMap<String, UnitTable>,
5908 errors: &mut ErrorSink,
5909) {
5910 if target != BuildTarget::Workers {
5911 return;
5912 }
5913 for (name, indices) in groups {
5914 if kinds.get(name) != Some(&UnitKind::Context) || indices.len() < 2 {
5915 continue;
5916 }
5917 let Some(table) = unit_tables.get(name) else {
5918 continue;
5919 };
5920 let local_agents: HashSet<String> = table.agents.keys().cloned().collect();
5921 for &i in indices {
5922 let SourceUnit::Context(ctx) = &parsed[i].unit() else {
5923 continue;
5924 };
5925 for item in &ctx.items {
5926 let CommonsItem::Service(service) = item else {
5927 continue;
5928 };
5929 if !matches!(service.protocol, ServiceProtocol::WebSocket { .. }) {
5930 continue;
5931 }
5932 for open in service
5933 .handlers
5934 .iter()
5935 .filter(|h| matches!(h.kind, HandlerKind::Open))
5936 {
5937 let crate::websocket::WsOpenShape::One(target_agent) =
5938 crate::websocket::analyse_open_shape(&open.body, &local_agents)
5939 else {
5940 continue; };
5942 let declared_here = ctx.items.iter().any(|it| {
5943 matches!(it, CommonsItem::Agent(a) if a.name.name == target_agent.agent)
5944 });
5945 if declared_here {
5946 continue;
5947 }
5948 errors.push_for(
5949 Some(&parsed[i].identity_path()),
5950 CompileError::new(
5951 "bynk.ws.open_transfer_cross_file",
5952 open.span,
5953 format!(
5954 "this `on open` transfers its `connection` to agent `{}`, which is declared in a different file of context `{name}` than the service `{}`",
5955 target_agent.agent, service.name.name
5956 ),
5957 )
5958 .with_note(
5959 "on Workers the open is hosted inside the agent's Durable Object, which is emitted from the file that declares the agent; move the service into the agent's file, or build for `--target bundle`",
5960 ),
5961 );
5962 }
5963 }
5964 }
5965 }
5966}
5967
5968pub fn provider_constructs_agent(p: &ProviderDecl, is_agent: impl Fn(&str) -> bool) -> bool {
5978 fn walk(e: &Expr, is_agent: &dyn Fn(&str) -> bool) -> bool {
5979 if let ExprKind::Call { name, .. } = &e.kind
5980 && is_agent(&name.name)
5981 {
5982 return true;
5983 }
5984 expr_children(e).into_iter().any(|c| walk(c, is_agent))
5985 }
5986 p.ops.iter().any(|op| {
5987 let mut top = Vec::new();
5988 for s in &op.body.statements {
5989 statement_exprs(s, &mut top);
5990 }
5991 top.push(&op.body.tail);
5992 top.into_iter().any(|e| walk(e, &is_agent))
5993 })
5994}
5995
5996pub fn phase_workers_ws_open_key(
6008 target: BuildTarget,
6009 parsed: &[ParsedFile],
6010 groups: &BTreeMap<String, Vec<usize>>,
6011 kinds: &BTreeMap<String, UnitKind>,
6012 unit_tables: &HashMap<String, UnitTable>,
6013 unit_uses: &HashMap<String, Vec<String>>,
6014 errors: &mut ErrorSink,
6015) {
6016 if target != BuildTarget::Workers {
6017 return;
6018 }
6019 for (name, indices) in groups {
6020 if kinds.get(name) != Some(&UnitKind::Context) {
6021 continue;
6022 }
6023 let Some(table) = unit_tables.get(name) else {
6024 continue;
6025 };
6026 let uses = unit_uses.get(name).map(Vec::as_slice).unwrap_or_default();
6029 let consts = crate::consts::visible_consts(table, uses, |u| unit_tables.get(u));
6030 let local_agents: HashSet<String> = table.agents.keys().cloned().collect();
6031 for &i in indices {
6032 let SourceUnit::Context(ctx) = &parsed[i].unit() else {
6033 continue;
6034 };
6035 for item in &ctx.items {
6036 let CommonsItem::Service(service) = item else {
6037 continue;
6038 };
6039 if !matches!(service.protocol, ServiceProtocol::WebSocket { .. }) {
6040 continue;
6041 }
6042 for open in service
6043 .handlers
6044 .iter()
6045 .filter(|h| matches!(h.kind, HandlerKind::Open))
6046 {
6047 let crate::websocket::WsOpenShape::One(target_agent) =
6048 crate::websocket::analyse_open_shape(&open.body, &local_agents)
6049 else {
6050 continue; };
6052 let key = crate::websocket::classify_open_key(open, target_agent.key, |n| {
6053 consts.contains_key(n)
6054 });
6055 if !matches!(key, crate::websocket::WsOpenKey::Other) {
6056 continue;
6057 }
6058 errors.push_for(
6059 Some(&parsed[i].identity_path()),
6060 CompileError::new(
6061 "bynk.ws.open_transfer_key",
6062 target_agent.key.span,
6063 format!(
6064 "the key of this `on open`'s transfer to agent `{}` is not a route parameter, a constant or a literal, so the Workers upgrade cannot address the agent's Durable Object",
6065 target_agent.agent
6066 ),
6067 )
6068 .with_note(
6069 "on Workers the upgrade is routed to the hosting Durable Object before the `on open` body runs; key the agent by a parameter of `on open`, a `const` of the context or of a commons it `uses`, or a literal",
6070 ),
6071 );
6072 }
6073 }
6074 }
6075 }
6076}
6077
6078#[allow(clippy::too_many_arguments)]
6091pub fn phase_workers_provider_agent_cross_context(
6092 target: BuildTarget,
6093 parsed: &[ParsedFile],
6094 groups: &BTreeMap<String, Vec<usize>>,
6095 kinds: &BTreeMap<String, UnitKind>,
6096 unit_tables: &HashMap<String, UnitTable>,
6097 unit_consumes: &HashMap<String, Vec<String>>,
6098 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
6099 unit_flattened: &HashMap<String, HashMap<String, String>>,
6100 errors: &mut ErrorSink,
6101) {
6102 if target != BuildTarget::Workers {
6103 return;
6104 }
6105 for (name, indices) in groups {
6106 if kinds.get(name) != Some(&UnitKind::Context) {
6107 continue;
6108 }
6109 let consumed = unit_consumes.get(name).cloned().unwrap_or_default();
6110 let aliases = unit_consumes_aliases.get(name).cloned().unwrap_or_default();
6111 let flattened = unit_flattened.get(name).cloned().unwrap_or_default();
6112 let mut reported: HashSet<(String, String)> = HashSet::new();
6113 for &i in indices {
6114 let SourceUnit::Context(ctx) = &parsed[i].unit() else {
6115 continue;
6116 };
6117 let mut givens: Vec<&CapRef> = Vec::new();
6118 for item in &ctx.items {
6119 match item {
6120 CommonsItem::Service(s) => {
6121 givens.extend(s.handlers.iter().flat_map(|h| &h.given));
6122 }
6123 CommonsItem::Agent(a) => {
6124 givens.extend(a.handlers.iter().flat_map(|h| &h.given));
6125 }
6126 CommonsItem::Provider(p) => givens.extend(&p.given),
6127 _ => {}
6128 }
6129 }
6130 for cap in givens {
6131 let target_ctx = match cap.prefix() {
6133 Some(p) => resolve_consume_prefix(&p, &consumed, &aliases)
6134 .unwrap_or_else(|| name.clone()),
6135 None => flattened
6136 .get(cap.key())
6137 .cloned()
6138 .unwrap_or_else(|| name.clone()),
6139 };
6140 let mut reached: BTreeSet<(String, String)> = BTreeSet::new();
6141 collect_given_closure(
6142 &target_ctx,
6143 cap.key(),
6144 unit_tables,
6145 unit_consumes,
6146 unit_consumes_aliases,
6147 unit_flattened,
6148 &mut reached,
6149 );
6150 for (unit, key) in reached {
6151 if unit == *name {
6152 continue;
6153 }
6154 let Some(table) = unit_tables.get(&unit) else {
6155 continue;
6156 };
6157 let Some(provider) = table.providers.get(&key) else {
6158 continue;
6159 };
6160 if provider.external
6161 || !provider_constructs_agent(provider, |n| table.agents.contains_key(n))
6162 || !reported.insert((unit.clone(), key.clone()))
6163 {
6164 continue;
6165 }
6166 errors.push_for(
6167 Some(&parsed[i].identity_path()),
6168 CompileError::new(
6169 "bynk.capability.provider_agent_cross_context",
6170 cap.span,
6171 format!(
6172 "capability `{key}` is provided by `{}` in context `{unit}`, which constructs `{unit}`'s agents; on Workers context `{name}` would build that provider with its own `env`, which has no binding for those agents' Durable Objects",
6173 provider.provider_name.name
6174 ),
6175 )
6176 .with_note(format!(
6177 "call a `{unit}` service that uses `{key}` instead, or build for `--target bundle`, where every context shares one process"
6178 )),
6179 );
6180 }
6181 }
6182 }
6183 }
6184}
6185
6186pub fn phase_file_index(
6189 groups: &BTreeMap<String, Vec<usize>>,
6190 parsed: &[ParsedFile],
6191) -> HashMap<String, FileDeclIndex> {
6192 let mut unit_file_index: HashMap<String, FileDeclIndex> = HashMap::new();
6193 for (name, indices) in groups {
6194 unit_file_index.insert(name.clone(), build_file_decl_index(indices, parsed));
6195 }
6196 unit_file_index
6197}
6198
6199pub struct UnitInfo {
6207 pub kind: UnitKind,
6208 pub table: UnitTable,
6209 pub uses: Vec<String>,
6210 pub consumes: Vec<String>,
6211 pub flattened: HashMap<String, String>,
6212 pub aliases: HashMap<String, String>,
6213 pub exports: HashMap<String, Visibility>,
6214 pub file_index: FileDeclIndex,
6215 pub files: Vec<usize>,
6216}
6217
6218#[allow(clippy::too_many_arguments)]
6225pub fn assemble_unit_info(
6226 groups: &BTreeMap<String, Vec<usize>>,
6227 kinds: &BTreeMap<String, UnitKind>,
6228 unit_tables: &HashMap<String, UnitTable>,
6229 unit_uses: &HashMap<String, Vec<String>>,
6230 unit_consumes: &HashMap<String, Vec<String>>,
6231 unit_flattened: &HashMap<String, HashMap<String, String>>,
6232 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
6233 exports_visibility: &HashMap<String, HashMap<String, Visibility>>,
6234 unit_file_index: &HashMap<String, FileDeclIndex>,
6235) -> BTreeMap<String, UnitInfo> {
6236 groups
6237 .iter()
6238 .map(|(name, indices)| {
6239 let info = UnitInfo {
6240 kind: *kinds.get(name).unwrap(),
6241 table: unit_tables.get(name).unwrap().clone(),
6242 uses: unit_uses.get(name).cloned().unwrap_or_default(),
6243 consumes: unit_consumes.get(name).cloned().unwrap_or_default(),
6244 flattened: unit_flattened.get(name).cloned().unwrap_or_default(),
6245 aliases: unit_consumes_aliases.get(name).cloned().unwrap_or_default(),
6246 exports: exports_visibility.get(name).cloned().unwrap_or_default(),
6247 file_index: unit_file_index
6248 .get(name)
6249 .cloned()
6250 .unwrap_or_else(|| FileDeclIndex {
6251 types: HashMap::new(),
6252 fns: HashMap::new(),
6253 methods: HashMap::new(),
6254 agents: HashMap::new(),
6255 capabilities: HashMap::new(),
6256 }),
6257 files: indices.clone(),
6258 };
6259 (name.clone(), info)
6260 })
6261 .collect()
6262}
6263
6264pub fn collect_unit_methods(
6269 indices: &[usize],
6270 parsed: &[ParsedFile],
6271) -> HashMap<String, Vec<FnDecl>> {
6272 let mut local_methods_for_type: HashMap<String, Vec<FnDecl>> = HashMap::new();
6273 for &j in indices {
6274 for item in parsed[j].items() {
6275 if let CommonsItem::Fn(f) = item
6276 && let FnName::Method { type_name, .. } = &f.name
6277 {
6278 local_methods_for_type
6279 .entry(type_name.name.clone())
6280 .or_default()
6281 .push(f.clone());
6282 }
6283 }
6284 }
6285 local_methods_for_type
6286}
6287
6288fn suggest_alias(target: &str, type_name: &str) -> String {
6292 let last = target.rsplit('.').next().unwrap_or(target);
6293 let mut chars = last.chars();
6294 let head: String = chars
6295 .next()
6296 .map(|c| c.to_uppercase().collect())
6297 .unwrap_or_default();
6298 format!("{head}{}{type_name}", chars.as_str())
6299}
6300
6301#[allow(clippy::too_many_arguments)]
6307pub fn merge_consumed_exports(
6308 name: &str,
6309 parsed: &[ParsedFile],
6310 unit_info: &BTreeMap<String, UnitInfo>,
6311 combined_types: &mut HashMap<String, Arc<TypeDecl>>,
6312 combined_methods: &mut HashMap<String, ResolverMethodTable>,
6313 imported_from: &mut HashMap<String, String>,
6314 imported_from_kind: &mut HashMap<String, UnitKind>,
6315 errors: &mut ErrorSink,
6316) -> HashMap<String, ConsumedType> {
6317 let mut consumed_types: HashMap<String, ConsumedType> = HashMap::new();
6323
6324 for t in unit_info.get(name).into_iter().flat_map(|i| &i.consumes) {
6328 let used = &unit_info.get(t).expect("consumed unit present").table;
6329 let used_exports = &unit_info[t].exports;
6330 let renames: HashMap<String, String> = unit_info[name]
6336 .table
6337 .consumed_type_aliases
6338 .iter()
6339 .filter(|(_, a)| a.target == *t)
6340 .map(|(alias, a)| (a.original.clone(), alias.clone()))
6341 .collect();
6342 for (type_name, vis) in used_exports {
6343 let Some(decl) = used.types.get(type_name) else {
6344 continue;
6345 };
6346 let original = type_name;
6347 let aliased = renames.contains_key(original);
6348 let type_name = renames.get(original).unwrap_or(original);
6349 let decl = &crate::symbols::rename_consumed_decl(decl, type_name, &renames);
6350 let local_value = crate::symbols::local_value_kind(&unit_info[name].table, type_name)
6354 .map(|(kind, _)| kind)
6355 .filter(|kind| !matches!(*kind, "type" | "event"));
6356 if unit_info[name]
6359 .table
6360 .unselected_consumed_types
6361 .contains(type_name)
6362 && (combined_types.contains_key(type_name) || local_value.is_some())
6363 {
6364 continue;
6365 }
6366 if combined_types.contains_key(type_name) || local_value.is_some() {
6367 let consumes_site = consumes_span_of(parsed, &unit_info[name].files, t);
6369 let consumes_span = consumes_site.map(|(_, s)| s).unwrap_or_default();
6370 let consumes_file = consumes_site.map(|(i, _)| parsed[i].identity_path());
6371 let in_scope = match local_value {
6372 Some(kind) => format!("this context declares a {kind} of the same name"),
6373 None => "a type of the same name is already in scope".to_string(),
6374 };
6375 let clashes_alias = !aliased
6379 && unit_info[name]
6380 .table
6381 .consumed_type_aliases
6382 .contains_key(type_name);
6383 if aliased || clashes_alias {
6384 let what = if aliased {
6385 format!("aliases an export of `{t}` as `{type_name}`, but {in_scope}")
6386 } else {
6387 format!(
6388 "consumes `{t}` which exports type `{type_name}`, but an alias of the same name is in scope"
6389 )
6390 };
6391 errors.push_for(
6392 consumes_file.as_deref(),
6393 CompileError::new(
6394 "bynk.consumes.type_alias_conflict",
6395 consumes_span,
6396 format!("context `{name}` {what}"),
6397 )
6398 .with_note("choose an alias no other declaration in this context uses"),
6399 );
6400 continue;
6401 }
6402 errors.push_for(consumes_file.as_deref(),
6403 CompileError::new(
6404 "bynk.consumes.name_conflict",
6405 consumes_span,
6406 format!(
6407 "context `{name}` consumes `{t}` which exports type `{type_name}`, but {in_scope}",
6408 ),
6409 )
6410 .with_note(format!(
6411 "alias it so the two no longer share a name: `consumes {t} {{ …, {type_name} as {t_alias} }}`, then write `{t_alias}` for `{t}`'s type",
6412 t_alias = suggest_alias(t, type_name),
6413 )),
6414 );
6415 continue;
6416 }
6417 combined_types.insert(type_name.clone(), decl.clone());
6418 imported_from.insert(type_name.clone(), t.clone());
6419 imported_from_kind.insert(type_name.clone(), UnitKind::Context);
6420 consumed_types.insert(
6421 type_name.clone(),
6422 ConsumedType {
6423 owning_context: t.clone(),
6424 visibility: *vis,
6425 },
6426 );
6427 if let Some(mt) = used.methods.get(original) {
6435 let entry = combined_methods.entry(type_name.clone()).or_default();
6436 for (m, decl) in &mt.instance {
6437 entry
6438 .instance
6439 .entry(m.clone())
6440 .or_insert_with(|| decl.clone());
6441 }
6442 }
6446 }
6447 }
6448
6449 consumed_types
6450}
6451
6452#[allow(clippy::too_many_arguments)]
6490pub fn close_reachable_types(
6491 name: &str,
6492 parsed: &[ParsedFile],
6493 unit_info: &BTreeMap<String, UnitInfo>,
6494 combined_types: &mut HashMap<String, Arc<TypeDecl>>,
6495 combined_fns: &HashMap<String, Arc<FnDecl>>,
6496 combined_methods: &mut HashMap<String, ResolverMethodTable>,
6497 imported_from: &mut HashMap<String, String>,
6498 imported_from_kind: &mut HashMap<String, UnitKind>,
6499 errors: &mut ErrorSink,
6500) -> ReachedTypes {
6501 let mut conflicted: HashSet<String> = HashSet::new();
6502 let mut shadowed = ShadowedReaches::default();
6503 let mut consumed_signatures = consumed_service_seeds(name, unit_info);
6504 consumed_signatures.extend(used_const_seeds(name, unit_info));
6507 let hidden = close_imported(
6508 unit_info,
6509 combined_types,
6510 combined_fns,
6511 combined_methods,
6512 imported_from,
6513 imported_from_kind,
6514 consumed_signatures,
6515 |r, owner, bound| {
6516 if r.signature {
6520 return;
6521 }
6522 let bound = bound.unwrap_or(name);
6523 let directly_used = unit_info[name].uses.iter().any(|u| u == owner);
6528 if bound != owner && directly_used {
6532 shadowed.0.insert(
6533 (r.scope.clone(), r.name.clone()),
6534 ShadowedType {
6535 name: r.name.clone(),
6536 owner: owner.to_string(),
6537 bound: bound.to_string(),
6538 },
6539 );
6540 }
6541 if bound != owner && !directly_used && conflicted.insert(r.name.clone()) {
6542 let site = uses_span_of(parsed, &unit_info[name].files, &r.via)
6543 .or_else(|| consumes_span_of(parsed, &unit_info[name].files, &r.via));
6544 let span = site.map(|(_, s)| s).unwrap_or_default();
6545 let file = site.map(|(i, _)| parsed[i].identity_path());
6546 errors.push_for(
6547 file.as_deref(),
6548 CompileError::new(
6549 "bynk.uses.name_conflict",
6550 span,
6551 format!(
6552 "`{via}` brings in declarations that use type `{t}` from `{owner}`, \
6553 but `{t}` in `{name}` names `{bound}`'s type",
6554 via = r.via,
6555 t = r.name,
6556 ),
6557 )
6558 .with_note(
6559 "rename one of the two types; the imported declarations cannot be \
6560 checked against a different type of the same name",
6561 ),
6562 );
6563 }
6564 },
6565 );
6566 ReachedTypes { hidden, shadowed }
6567}
6568
6569pub fn close_view_types(
6589 imported: &[String],
6590 unit_tables: &HashMap<String, UnitTable>,
6591 unit_uses: &HashMap<String, Vec<String>>,
6592 types: &mut HashMap<String, Arc<TypeDecl>>,
6593 fns: &HashMap<String, Arc<FnDecl>>,
6594 methods: &mut HashMap<String, ResolverMethodTable>,
6595 harness: bool,
6598) -> ViewReach {
6599 let mut imported_from: HashMap<String, String> = HashMap::new();
6600 for u in imported {
6601 let Some(t) = unit_tables.get(u) else {
6602 continue;
6603 };
6604 for (n, d) in &t.types {
6605 if types.get(n).is_some_and(|v| Arc::ptr_eq(v, d)) {
6606 imported_from.entry(n.clone()).or_insert_with(|| u.clone());
6607 }
6608 }
6609 for (n, d) in &t.fns {
6610 if fns.get(n).is_some_and(|v| Arc::ptr_eq(v, d)) {
6611 imported_from.entry(n.clone()).or_insert_with(|| u.clone());
6612 }
6613 }
6614 }
6615 let seeds = if harness {
6616 harness_seeds(imported, unit_tables)
6617 } else {
6618 Vec::new()
6619 };
6620 let mut conflicts: Vec<ViewConflict> = Vec::new();
6621 let mut seen: HashSet<String> = HashSet::new();
6622 let hidden = close_imported(
6623 &TableScopes {
6624 tables: unit_tables,
6625 uses: unit_uses,
6626 },
6627 types,
6628 fns,
6629 methods,
6630 &mut imported_from,
6631 &mut HashMap::new(),
6632 seeds,
6633 |r, owner, bound| {
6634 if r.signature {
6638 return;
6639 }
6640 if bound != Some(owner) && seen.insert(r.name.clone()) {
6641 conflicts.push(ViewConflict {
6642 name: r.name.clone(),
6643 owner: owner.to_string(),
6644 bound: bound.map(str::to_string),
6645 via: r.via.clone(),
6646 });
6647 }
6648 },
6649 );
6650 ViewReach { hidden, conflicts }
6651}
6652
6653fn harness_seeds(imported: &[String], unit_tables: &HashMap<String, UnitTable>) -> Vec<Reached> {
6669 let mut seeds = Vec::new();
6670 let tables = || {
6671 imported
6672 .iter()
6673 .filter_map(|u| Some((u, unit_tables.get(u)?)))
6674 };
6675 for (u, t) in tables() {
6676 let mut actors: Vec<_> = t.actors.iter().collect();
6677 actors.sort_by_key(|(n, _)| n.as_str());
6678 for (_, a) in actors {
6679 if let Some(id) = &a.identity {
6680 let mut names = Vec::new();
6681 type_ref_names(id, &HashSet::new(), &mut names);
6682 push_refs(names, u, u, &mut seeds);
6683 }
6684 }
6685 }
6686 for (u, t) in tables() {
6687 let mut services: Vec<&ServiceDecl> = t.services.values().collect();
6688 services.sort_by(|a, b| a.name.name.cmp(&b.name.name));
6689 for h in services.into_iter().flat_map(|s| &s.handlers) {
6690 let mut names = Vec::new();
6691 for p in &h.params {
6692 type_ref_names(&p.type_ref, &HashSet::new(), &mut names);
6693 }
6694 type_ref_names(&h.return_type, &HashSet::new(), &mut names);
6695 push_refs_with(names, u, u, true, &mut seeds);
6696 }
6697 }
6698 seeds
6699}
6700
6701#[derive(Debug, Clone, Default)]
6703pub struct ViewReach {
6704 pub hidden: BTreeMap<String, String>,
6706 pub conflicts: Vec<ViewConflict>,
6709}
6710
6711#[derive(Debug, Clone, PartialEq, Eq)]
6714pub struct ViewConflict {
6715 pub name: String,
6717 pub owner: String,
6719 pub bound: Option<String>,
6722 pub via: String,
6724}
6725
6726trait ScopeTables {
6732 fn scope(&self, unit: &str) -> Option<(&UnitTable, &[String], Option<UnitKind>)>;
6733}
6734
6735impl ScopeTables for BTreeMap<String, UnitInfo> {
6736 fn scope(&self, unit: &str) -> Option<(&UnitTable, &[String], Option<UnitKind>)> {
6737 self.get(unit)
6738 .map(|i| (&i.table, i.uses.as_slice(), Some(i.kind)))
6739 }
6740}
6741
6742struct TableScopes<'a> {
6744 tables: &'a HashMap<String, UnitTable>,
6745 uses: &'a HashMap<String, Vec<String>>,
6746}
6747
6748impl ScopeTables for TableScopes<'_> {
6749 fn scope(&self, unit: &str) -> Option<(&UnitTable, &[String], Option<UnitKind>)> {
6750 let table = self.tables.get(unit)?;
6751 let uses = self.uses.get(unit).map(Vec::as_slice).unwrap_or_default();
6752 Some((table, uses, table.kind))
6753 }
6754}
6755
6756struct Reached {
6761 name: String,
6762 scope: String,
6763 via: String,
6764 signature: bool,
6768}
6769
6770fn push_refs(names: Vec<String>, scope: &str, via: &str, queue: &mut Vec<Reached>) {
6771 push_refs_with(names, scope, via, false, queue);
6772}
6773
6774fn push_refs_with(
6775 names: Vec<String>,
6776 scope: &str,
6777 via: &str,
6778 signature: bool,
6779 queue: &mut Vec<Reached>,
6780) {
6781 queue.extend(names.into_iter().map(|n| Reached {
6782 name: n,
6783 scope: scope.to_string(),
6784 via: via.to_string(),
6785 signature,
6786 }));
6787}
6788
6789fn consumed_service_seeds(name: &str, unit_info: &BTreeMap<String, UnitInfo>) -> Vec<Reached> {
6796 let mut out = Vec::new();
6797 let Some(info) = unit_info.get(name) else {
6798 return out;
6799 };
6800 for t in &info.consumes {
6801 let Some(consumed) = unit_info.get(t) else {
6802 continue;
6803 };
6804 let mut services: Vec<&ServiceDecl> = consumed.table.services.values().collect();
6805 services.sort_by(|a, b| a.name.name.cmp(&b.name.name));
6806 for s in services {
6807 if let Some(h) = s.handlers.iter().find(|h| h.kind == HandlerKind::Call) {
6810 let mut names = Vec::new();
6811 for p in &h.params {
6812 type_ref_names(&p.type_ref, &HashSet::new(), &mut names);
6813 }
6814 type_ref_names(&h.return_type, &HashSet::new(), &mut names);
6815 push_refs_with(names, t, t, true, &mut out);
6816 }
6817 }
6818 }
6819 out
6820}
6821
6822fn used_const_seeds(name: &str, unit_info: &BTreeMap<String, UnitInfo>) -> Vec<Reached> {
6827 let mut out = Vec::new();
6828 let Some(info) = unit_info.get(name) else {
6829 return out;
6830 };
6831 for t in &info.uses {
6832 let Some(used) = unit_info.get(t) else {
6833 continue;
6834 };
6835 let mut consts: Vec<&ConstDecl> = used
6836 .table
6837 .consts
6838 .values()
6839 .filter(|c| c.private.is_none())
6840 .filter(|c| crate::symbols::local_value_kind(&info.table, &c.name.name).is_none())
6841 .collect();
6842 consts.sort_by(|a, b| a.name.name.cmp(&b.name.name));
6843 for c in consts {
6844 let mut names = Vec::new();
6845 type_ref_names(&c.ty, &HashSet::new(), &mut names);
6846 push_refs(names, t, t, &mut out);
6847 }
6848 }
6849 out
6850}
6851
6852#[allow(clippy::too_many_arguments)]
6859fn close_imported<S: ScopeTables + ?Sized>(
6860 scopes: &S,
6861 combined_types: &mut HashMap<String, Arc<TypeDecl>>,
6862 combined_fns: &HashMap<String, Arc<FnDecl>>,
6863 combined_methods: &mut HashMap<String, ResolverMethodTable>,
6864 imported_from: &mut HashMap<String, String>,
6865 imported_from_kind: &mut HashMap<String, UnitKind>,
6866 extra_seeds: Vec<Reached>,
6869 mut on_bound: impl FnMut(&Reached, &str, Option<&str>),
6870) -> BTreeMap<String, String> {
6871 let mut queue: Vec<Reached> = Vec::new();
6872 let mut type_names: Vec<&String> = combined_types.keys().collect();
6873 type_names.sort();
6874 for n in type_names {
6875 if let Some(unit) = imported_from.get(n) {
6876 push_refs(
6877 type_decl_ref_names(&combined_types[n]),
6878 unit,
6879 unit,
6880 &mut queue,
6881 );
6882 }
6883 }
6884 let mut fn_names: Vec<&String> = combined_fns.keys().collect();
6885 fn_names.sort();
6886 for n in fn_names {
6887 if let Some(unit) = imported_from.get(n) {
6888 push_refs(
6889 fn_sig_ref_names(&combined_fns[n], &[]),
6890 unit,
6891 unit,
6892 &mut queue,
6893 );
6894 }
6895 }
6896 let mut method_types: Vec<&String> = combined_methods.keys().collect();
6897 method_types.sort();
6898 for t in method_types {
6899 if let Some(unit) = imported_from.get(t) {
6900 let mt = &combined_methods[t];
6901 let attached = combined_types.get(t).map(|d| d.type_params.as_slice());
6902 let mut decls: Vec<&Arc<FnDecl>> =
6903 mt.instance.values().chain(mt.statics.values()).collect();
6904 decls.sort_by_key(|d| d.span.start);
6905 for d in decls {
6906 push_refs(
6907 fn_sig_ref_names(d, attached.unwrap_or_default()),
6908 unit,
6909 unit,
6910 &mut queue,
6911 );
6912 }
6913 }
6914 }
6915 queue.extend(extra_seeds);
6916 queue.reverse();
6919
6920 let mut hidden: BTreeMap<String, String> = BTreeMap::new();
6921 let mut visited: HashSet<(String, String)> = HashSet::new();
6922 while let Some(r) = queue.pop() {
6923 if !visited.insert((r.scope.clone(), r.name.clone())) {
6924 continue;
6925 }
6926 let Some(owner) = type_owner_in_scope(&r.scope, &r.name, scopes) else {
6927 continue;
6928 };
6929 let Some((owner_table, _, owner_kind)) = scopes.scope(owner) else {
6934 continue;
6935 };
6936 if owner_kind != Some(UnitKind::Commons) {
6937 continue;
6938 }
6939 if combined_types.contains_key(&r.name) {
6940 on_bound(&r, owner, imported_from.get(&r.name).map(String::as_str));
6941 continue;
6942 }
6943 let decl = owner_table.types[&r.name].clone();
6944 push_refs_with(
6945 type_decl_ref_names(&decl),
6946 owner,
6947 &r.via,
6948 r.signature,
6949 &mut queue,
6950 );
6951 combined_types.insert(r.name.clone(), decl.clone());
6952 imported_from.insert(r.name.clone(), owner.to_string());
6953 imported_from_kind.insert(r.name.clone(), UnitKind::Commons);
6954 hidden.insert(r.name.clone(), owner.to_string());
6955 if let Some(mt) = owner_table.methods.get(&r.name) {
6958 let entry = combined_methods.entry(r.name.clone()).or_default();
6959 let mut decls: Vec<(&String, &Arc<FnDecl>, bool)> = mt
6960 .instance
6961 .iter()
6962 .map(|(m, d)| (m, d, true))
6963 .chain(mt.statics.iter().map(|(m, d)| (m, d, false)))
6964 .collect();
6965 decls.sort_by_key(|(_, d, _)| d.span.start);
6966 for (m, d, is_instance) in decls {
6967 push_refs_with(
6968 fn_sig_ref_names(d, &decl.type_params),
6969 owner,
6970 &r.via,
6971 r.signature,
6972 &mut queue,
6973 );
6974 let table = if is_instance {
6975 &mut entry.instance
6976 } else {
6977 &mut entry.statics
6978 };
6979 table.entry(m.clone()).or_insert_with(|| d.clone());
6980 }
6981 }
6982 }
6983 hidden
6984}
6985
6986#[derive(Debug, Clone, Default)]
6988pub struct ReachedTypes {
6989 pub hidden: BTreeMap<String, String>,
6992 pub shadowed: ShadowedReaches,
6994}
6995
6996#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
6999pub struct ShadowedType {
7000 pub name: String,
7002 pub owner: String,
7004 pub bound: String,
7007}
7008
7009#[derive(Debug, Clone, Default)]
7019pub struct ShadowedReaches(HashMap<(String, String), ShadowedType>);
7020
7021impl ShadowedReaches {
7022 pub(crate) fn sorted(&self) -> Vec<(&(String, String), &ShadowedType)> {
7025 let mut v: Vec<_> = self.0.iter().collect();
7026 v.sort_by(|a, b| a.0.cmp(b.0));
7027 v
7028 }
7029
7030 pub fn is_empty(&self) -> bool {
7032 self.0.is_empty()
7033 }
7034
7035 pub fn in_type_ref(&self, scope: &str, r: &TypeRef, vars: &[TypeParam]) -> Vec<&ShadowedType> {
7039 let vars: HashSet<&str> = vars.iter().map(|p| p.name.name.as_str()).collect();
7040 let mut names = Vec::new();
7041 type_ref_names(r, &vars, &mut names);
7042 let mut out: Vec<&ShadowedType> = names
7043 .iter()
7044 .filter_map(|n| self.0.get(&(scope.to_string(), n.clone())))
7045 .collect();
7046 out.sort();
7047 out.dedup();
7048 out
7049 }
7050}
7051
7052fn type_owner_in_scope<'a, S: ScopeTables + ?Sized>(
7056 scope: &'a str,
7057 name: &str,
7058 scopes: &'a S,
7059) -> Option<&'a str> {
7060 let (table, uses, _) = scopes.scope(scope)?;
7061 if table.types.contains_key(name) {
7062 return Some(scope);
7063 }
7064 uses.iter()
7065 .find(|u| {
7066 scopes
7067 .scope(u)
7068 .is_some_and(|(t, _, _)| t.types.contains_key(name))
7069 })
7070 .map(String::as_str)
7071}
7072
7073pub(crate) fn type_decl_ref_names(d: &TypeDecl) -> Vec<String> {
7076 let vars: HashSet<&str> = d.type_params.iter().map(|p| p.name.name.as_str()).collect();
7077 let mut out = Vec::new();
7078 match &d.body {
7079 TypeBody::Record(r) => {
7080 for f in &r.fields {
7081 type_ref_names(&f.type_ref, &vars, &mut out);
7082 }
7083 }
7084 TypeBody::Sum(s) => {
7085 for v in &s.variants {
7086 for p in &v.payload {
7087 type_ref_names(&p.type_ref, &vars, &mut out);
7088 }
7089 }
7090 }
7091 TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
7092 }
7093 out
7094}
7095
7096fn fn_sig_ref_names(f: &FnDecl, attached: &[TypeParam]) -> Vec<String> {
7100 let vars: HashSet<&str> = f
7101 .type_params
7102 .iter()
7103 .chain(attached)
7104 .map(|p| p.name.name.as_str())
7105 .collect();
7106 let mut out = Vec::new();
7107 for p in &f.params {
7108 type_ref_names(&p.type_ref, &vars, &mut out);
7109 }
7110 type_ref_names(&f.return_type, &vars, &mut out);
7111 out
7112}
7113
7114pub(crate) fn type_ref_names(r: &TypeRef, vars: &HashSet<&str>, out: &mut Vec<String>) {
7118 match r {
7119 TypeRef::Named(id) => {
7120 if !vars.contains(id.name.as_str()) {
7121 out.push(id.name.clone());
7122 }
7123 }
7124 TypeRef::App { name, args, .. } => {
7125 if !vars.contains(name.name.as_str()) {
7126 out.push(name.name.clone());
7127 }
7128 for a in args {
7129 type_ref_names(a, vars, out);
7130 }
7131 }
7132 TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
7133 type_ref_names(a, vars, out);
7134 type_ref_names(b, vars, out);
7135 }
7136 TypeRef::Option(t, _)
7137 | TypeRef::Effect(t, _)
7138 | TypeRef::HttpResult(t, _)
7139 | TypeRef::List(t, _)
7140 | TypeRef::Set(t, _)
7141 | TypeRef::Query(t, _)
7142 | TypeRef::Stream(t, _)
7143 | TypeRef::Connection(t, _)
7144 | TypeRef::History(t, _) => type_ref_names(t, vars, out),
7145 TypeRef::Fn(params, ret, _) => {
7146 for p in params {
7147 type_ref_names(p, vars, out);
7148 }
7149 type_ref_names(ret, vars, out);
7150 }
7151 TypeRef::Base(..)
7152 | TypeRef::QueueResult(_)
7153 | TypeRef::Asset(_)
7154 | TypeRef::RequestHeaders(_)
7155 | TypeRef::RequestQuery(_)
7156 | TypeRef::RequestCookies(_)
7157 | TypeRef::TokenClaims(_)
7158 | TypeRef::BoundaryRejection(_)
7159 | TypeRef::ValidationError(_)
7160 | TypeRef::DecodeError(_)
7161 | TypeRef::Unit(_) => {}
7162 }
7163}
7164
7165#[allow(clippy::type_complexity)]
7170pub fn compose_unit_symbols(
7171 name: &str,
7172 local_table: &UnitTable,
7173 unit_info: &BTreeMap<String, UnitInfo>,
7174) -> (
7175 HashMap<String, Arc<TypeDecl>>,
7176 HashMap<String, Arc<FnDecl>>,
7177 HashMap<String, ResolverMethodTable>,
7178 HashMap<String, String>,
7179 HashMap<String, UnitKind>,
7180) {
7181 let mut combined_types = local_table.types.clone();
7186 let mut combined_fns = local_table.fns.clone();
7187 let mut combined_methods = local_table.methods.clone();
7188 let mut imported_from: HashMap<String, String> = HashMap::new();
7189 let mut imported_from_kind: HashMap<String, UnitKind> = HashMap::new();
7190
7191 for t in unit_info.get(name).into_iter().flat_map(|i| &i.uses) {
7192 let used = unit_info
7194 .get(t)
7195 .expect("used unit present")
7196 .table
7197 .importable();
7198 for (type_name, decl) in &used.types {
7199 if !combined_types.contains_key(type_name) {
7200 combined_types.insert(type_name.clone(), decl.clone());
7201 imported_from.insert(type_name.clone(), t.clone());
7202 imported_from_kind.insert(type_name.clone(), UnitKind::Commons);
7203 }
7204 }
7205 for (fn_name, decl) in &used.fns {
7206 if !combined_fns.contains_key(fn_name)
7209 && crate::symbols::local_value_kind(local_table, fn_name).is_none()
7210 {
7211 combined_fns.insert(fn_name.clone(), decl.clone());
7212 imported_from.insert(fn_name.clone(), t.clone());
7213 imported_from_kind.insert(fn_name.clone(), UnitKind::Commons);
7214 }
7215 }
7216 for asset_name in used.assets.keys() {
7221 if crate::symbols::local_value_kind(local_table, asset_name).is_none()
7222 && !combined_fns.contains_key(asset_name)
7223 && !imported_from.contains_key(asset_name)
7224 {
7225 imported_from.insert(asset_name.clone(), t.clone());
7226 imported_from_kind.insert(asset_name.clone(), UnitKind::Commons);
7227 }
7228 }
7229 for embed_name in used.embeds.keys() {
7231 if crate::symbols::local_value_kind(local_table, embed_name).is_none()
7232 && !combined_fns.contains_key(embed_name)
7233 && !imported_from.contains_key(embed_name)
7234 {
7235 imported_from.insert(embed_name.clone(), t.clone());
7236 imported_from_kind.insert(embed_name.clone(), UnitKind::Commons);
7237 }
7238 }
7239 for const_name in used.consts.keys() {
7241 if crate::symbols::local_value_kind(local_table, const_name).is_none()
7242 && !combined_fns.contains_key(const_name)
7243 && !imported_from.contains_key(const_name)
7244 {
7245 imported_from.insert(const_name.clone(), t.clone());
7246 imported_from_kind.insert(const_name.clone(), UnitKind::Commons);
7247 }
7248 }
7249 for (type_name, mt) in &used.methods {
7250 let entry = combined_methods.entry(type_name.clone()).or_default();
7251 for (m, decl) in &mt.instance {
7252 entry
7253 .instance
7254 .entry(m.clone())
7255 .or_insert_with(|| decl.clone());
7256 }
7257 for (m, decl) in &mt.statics {
7258 entry
7259 .statics
7260 .entry(m.clone())
7261 .or_insert_with(|| decl.clone());
7262 }
7263 }
7264 }
7265
7266 (
7267 combined_types,
7268 combined_fns,
7269 combined_methods,
7270 imported_from,
7271 imported_from_kind,
7272 )
7273}
7274
7275pub fn shadowed_imports(
7293 name: &str,
7294 unit_info: &BTreeMap<String, UnitInfo>,
7295) -> HashMap<String, crate::resolver::ShadowedImport> {
7296 let Some(info) = unit_info.get(name) else {
7297 return HashMap::new();
7298 };
7299 shadowed_imports_in(
7300 &info.table,
7301 info.uses
7302 .iter()
7303 .filter_map(|t| unit_info.get(t).map(|u| (t, &u.table))),
7304 )
7305}
7306
7307pub fn shadowed_imports_in<'a>(
7311 local: &UnitTable,
7312 uses: impl Iterator<Item = (&'a String, &'a UnitTable)>,
7313) -> HashMap<String, crate::resolver::ShadowedImport> {
7314 let mut out = HashMap::new();
7315 for (t, used) in uses {
7316 let used = used.importable();
7318 let imports = used
7321 .fns
7322 .keys()
7323 .map(|n| (n, "function"))
7324 .chain(used.assets.keys().map(|n| (n, "asset")))
7325 .chain(used.types.keys().map(|n| (n, "type")));
7326 for (n, imported) in imports {
7327 if let Some((kind, local_span)) = crate::symbols::local_value_kind(local, n)
7328 && kind != imported
7329 && !(imported == "type" && kind == "event")
7330 {
7331 let hidden = crate::resolver::ShadowedImport {
7332 unit: t.clone(),
7333 imported,
7334 local: kind,
7335 local_span,
7336 };
7337 match out.entry(n.clone()) {
7343 std::collections::hash_map::Entry::Vacant(e) => {
7344 e.insert(hidden);
7345 }
7346 std::collections::hash_map::Entry::Occupied(mut e) => {
7347 if imported == "type" && e.get().imported != "type" {
7348 e.insert(hidden);
7349 }
7350 }
7351 }
7352 }
7353 }
7354 }
7355 out
7356}
7357
7358pub fn phase_detect_consumes_cycles(
7364 groups: &BTreeMap<String, Vec<usize>>,
7365 parsed: &[ParsedFile],
7366 unit_consumes: &HashMap<String, Vec<String>>,
7367 errors: &mut ErrorSink,
7368) {
7369 let mut consumes_sites: HashMap<(String, String), (PathBuf, Span)> = HashMap::new();
7370 for (name, indices) in groups {
7371 for &i in indices {
7372 if parsed[i].is_synthetic() {
7373 continue;
7374 }
7375 for c in parsed[i].consumes() {
7376 consumes_sites
7377 .entry((name.clone(), c.target.joined()))
7378 .or_insert_with(|| (parsed[i].identity_path(), c.span));
7379 }
7380 }
7381 }
7382 let mut cycle_errors: Vec<(Option<PathBuf>, CompileError)> = Vec::new();
7383 detect_consumes_cycles(unit_consumes, &consumes_sites, &mut cycle_errors);
7384 for (path, err) in cycle_errors {
7385 errors.push_for(path.as_deref(), err);
7386 }
7387}
7388
7389#[cfg(test)]
7390mod platform_lock_tests {
7391 use super::{LockViolation, Platform, lock_violation};
7392 use std::collections::BTreeMap;
7393
7394 fn native(entries: &[(Platform, &str)]) -> BTreeMap<Platform, String> {
7395 entries
7396 .iter()
7397 .map(|(p, u)| (*p, (*u).to_string()))
7398 .collect()
7399 }
7400
7401 #[test]
7402 fn empty_closure_imposes_no_lock() {
7403 assert_eq!(lock_violation(&native(&[]), Platform::Node), None);
7404 }
7405
7406 #[test]
7407 fn matching_platform_is_fine() {
7408 let n = native(&[(Platform::Cloudflare, "bynk.cloudflare")]);
7409 assert_eq!(lock_violation(&n, Platform::Cloudflare), None);
7410 }
7411
7412 #[test]
7413 fn mismatched_platform_is_required() {
7414 let n = native(&[(Platform::Cloudflare, "bynk.cloudflare")]);
7415 assert_eq!(
7416 lock_violation(&n, Platform::Node),
7417 Some(LockViolation::Required {
7418 needed: Platform::Cloudflare,
7419 unit: "bynk.cloudflare".to_string(),
7420 })
7421 );
7422 }
7423
7424 #[test]
7429 fn two_platforms_conflict_regardless_of_selection() {
7430 let n = native(&[
7431 (Platform::Cloudflare, "bynk.cloudflare"),
7432 (Platform::Node, "bynk.synthetic"),
7433 ]);
7434 let v = lock_violation(&n, Platform::Cloudflare);
7435 assert_eq!(
7436 v,
7437 Some(LockViolation::Conflict {
7438 a: (Platform::Cloudflare, "bynk.cloudflare".to_string()),
7439 b: (Platform::Node, "bynk.synthetic".to_string()),
7440 })
7441 );
7442 }
7443}
7444
7445#[cfg(test)]
7446mod native_platform_closure_tests {
7447 use super::{HashMap, Platform, UnitTable, native_platforms_of_context};
7448 use bynk_syntax::ast::{CapRef, Ident, ProviderDecl, QualifiedName};
7449 use bynk_syntax::span::Span;
7450 use std::collections::HashMap as StdHashMap;
7451
7452 fn ident(name: &str) -> Ident {
7453 Ident {
7454 name: name.to_string(),
7455 span: Span::default(),
7456 }
7457 }
7458
7459 fn qualified(parts: &[&str]) -> QualifiedName {
7460 QualifiedName {
7461 parts: parts.iter().map(|p| ident(p)).collect(),
7462 span: Span::default(),
7463 }
7464 }
7465
7466 fn given_cap(prefix: Option<&[&str]>, name: &str) -> CapRef {
7467 CapRef {
7468 context: prefix.map(qualified),
7469 name: ident(name),
7470 span: Span::default(),
7471 }
7472 }
7473
7474 fn provider(capability: &str, given: Vec<CapRef>) -> ProviderDecl {
7475 ProviderDecl {
7476 capability: ident(capability),
7477 provider_name: ident(&format!("{capability}Impl")),
7478 given,
7479 ops: Vec::new(),
7480 external: false,
7481 documentation: None,
7482 span: Span::default(),
7483 trivia: Default::default(),
7484 }
7485 }
7486
7487 fn empty_table() -> UnitTable {
7488 UnitTable {
7489 exec_plan: Default::default(),
7490 kind: None,
7491 removed_agents: Vec::new(),
7492 types: StdHashMap::new(),
7493 fns: StdHashMap::new(),
7494 methods: StdHashMap::new(),
7495 capabilities: StdHashMap::new(),
7496 providers: StdHashMap::new(),
7497 services: StdHashMap::new(),
7498 agents: StdHashMap::new(),
7499 actors: StdHashMap::new(),
7500 exported_capabilities: Default::default(),
7501 events: StdHashMap::new(),
7502 flattened_caps: StdHashMap::new(),
7503 consumed_type_aliases: StdHashMap::new(),
7504 unselected_consumed_types: Default::default(),
7505 unlisted_consumed_types: Default::default(),
7506 assets: StdHashMap::new(),
7507 embeds: StdHashMap::new(),
7508 consts: StdHashMap::new(),
7509 derived: StdHashMap::new(),
7510 }
7511 }
7512
7513 #[test]
7526 fn a_providers_given_chain_into_a_platform_native_unit_is_recognised() {
7527 let mut table = empty_table();
7528 table.providers.insert(
7529 "Cache".to_string(),
7530 provider(
7531 "Cache",
7532 vec![given_cap(Some(&["bynk", "cloudflare"]), "Kv")],
7533 ),
7534 );
7535 let mut unit_tables = HashMap::new();
7536 unit_tables.insert("app.web".to_string(), table);
7537 let mut unit_consumes = HashMap::new();
7538 unit_consumes.insert("app.web".to_string(), vec!["bynk.cloudflare".to_string()]);
7539
7540 let native = native_platforms_of_context(
7541 "app.web",
7542 unit_tables.get("app.web").unwrap(),
7543 &unit_tables,
7544 &unit_consumes,
7545 &HashMap::new(),
7546 &HashMap::new(),
7547 );
7548 assert_eq!(
7549 native.get(&Platform::Cloudflare).map(String::as_str),
7550 Some("bynk.cloudflare"),
7551 "a provider's own `given` closure into a platform-native unit must be \
7552 walked recursively, not just a handler's direct `given` — got {native:?}"
7553 );
7554 }
7555
7556 #[test]
7560 fn a_providers_given_chain_into_an_ordinary_unit_is_not_native() {
7561 let mut table = empty_table();
7562 table.providers.insert(
7563 "Cache".to_string(),
7564 provider("Cache", vec![given_cap(None, "Clock")]),
7565 );
7566 let mut unit_tables = HashMap::new();
7567 unit_tables.insert("app.web".to_string(), table);
7568
7569 let native = native_platforms_of_context(
7570 "app.web",
7571 unit_tables.get("app.web").unwrap(),
7572 &unit_tables,
7573 &HashMap::new(),
7574 &HashMap::new(),
7575 &HashMap::new(),
7576 );
7577 assert!(
7578 native.is_empty(),
7579 "a `given` closure that never reaches a platform-native unit must not \
7580 report one — got {native:?}"
7581 );
7582 }
7583}
7584
7585#[cfg(test)]
7586mod view_closure_tests {
7587 use super::{HashMap, UnitTable, build_unit_table, close_view_types};
7588 use bynk_project::{ParsedFile, UnitKind};
7589 use bynk_syntax::{lexer, parser};
7590 use std::path::PathBuf;
7591
7592 fn table(name: &str, kind: UnitKind, src: &str) -> UnitTable {
7593 let tokens = lexer::tokenize(src).expect("lex");
7594 let unit = parser::parse_unit(&tokens, src).expect("parse");
7595 let path = PathBuf::from(format!("{}.bynk", name.replace('.', "/")));
7596 let pf = ParsedFile::new(path.clone(), path, None, src.to_string(), unit, kind, false);
7597 let mut errors = Vec::new();
7598 build_unit_table(name, kind, &[0], &[pf], &mut errors)
7599 }
7600
7601 #[test]
7607 fn a_kindless_table_is_still_searched_as_a_scope() {
7608 let core = table(
7609 "t.core",
7610 UnitKind::Commons,
7611 "commons t.core\n\ntype Repo = String where NonEmpty\n",
7612 );
7613 let mut model = table(
7614 "t.model",
7615 UnitKind::Commons,
7616 "commons t.model\n\nuses t.core\n\ntype Run = { repo: Repo }\n",
7617 );
7618 model.kind = None;
7619 let mut types = model.types.clone();
7620 let tables: HashMap<String, UnitTable> =
7621 [("t.core".to_string(), core), ("t.model".to_string(), model)].into();
7622 let uses: HashMap<String, Vec<String>> =
7623 [("t.model".to_string(), vec!["t.core".to_string()])].into();
7624 let reach = close_view_types(
7625 &["t.model".to_string()],
7626 &tables,
7627 &uses,
7628 &mut types,
7629 &HashMap::new(),
7630 &mut HashMap::new(),
7631 false,
7632 );
7633 assert_eq!(
7634 reach.hidden.get("Repo").map(String::as_str),
7635 Some("t.core"),
7636 "{:?}",
7637 reach.hidden
7638 );
7639 assert!(types.contains_key("Repo"));
7640 }
7641
7642 #[test]
7648 fn a_signature_reach_does_not_swallow_an_identity_conflict() {
7649 let lib = table(
7650 "t.lib",
7651 UnitKind::Commons,
7652 "commons t.lib\n\ntype X = String where NonEmpty\n\ntype Wrap = { x: X }\n\ntype Id = { x: X }\n",
7653 );
7654 let a = table(
7655 "t.a",
7656 UnitKind::Context,
7657 "context t.a\n\nuses t.lib\n\nservice s {\n on call() -> Effect[Wrap] by Caller { Effect.pure(Wrap { x: X.unsafe(\"x\") }) }\n}\n",
7658 );
7659 let b = table(
7660 "t.b",
7661 UnitKind::Context,
7662 "context t.b\n\nuses t.lib\n\nactor U { auth = Internal, identity = Id }\n",
7663 );
7664 let mine = table(
7666 "t.mine",
7667 UnitKind::Commons,
7668 "commons t.mine\n\ntype X = Int\n",
7669 );
7670 let mut types = mine.types.clone();
7671 let tables: HashMap<String, UnitTable> = [
7672 ("t.lib".to_string(), lib),
7673 ("t.a".to_string(), a),
7674 ("t.b".to_string(), b),
7675 ("t.mine".to_string(), mine),
7676 ]
7677 .into();
7678 let uses: HashMap<String, Vec<String>> = [
7679 ("t.a".to_string(), vec!["t.lib".to_string()]),
7680 ("t.b".to_string(), vec!["t.lib".to_string()]),
7681 ]
7682 .into();
7683 let reach = close_view_types(
7684 &["t.a".to_string(), "t.b".to_string()],
7685 &tables,
7686 &uses,
7687 &mut types,
7688 &HashMap::new(),
7689 &mut HashMap::new(),
7690 true,
7691 );
7692 assert!(
7693 reach
7694 .conflicts
7695 .iter()
7696 .any(|c| c.name == "X" && c.via == "t.b"),
7697 "{:?}",
7698 reach.conflicts
7699 );
7700 }
7701}
7702
7703#[cfg(test)]
7704mod label_attribution_tests {
7705 use super::*;
7706
7707 #[test]
7712 fn labels_are_attributed_to_the_file_their_span_is_in() {
7713 let (own, sibling, injected) = (FileId(10), FileId(11), FileId(12));
7714 let mut sink = ErrorSink::new();
7715 sink.register_file(own, PathBuf::from("src/app/z_more.bynk"));
7716 sink.register_file(sibling, PathBuf::from("src/app/a_web.bynk"));
7717 let error = CompileError::new(
7718 "bynk.resolve.duplicate_service",
7719 Span::new_in(own, 24, 27),
7720 "service `api` is already declared",
7721 )
7722 .with_label(Span::new_in(own, 0, 1), "same id")
7723 .with_label(Span::new(0, 1), "no id")
7724 .with_label(Span::new_in(sibling, 21, 24), "sibling")
7725 .with_label(Span::new_in(injected, 0, 1), "unregistered");
7726 sink.push_for(Some(Path::new("src/app/z_more.bynk")), error);
7727 let all = sink.into_all();
7728 assert_eq!(
7729 all[0].label_files,
7730 vec![
7731 LabelFile::Primary,
7732 LabelFile::Primary,
7733 LabelFile::Other(PathBuf::from("src/app/a_web.bynk")),
7734 LabelFile::Unavailable,
7735 ]
7736 );
7737 }
7738
7739 #[test]
7743 fn extend_attributed_uses_the_files_registered_up_front() {
7744 let known = FileId(40);
7745 let mut sink = ErrorSink::new();
7746 sink.register_file(known, PathBuf::from("src/a.bynk"));
7747 sink.extend_attributed([CompileError::new(
7748 "bynk.resolve.duplicate_service",
7749 Span::new_in(known, 0, 1),
7750 "in a registered file",
7751 )]);
7752 sink.extend_attributed([CompileError::new(
7753 "bynk.resolve.duplicate_service",
7754 Span::new_in(FileId(41), 0, 1),
7755 "in no registered file",
7756 )]);
7757 let all = sink.into_all();
7758 assert_eq!(all[0].source_path.as_deref(), Some(Path::new("src/a.bynk")));
7759 assert_eq!(all[1].source_path, None);
7760 }
7761
7762 #[test]
7766 fn a_label_in_a_firstparty_unit_is_attributed_to_that_unit() {
7767 let unit = firstparty::unit("bynk").expect("the `bynk` unit is registered");
7768 let own = FileId(30);
7769 let mut sink = ErrorSink::new();
7770 sink.register_file(own, PathBuf::from("src/app/web.bynk"));
7771 let error = CompileError::new(
7772 "bynk.resolve.missing_field",
7773 Span::new_in(own, 0, 7),
7774 "missing required field `headers` for record `Request`",
7775 )
7776 .with_label(
7777 Span::new_in(firstparty_file_id(unit), 0, 7),
7778 "field declared here",
7779 );
7780 sink.push_for(Some(Path::new("src/app/web.bynk")), error);
7781 assert_eq!(
7782 sink.into_all()[0].label_files,
7783 vec![LabelFile::FirstParty {
7784 identity_path: unit.identity_path,
7785 source: unit.source,
7786 }]
7787 );
7788 }
7789
7790 #[test]
7793 fn a_label_naming_the_errors_own_path_is_primary() {
7794 let own = FileId(20);
7795 let mut sink = ErrorSink::new();
7796 sink.register_file(own, PathBuf::from("src/a.bynk"));
7797 let error = CompileError::new("bynk.test", Span::default(), "msg")
7798 .with_label(Span::new_in(own, 0, 1), "here");
7799 sink.push_for(Some(Path::new("src/a.bynk")), error);
7800 assert_eq!(sink.into_all()[0].label_files, vec![LabelFile::Primary]);
7801 }
7802}
7803
7804#[cfg(test)]
7811mod shadowed_import_tests {
7812 use crate::testkit::analyse;
7813
7814 const IMPORTED: [(&str, &str, &str, &str); 3] = [
7817 (
7818 "function",
7819 "fn thing() -> Int {\n 1\n}\n",
7820 "thing()",
7821 "Int",
7822 ),
7823 (
7824 "asset",
7825 "asset thing = \"assets/x.json\"\n",
7826 "thing.url",
7827 "String",
7828 ),
7829 (
7831 "type",
7832 "type thing = { n: Int }\n",
7833 "thing { n: 1 }.n",
7834 "Int",
7835 ),
7836 ];
7837
7838 const LOCAL: [(&str, &str); 7] = [
7839 ("function", "fn thing() -> Int {\n 2\n}\n"),
7840 ("asset", "asset thing = \"assets/x.json\"\n"),
7841 ("type", "type thing = { n: Int }\n"),
7842 ("event", "event thing = { n: Int }\n"),
7843 (
7844 "service",
7845 "service thing {\n on call() -> Effect[Int] by Caller {\n Effect.pure(1)\n }\n}\n",
7846 ),
7847 (
7848 "agent",
7849 "agent thing {\n key id: String\n\n store hits: Cell[Int]\n\n on call ping() -> Effect[Int] {\n 1\n }\n}\n",
7850 ),
7851 (
7852 "provider",
7853 "capability ProbeCap {\n fn go() -> Effect[Int]\n}\n\nprovides ProbeCap = thing {\n fn go() -> Effect[Int] {\n Effect.pure(1)\n }\n}\n",
7854 ),
7855 ];
7856
7857 #[derive(Clone, Copy, Debug)]
7858 enum Use {
7859 None,
7860 FnBody,
7861 HandlerBody,
7862 }
7863
7864 #[test]
7865 fn every_local_kind_against_every_import_and_use_site() {
7866 for (imported, idecl, expr, ty) in IMPORTED {
7867 for (local, ldecl) in LOCAL {
7868 for at in [Use::None, Use::FnBody, Use::HandlerBody] {
7869 let using = match at {
7870 Use::None => String::new(),
7871 Use::FnBody => format!("fn useIt() -> {ty} {{\n {expr}\n}}\n"),
7872 Use::HandlerBody => format!(
7873 "service user {{\n on call() -> Effect[{ty}] by Caller {{\n Effect.pure({expr})\n }}\n}}\n"
7874 ),
7875 };
7876 let lib = format!("commons lib.util\n\n{idecl}");
7877 let app = format!("context app\n\nuses lib.util\n\n{ldecl}\n{using}");
7878 let r = analyse(&[
7879 ("lib/util.bynk", &lib),
7880 ("app/main.bynk", &app),
7881 ("assets/x.json", "{}"),
7882 ]);
7883 let cats = r.error_categories();
7884 let case = format!("local {local} over imported {imported}, used {at:?}");
7885 let want: Vec<&str> = match at {
7886 Use::None => vec![],
7888 _ if local == imported => vec![],
7889 _ if imported == "type" && local == "event" => vec![],
7892 Use::FnBody if imported == "asset" && matches!(local, "type" | "event") => {
7896 vec!["bynk.resolve.unknown_static_member"]
7897 }
7898 Use::HandlerBody if imported == "function" && local == "agent" => {
7902 vec!["bynk.agent.construction_arity"]
7903 }
7904 _ => vec!["bynk.uses.name_conflict"],
7905 };
7906 assert_eq!(cats, want, "{case}");
7907 }
7908 }
7909 }
7910 }
7911
7912 #[test]
7916 fn a_local_agent_answers_its_own_call() {
7917 let r = analyse(&[
7918 (
7919 "lib/util.bynk",
7920 "commons lib.util\n\nfn thing() -> Int {\n 1\n}\n",
7921 ),
7922 (
7923 "app/main.bynk",
7924 "context app\n\nuses lib.util\n\nagent thing {\n key id: String\n\n store hits: Cell[Int]\n\n on call ping() -> Effect[Int] {\n 1\n }\n}\n\nservice web {\n on call() -> Effect[Int] by Caller {\n let n <- thing(\"k\").ping()\n Effect.pure(n)\n }\n}\n",
7925 ),
7926 ]);
7927 r.assert_clean();
7928 }
7929
7930 #[test]
7934 fn a_local_service_hiding_two_used_imports_is_no_ambiguity() {
7935 let r = analyse(&[
7936 (
7937 "lib/a.bynk",
7938 "commons lib.a\n\nfn thing() -> Int {\n 1\n}\n",
7939 ),
7940 (
7941 "lib/b.bynk",
7942 "commons lib.b\n\nfn thing() -> Int {\n 2\n}\n",
7943 ),
7944 (
7945 "app/main.bynk",
7946 "context app\n\nuses lib.a\nuses lib.b\n\nservice thing {\n on call() -> Effect[Int] by Caller {\n Effect.pure(1)\n }\n}\n",
7947 ),
7948 ]);
7949 r.assert_clean();
7950 }
7951
7952 #[test]
7956 fn a_bare_local_function_keeps_its_own_advice() {
7957 let lib = (
7958 "lib/util.bynk",
7959 "commons lib.util\n\nasset thing = \"assets/x.json\"\n",
7960 );
7961 let file = |body: &str| {
7962 format!(
7963 "context app\n\nuses lib.util\n\nfn thing() -> Int {{\n 1\n}}\n\nfn useIt() -> Int {{\n {body}\n}}\n"
7964 )
7965 };
7966 let bare = file("thing + 1");
7967 let r = analyse(&[lib, ("app/main.bynk", &bare), ("assets/x.json", "{}")]);
7968 assert_eq!(r.error_categories(), vec!["bynk.resolve.fn_without_call"]);
7969 let read = file("let u = thing.url\n 1");
7970 let r = analyse(&[lib, ("app/main.bynk", &read), ("assets/x.json", "{}")]);
7971 assert_eq!(r.error_categories(), vec!["bynk.uses.name_conflict"]);
7972 }
7973
7974 const STATUS_LIB: (&str, &str) = (
7977 "lib/st.bynk",
7978 "commons lib.st\n\ntype Status =\n | Done\n | Pending\n | Failed(reason: String)\n\nfn mk() -> Status {\n Done\n}\n\nfn isDone(s: Status) -> Bool {\n match s {\n Done => true\n _ => false\n }\n}\n",
7979 );
7980
7981 #[test]
7985 fn a_hidden_sums_bare_variant_constructs_only_by_conflict() {
7986 let unit = |body: &str| {
7987 format!("commons app\n\nuses lib.st\n\nfn Status() -> Int {{\n 1\n}}\n\n{body}")
7988 };
7989 let construct = unit("fn f() -> Bool {\n isDone(Done)\n}\n");
7990 let r = analyse(&[STATUS_LIB, ("app/main.bynk", &construct)]);
7991 assert_eq!(r.error_categories(), vec!["bynk.uses.name_conflict"]);
7992 let construct = unit("fn f() -> Bool {\n isDone(Failed(\"x\"))\n}\n");
7994 let r = analyse(&[STATUS_LIB, ("app/main.bynk", &construct)]);
7995 assert_eq!(r.error_categories(), vec!["bynk.uses.name_conflict"]);
7996 let matched = unit(
7997 "fn f() -> Bool {\n match mk() {\n Done => true\n Failed(r) => false\n _ => false\n }\n}\n",
7998 );
7999 let r = analyse(&[STATUS_LIB, ("app/main.bynk", &matched)]);
8000 r.assert_clean();
8001 }
8002
8003 #[test]
8007 fn a_hidden_types_values_still_flow() {
8008 let r = analyse(&[
8009 STATUS_LIB,
8010 (
8011 "app/main.bynk",
8012 "context app\n\nuses lib.st\n\nagent Status {\n key id: String\n\n store hits: Cell[Int]\n\n on call ping() -> Effect[Int] {\n 1\n }\n}\n\nfn f() -> Bool {\n let s = mk()\n isDone(s)\n}\n",
8013 ),
8014 ]);
8015 r.assert_clean();
8016 }
8017
8018 #[test]
8021 fn a_local_asset_answers_its_own_url_beside_a_hidden_type() {
8022 let r = analyse(&[
8023 STATUS_LIB,
8024 (
8025 "app/main.bynk",
8026 "commons app\n\nuses lib.st\n\nasset Status = \"assets/x.json\"\n\nfn f() -> String {\n Status.url\n}\n",
8027 ),
8028 ("assets/x.json", "{}"),
8029 ]);
8030 r.assert_clean();
8031 }
8032
8033 #[test]
8037 fn a_hidden_type_gates_whatever_the_uses_order() {
8038 let a = ("lib/a.bynk", "commons lib.a\n\ntype Status = { n: Int }\n");
8039 let b = (
8040 "lib/b.bynk",
8041 "commons lib.b\n\nfn Status() -> Int {\n 1\n}\n",
8042 );
8043 for (first, second) in [("lib.a", "lib.b"), ("lib.b", "lib.a")] {
8044 let app = format!(
8045 "context app\n\nuses {first}\nuses {second}\n\nservice Status {{\n on call() -> Effect[Int] by Caller {{\n Effect.pure(1)\n }}\n}}\n\nfn f(s: Status) -> Int {{\n s.n\n}}\n"
8046 );
8047 let r = analyse(&[a, b, ("app/main.bynk", &app)]);
8048 assert_eq!(
8049 r.error_categories(),
8050 vec!["bynk.uses.name_conflict"],
8051 "uses {first} then {second}"
8052 );
8053 }
8054 }
8055
8056 #[test]
8059 fn a_local_function_hiding_a_type_is_a_function_value() {
8060 let r = analyse(&[
8061 (
8062 "lib/util.bynk",
8063 "commons lib.util\n\ntype thing = { n: Int }\n",
8064 ),
8065 (
8066 "app/main.bynk",
8067 "commons app\n\nuses lib.util\n\nfn thing(x: Int) -> Int {\n x + 1\n}\n\nfn f() -> List[Int] {\n [1, 2].map(thing)\n}\n",
8068 ),
8069 ]);
8070 r.assert_clean();
8071 }
8072
8073 #[test]
8076 fn a_local_value_named_like_a_consumed_export_conflicts() {
8077 let r = analyse(&[
8078 (
8079 "shop.bynk",
8080 "context shop\n\nexports transparent { Order }\n\ntype Order = { id: String }\n",
8081 ),
8082 (
8083 "app.bynk",
8084 "context app\n\nconsumes shop\n\nservice Order {\n on call() -> Effect[Int] by Caller {\n Effect.pure(1)\n }\n}\n",
8085 ),
8086 ]);
8087 assert_eq!(r.error_categories(), vec!["bynk.consumes.name_conflict"]);
8088 }
8089
8090 #[test]
8092 fn the_conflict_names_both_declarations() {
8093 let r = analyse(&[
8094 (
8095 "lib/util.bynk",
8096 "commons lib.util\n\nfn thing() -> Int {\n 1\n}\n",
8097 ),
8098 (
8099 "app/main.bynk",
8100 "context app\n\nuses lib.util\n\ntype thing = { n: Int }\n\nfn useIt() -> Int {\n thing()\n}\n",
8101 ),
8102 ]);
8103 let e = r
8104 .analysis
8105 .errors
8106 .iter()
8107 .find(|e| e.error.category == "bynk.uses.name_conflict")
8108 .expect("a conflict");
8109 assert_eq!(
8110 e.error.message,
8111 "`thing` names this unit's type, which hides the function `thing` from `lib.util`"
8112 );
8113 }
8114
8115 const WITHIN_SVC: &str = "\nservice s {\n on call() -> Effect[String] by Caller {\n let r <- Effect.pure(1).within(2.seconds)\n Effect.pure(\"x\")\n }\n}\n";
8116
8117 #[test]
8120 fn consumes_bynk_may_select_an_exported_type() {
8121 for consumes in [
8122 "consumes bynk { TimedOut }",
8123 "consumes bynk { Clock, TimedOut }",
8124 ] {
8125 let src = format!("context app\n\n{consumes}\n{WITHIN_SVC}");
8126 let r = analyse(&[("app.bynk", &src)]);
8127 assert!(
8128 r.error_categories().is_empty(),
8129 "{consumes}: {:?}",
8130 r.error_categories()
8131 );
8132 }
8133 }
8134
8135 #[test]
8137 fn a_repeated_type_selection_is_refused() {
8138 let src = format!("context app\n\nconsumes bynk {{ TimedOut, TimedOut }}\n{WITHIN_SVC}");
8139 let r = analyse(&[("app.bynk", &src)]);
8140 assert_eq!(
8141 r.error_categories(),
8142 vec!["bynk.consumes.capability_name_clash"]
8143 );
8144 }
8145
8146 #[test]
8149 fn consumes_bynk_still_refuses_an_unknown_name() {
8150 let r = analyse(&[("app.bynk", "context app\n\nconsumes bynk { NoSuchThing }\n")]);
8151 assert_eq!(
8152 r.error_categories(),
8153 vec!["bynk.given.cross_context_unknown_capability"]
8154 );
8155 }
8156
8157 #[test]
8159 fn timed_out_not_in_scope_note_names_the_accepted_form() {
8160 let src = format!("context app\n{WITHIN_SVC}");
8161 let r = analyse(&[("app.bynk", &src)]);
8162 let e = r
8163 .analysis
8164 .errors
8165 .iter()
8166 .find(|e| e.error.category == "bynk.within.timed_out_not_in_scope")
8167 .expect("TimedOut is not in scope without `consumes bynk`");
8168 assert!(
8169 e.error
8170 .notes
8171 .iter()
8172 .any(|n| n.contains("consumes bynk { TimedOut }")),
8173 "{:?}",
8174 e.error.notes
8175 );
8176 }
8177}
8178
8179#[cfg(test)]
8182mod consumes_alias_tests {
8183 use crate::stability::StabilityPolicy;
8184 use crate::testkit::{Analysed, analyse_with};
8185
8186 const REPORT: (&str, &str) = (
8187 "report.bynk",
8188 "commons report\n\ntype Digest = { total: Int }\n",
8189 );
8190
8191 fn run(files: &[(&str, &str)]) -> Analysed {
8192 analyse_with(files, Some(StabilityPolicy::permissive()))
8193 }
8194
8195 fn app(consumes: &str, body: &str) -> String {
8196 format!("context app\n\nuses report\n{consumes}\n\n{body}\n")
8197 }
8198
8199 const USES_BOTH: &str = "fn empty() -> Digest { Digest { total: 0 } }\n\
8200 fn name(d: CryptoDigest) -> String {\n match d {\n Sha256 => \"a\"\n Sha384 => \"b\"\n Sha512 => \"c\"\n }\n}\n\
8201 service hashing {\n on call() -> Effect[Bytes] by Caller given Crypto {\n Crypto.digest(CryptoDigest.Sha256, Bytes.fromUtf8(\"x\"))\n }\n}";
8202
8203 #[test]
8204 fn an_aliased_export_clears_the_clash_and_works_everywhere() {
8205 let src = app(
8206 "consumes bynk.crypto { Crypto, Digest as CryptoDigest }",
8207 USES_BOTH,
8208 );
8209 let a = run(&[REPORT, ("app.bynk", &src)]);
8210 a.assert_clean();
8211 assert_eq!(a.resolves_to("app.bynk", "Digest {").unit, "report");
8213 }
8214
8215 #[test]
8216 fn an_alias_names_the_real_declaration_for_the_ide() {
8217 let lib = (
8220 "lib.bynk",
8221 "adapter lib\n\nbinding \"./lib.binding.ts\"\n\nexports transparent { Digest }\n\ntype Digest = enum { Fast, Slow }\n",
8222 );
8223 let src = app(
8224 "consumes lib { Digest as LibDigest }",
8225 "fn pick() -> LibDigest { LibDigest.Fast }\nfn empty() -> Digest { Digest { total: 0 } }",
8226 );
8227 let a = run(&[
8228 REPORT,
8229 lib,
8230 ("lib.binding.ts", "export {};\n"),
8231 ("app.bynk", &src),
8232 ]);
8233 a.assert_clean();
8234 for needle in ["Digest as", "LibDigest {", "LibDigest.Fast"] {
8235 let key = a.resolves_to("app.bynk", needle);
8236 assert_eq!(
8237 (key.unit.as_str(), key.name.as_str()),
8238 ("lib", "Digest"),
8239 "{needle}"
8240 );
8241 }
8242 assert_eq!(a.resolves_to("app.bynk", "Digest { total").unit, "report");
8243 }
8244
8245 #[test]
8249 fn an_unlisted_export_yields_to_the_units_own_type() {
8250 let src = app(
8251 "consumes bynk { Clock }",
8252 "type Method = | Fetch | Skip\n\nfn pick() -> Method { Fetch }",
8253 );
8254 run(&[REPORT, ("app.bynk", &src)]).assert_clean();
8255 }
8256
8257 #[test]
8261 fn the_unaliased_form_still_clashes_with_a_note_that_names_the_way_out() {
8262 let src = app(
8263 "consumes bynk.crypto { Crypto }",
8264 "fn empty() -> Digest { Digest { total: 0 } }",
8265 );
8266 let a = run(&[REPORT, ("app.bynk", &src)]);
8267 assert_eq!(a.error_categories(), vec!["bynk.consumes.name_conflict"]);
8268 let e = &a.analysis.errors[0].error;
8269 assert!(
8270 e.notes.iter().any(|n| n.contains("Digest as CryptoDigest")),
8271 "{:?}",
8272 e.notes
8273 );
8274 }
8275
8276 #[test]
8277 fn a_refused_alias_does_not_take_over_the_name_it_clashed_with() {
8278 let src = "context app\n\nconsumes bynk.crypto { Crypto, Digest as Report }\n\ntype Report = { total: Int }\n\nfn f(r: Report) -> Int { r.total }\n";
8281 let a = run(&[("app.bynk", src)]);
8282 assert_eq!(
8283 a.error_categories(),
8284 vec!["bynk.consumes.type_alias_conflict"]
8285 );
8286 let reports: Vec<_> = a
8290 .analysis
8291 .index
8292 .symbols
8293 .keys()
8294 .filter(|k| k.name == "Report" || k.name == "Digest")
8295 .collect();
8296 assert!(
8297 reports
8298 .iter()
8299 .all(|k| k.unit == "app" && k.name == "Report"),
8300 "{reports:?}"
8301 );
8302 }
8303
8304 #[test]
8305 fn the_conflict_note_for_a_context_also_names_the_alias_form() {
8306 let lib = (
8309 "lib.bynk",
8310 "context lib\n\nexports transparent { Code }\n\ntype Code = enum { A, B }\n",
8311 );
8312 let codes = ("codes.bynk", "commons codes\n\ntype Code = { n: Int }\n");
8313 let app = "context app\n\nuses codes\nconsumes lib\n\nfn one() -> Int { 1 }\n";
8314 let a = run(&[lib, codes, ("app.bynk", app)]);
8315 assert_eq!(a.error_categories(), vec!["bynk.consumes.name_conflict"]);
8316 assert!(
8317 a.analysis.errors[0]
8318 .error
8319 .notes
8320 .iter()
8321 .any(|n| n.contains("Code as LibCode")),
8322 "{:?}",
8323 a.analysis.errors[0].error.notes
8324 );
8325 }
8326
8327 #[test]
8328 fn the_original_name_is_not_in_scope_once_aliased() {
8329 let src = app(
8330 "consumes bynk.crypto { Crypto, Digest as CryptoDigest }",
8331 "fn f(d: Digest) -> Int { 1 }",
8332 );
8333 let a = run(&[REPORT, ("app.bynk", &src)]);
8336 a.assert_clean();
8337 let bad = app(
8338 "consumes bynk.crypto { Crypto, Digest as CryptoDigest }",
8339 "service s {\n on call() -> Effect[Bytes] by Caller given Crypto {\n Crypto.digest(Digest { total: 1 }, Bytes.fromUtf8(\"x\"))\n }\n}",
8340 );
8341 let a = run(&[REPORT, ("app.bynk", &bad)]);
8342 assert!(
8343 !a.error_categories().is_empty(),
8344 "the local Digest is not the crypto Digest"
8345 );
8346 }
8347
8348 #[test]
8349 fn an_alias_in_one_file_of_a_split_context_applies_to_the_unit() {
8350 let one = "context app\n\nuses report\nconsumes bynk.crypto { Crypto, Digest as CryptoDigest }\n\nfn empty() -> Digest { Digest { total: 0 } }\n";
8351 let two = "context app\n\nuses report\nconsumes bynk.crypto { Crypto, Digest as CryptoDigest }\n\nfn first() -> CryptoDigest { CryptoDigest.Sha256 }\n";
8352 run(&[REPORT, ("app/one.bynk", one), ("app/two.bynk", two)]).assert_clean();
8353 let disagree =
8354 "context app\n\nuses report\nconsumes bynk.crypto { Crypto, Digest as Other }\n";
8355 let a = run(&[REPORT, ("app/one.bynk", one), ("app/two.bynk", disagree)]);
8356 assert!(
8357 a.error_categories()
8358 .contains(&"bynk.consumes.type_alias_repeated"),
8359 "{:?}",
8360 a.error_categories()
8361 );
8362 }
8363}
8364
8365#[cfg(test)]
8366mod firstparty_injection_tests {
8367 use super::{
8368 ErrorSink, ParsedFile, UnitKind, firstparty, firstparty_file_id, inject_firstparty, lexer,
8369 parser,
8370 };
8371 use bynk_syntax::span::FileId;
8372 use std::collections::BTreeSet;
8373 use std::path::PathBuf;
8374
8375 const REFS: [&str; 7] = [
8378 "consumes bynk { Clock }",
8379 "consumes bynk.cloudflare { Kv }",
8380 "uses bynk.map",
8381 "uses bynk.list",
8382 "uses bynk.string",
8383 "uses bynk.locale",
8384 "uses bynk.locale.types",
8385 ];
8386
8387 #[test]
8391 fn injected_units_carry_their_reserved_file_id() {
8392 let ids: BTreeSet<FileId> = firstparty::UNITS.iter().map(firstparty_file_id).collect();
8393 assert_eq!(ids.len(), firstparty::UNITS.len());
8394 assert!(!ids.contains(&FileId::UNKNOWN));
8395 let mut parsed = project((1 << REFS.len()) - 1);
8396 let injected = inject_firstparty(&mut parsed, &mut ErrorSink::new());
8397 assert!(!injected.is_empty());
8398 for unit in injected {
8399 let pf = parsed
8400 .iter()
8401 .find(|pf| pf.identity_path() == std::path::Path::new(unit.identity_path))
8402 .expect("an injected unit is in `parsed`");
8403 assert_eq!(
8404 pf.unit().span().file,
8405 firstparty_file_id(unit),
8406 "{}",
8407 unit.name
8408 );
8409 }
8410 }
8411
8412 fn project(mask: u32) -> Vec<ParsedFile> {
8414 let mut uses = String::new();
8415 let mut consumes = String::new();
8416 for (bit, line) in REFS.iter().enumerate() {
8417 if mask & (1 << bit) != 0 {
8418 let into = if line.starts_with("uses") {
8419 &mut uses
8420 } else {
8421 &mut consumes
8422 };
8423 into.push_str(line);
8424 into.push('\n');
8425 }
8426 }
8427 let src = format!("context t\n\n{uses}{consumes}\nfn f() -> Int {{ 1 }}\n");
8428 let toks = lexer::tokenize(&src).expect("lexes");
8429 let (unit, _) =
8430 parser::parse_unit_with_warnings_from(&toks, &src, &mut { 0 }).expect("parses");
8431 vec![ParsedFile::synthetic(
8432 PathBuf::from("t.bynk"),
8433 PathBuf::from("t.bynk"),
8434 src,
8435 unit,
8436 UnitKind::Context,
8437 )]
8438 }
8439
8440 fn previous_injection(mask: u32) -> BTreeSet<&'static str> {
8443 let has = |bit: u32| mask & (1 << bit) != 0;
8444 let (bynk, cloudflare) = (has(0), has(1));
8445 let (map, list, string, locale, locale_types) = (has(2), has(3), has(4), has(5), has(6));
8446 let mut out = BTreeSet::new();
8447 let mut add = |cond: bool, name: &'static str| {
8448 if cond {
8449 out.insert(name);
8450 }
8451 };
8452 let bynk = bynk || cloudflare;
8456 add(bynk, "bynk");
8457 add(cloudflare, "bynk.cloudflare");
8458 add(map, "bynk.map");
8459 add(list, "bynk.list");
8460 add(locale || string, "bynk.string");
8461 add(locale || locale_types || bynk, "bynk.locale.types");
8464 add(locale, "bynk.locale");
8465 out
8466 }
8467
8468 #[test]
8471 fn the_closure_matches_the_previous_gates_for_every_combination() {
8472 for mask in 0..(1u32 << REFS.len()) {
8473 let mut parsed = project(mask);
8474 let mut errors = ErrorSink::new();
8475 let injected = inject_firstparty(&mut parsed, &mut errors);
8476 assert!(
8477 errors.is_empty(),
8478 "mask {mask:#09b}: a first-party source failed to parse"
8479 );
8480 let names: BTreeSet<&str> = injected.iter().map(|u| u.name).collect();
8481 assert_eq!(names, previous_injection(mask), "mask {mask:#09b}");
8482 }
8483 }
8484
8485 #[test]
8489 fn injected_units_are_pushed_in_id_block_order() {
8490 let mut parsed = project((1 << REFS.len()) - 1);
8491 let mut errors = ErrorSink::new();
8492 let injected = inject_firstparty(&mut parsed, &mut errors);
8493 let pushed: Vec<String> = parsed[1..]
8494 .iter()
8495 .map(|pf| pf.unit().name().joined())
8496 .collect();
8497 assert_eq!(
8498 pushed,
8499 [
8500 "bynk",
8501 "bynk.cloudflare",
8502 "bynk.map",
8503 "bynk.list",
8504 "bynk.string",
8505 "bynk.locale.types",
8506 "bynk.locale",
8507 ]
8508 );
8509 let returned: Vec<&str> = injected.iter().map(|u| u.name).collect();
8510 assert_eq!(returned, pushed);
8511 assert!(injected.windows(2).all(|w| w[0].id_block < w[1].id_block));
8512 }
8513
8514 #[test]
8516 fn nothing_is_injected_unreferenced() {
8517 let mut parsed = project(0);
8518 let injected = inject_firstparty(&mut parsed, &mut ErrorSink::new());
8519 assert!(injected.is_empty());
8520 assert_eq!(parsed.len(), 1);
8521 }
8522
8523 #[test]
8527 fn injection_is_registry_driven() {
8528 let src = include_str!("project_model.rs");
8529 let start = src.find("pub fn phase_parse(").expect("phase_parse");
8530 let end = src[start..]
8531 .find("\n/// #1710: for each unit with a file the strict parse rejected")
8532 .map(|rel| start + rel)
8533 .expect("the item after inject_firstparty");
8534 let body = &src[start..end];
8535 for name in firstparty::UNITS.iter().map(|u| u.name) {
8536 assert!(!body.contains(&format!("\"{name}\"")), "names {name}");
8537 }
8538 let per_unit_constant = body
8539 .lines()
8540 .find(|l| l.contains("firstparty::") && (l.contains("_UNIT") || l.contains("_SRC")));
8541 assert_eq!(per_unit_constant, None, "references a per-unit constant");
8542 }
8543
8544 #[test]
8551 fn exported_capability_signatures_name_only_exported_types() {
8552 use bynk_syntax::ast::{
8553 CommonsItem, ExportKind, RecordField, SourceUnit, TypeBody, Visibility,
8554 };
8555 use std::collections::{HashMap, HashSet};
8556 let mut missing = Vec::new();
8557 for unit in firstparty::UNITS
8558 .iter()
8559 .filter(|u| u.kind == firstparty::UnitKind::Adapter)
8560 {
8561 let toks = lexer::tokenize(unit.source).expect("lexes");
8562 let (parsed, _) = parser::parse_unit_with_warnings_from(&toks, unit.source, &mut { 0 })
8563 .expect("parses");
8564 let SourceUnit::Adapter(adapter) = parsed else {
8565 panic!("{} is registered as an adapter", unit.name);
8566 };
8567 let exported = |kind: fn(&ExportKind) -> bool| -> HashSet<&str> {
8568 adapter
8569 .exports
8570 .iter()
8571 .filter(|c| kind(&c.kind))
8572 .flat_map(|c| c.names.iter().map(|e| e.name.name.as_str()))
8573 .collect()
8574 };
8575 let types = exported(|k| matches!(k, ExportKind::Type(_)));
8576 let transparent = exported(|k| matches!(k, ExportKind::Type(Visibility::Transparent)));
8577 let capabilities = exported(|k| matches!(k, ExportKind::Capability));
8578 let fields = |fs: &[RecordField], vars: &HashSet<&str>| {
8582 let mut out = Vec::new();
8583 for f in fs {
8584 super::type_ref_names(&f.type_ref, vars, &mut out);
8585 }
8586 out
8587 };
8588 let local: HashMap<&str, Vec<String>> = adapter
8589 .items
8590 .iter()
8591 .filter_map(|item| match item {
8592 CommonsItem::Type(t) => {
8593 let vars = t.type_params.iter().map(|p| p.name.name.as_str()).collect();
8594 let inner = match &t.body {
8595 TypeBody::Record(r) => fields(&r.fields, &vars),
8596 TypeBody::Sum(s) => {
8597 let mut out = Vec::new();
8598 for f in s.variants.iter().flat_map(|v| &v.payload) {
8599 super::type_ref_names(&f.type_ref, &vars, &mut out);
8600 }
8601 for e in &s.embeds {
8602 super::type_ref_names(&e.source_type, &vars, &mut out);
8603 }
8604 out
8605 }
8606 TypeBody::Refined { .. } | TypeBody::Opaque { .. } => Vec::new(),
8607 };
8608 Some((t.name.name.as_str(), inner))
8609 }
8610 CommonsItem::Event(e) => Some((
8611 e.name.name.as_str(),
8612 fields(&e.body.fields, &HashSet::new()),
8613 )),
8614 _ => None,
8615 })
8616 .collect();
8617 for item in &adapter.items {
8618 let CommonsItem::Capability(cap) = item else {
8619 continue;
8620 };
8621 if !capabilities.contains(cap.name.name.as_str()) {
8622 continue;
8623 }
8624 for op in &cap.ops {
8625 let vars = op
8626 .type_params
8627 .iter()
8628 .map(|p| p.name.name.as_str())
8629 .collect();
8630 let mut names = Vec::new();
8631 for p in &op.params {
8632 super::type_ref_names(&p.type_ref, &vars, &mut names);
8633 }
8634 super::type_ref_names(&op.return_type, &vars, &mut names);
8635 let mut work: Vec<(String, String)> = names
8638 .into_iter()
8639 .map(|n| {
8640 (
8641 n.clone(),
8642 format!("`{}.{}` → `{n}`", cap.name.name, op.name.name),
8643 )
8644 })
8645 .collect();
8646 let mut seen = HashSet::new();
8647 while let Some((name, path)) = work.pop() {
8648 let Some(inner) = local.get(name.as_str()) else {
8649 continue;
8650 };
8651 if !seen.insert(name.clone()) {
8652 continue;
8653 }
8654 if !types.contains(name.as_str()) {
8655 missing.push(format!(
8656 "{}: {path}, which is not in an `exports` clause",
8657 unit.name
8658 ));
8659 } else if transparent.contains(name.as_str()) {
8660 work.extend(
8661 inner.iter().map(|n| (n.clone(), format!("{path} → `{n}`"))),
8662 );
8663 }
8664 }
8665 }
8666 }
8667 }
8668 missing.sort();
8669 missing.dedup();
8670 assert!(missing.is_empty(), "{}", missing.join("\n"));
8671 }
8672}
8673
8674fn display_canonical_names(error: &mut CompileError) {
8677 if error.message.contains('$') {
8678 error.message = bynk_project::display_names(&error.message);
8679 }
8680 for note in &mut error.notes {
8681 if note.contains('$') {
8682 *note = bynk_project::display_names(note);
8683 }
8684 }
8685 for (_, label) in &mut error.labels {
8686 if label.contains('$') {
8687 *label = bynk_project::display_names(label);
8688 }
8689 }
8690}
8691
8692#[cfg(test)]
8693mod metadata_property_tests {
8694 use super::is_metadata_property;
8695
8696 #[test]
8697 fn a_dot_nests_and_each_segment_is_checked() {
8698 assert!(is_metadata_property("category"));
8699 assert!(is_metadata_property("author.name"));
8700 assert!(!is_metadata_property(""));
8701 assert!(!is_metadata_property("a..b"));
8702 assert!(!is_metadata_property(".a"));
8703 assert!(!is_metadata_property("a."));
8704 assert!(!is_metadata_property("$x"));
8705 assert!(!is_metadata_property("a.$x"));
8706 assert!(!is_metadata_property("a\"b"));
8707 assert!(!is_metadata_property(&"x".repeat(513)));
8708 }
8709}
8710
8711#[cfg(test)]
8715mod lock_unit_tests {
8716 use super::*;
8717 use bynk_project::worker_groups::{WorkerGroup, WorkerGroups};
8718
8719 fn native(platform: Platform, unit: &str) -> BTreeMap<Platform, String> {
8720 BTreeMap::from([(platform, unit.to_string())])
8721 }
8722
8723 fn per_context() -> Vec<(String, BTreeMap<Platform, String>)> {
8724 vec![
8725 (
8726 "a.x".to_string(),
8727 native(Platform::Cloudflare, "bynk.cloudflare"),
8728 ),
8729 ("a.y".to_string(), native(Platform::Node, "bynk.node")),
8730 (
8731 "a.z".to_string(),
8732 native(Platform::Cloudflare, "bynk.cloudflare"),
8733 ),
8734 ]
8735 }
8736
8737 fn group(members: &[&str]) -> WorkerGroups {
8738 WorkerGroups::from([(
8739 "core".to_string(),
8740 WorkerGroup {
8741 contexts: members.iter().map(|m| m.to_string()).collect(),
8742 ..WorkerGroup::default()
8743 },
8744 )])
8745 }
8746
8747 #[test]
8749 fn workers_without_groups_is_one_unit_per_context() {
8750 let units = lock_units(BuildTarget::Workers, per_context(), &WorkerGroups::new());
8751 assert_eq!(units.len(), 3);
8752 assert!(
8753 units
8754 .iter()
8755 .all(|u| u.group.is_none() && u.members.len() == 1)
8756 );
8757 assert!(units.iter().all(
8758 |u| lock_violation(&u.native, Platform::Cloudflare).is_some()
8759 == (u.members[0] == "a.y")
8760 ));
8761 }
8762
8763 #[test]
8766 fn a_group_is_one_unit_over_its_members_union() {
8767 let units = lock_units(BuildTarget::Workers, per_context(), &group(&["a.x", "a.y"]));
8768 assert_eq!(units.len(), 2, "{units:?}");
8769 let core = &units[0];
8770 assert_eq!(core.group.as_deref(), Some("core"));
8771 assert_eq!(core.members, ["a.x", "a.y"]);
8772 assert!(matches!(
8773 lock_violation(&core.native, Platform::Cloudflare),
8774 Some(LockViolation::Conflict { .. })
8775 ));
8776 assert_eq!(units[1].members, ["a.z"]);
8778 assert!(lock_violation(&units[1].native, Platform::Cloudflare).is_none());
8779 }
8780
8781 #[test]
8783 fn a_group_with_no_native_platforms_is_not_a_unit() {
8784 let units = lock_units(
8785 BuildTarget::Workers,
8786 vec![("a.x".to_string(), BTreeMap::new())],
8787 &group(&["a.x"]),
8788 );
8789 assert!(units.is_empty());
8790 }
8791
8792 #[test]
8795 fn bundle_is_one_unit_and_ignores_groups() {
8796 let units = lock_units(BuildTarget::Bundle, per_context(), &group(&["a.x", "a.y"]));
8797 assert_eq!(units.len(), 1);
8798 assert_eq!(units[0].group, None);
8799 assert_eq!(units[0].members, ["a.x"]);
8800 assert_eq!(units[0].native.len(), 2);
8801 }
8802}
8803
8804#[cfg(test)]
8805mod cross_caps_first_party_tests {
8806 use super::*;
8811 use bynk_syntax::ast::{CapRef, Ident, ProviderDecl};
8812 use bynk_syntax::span::Span;
8813
8814 fn ident(name: &str) -> Ident {
8815 Ident {
8816 name: name.to_string(),
8817 span: Span::default(),
8818 }
8819 }
8820
8821 fn bare(name: &str) -> CapRef {
8822 CapRef {
8823 context: None,
8824 name: ident(name),
8825 span: Span::default(),
8826 }
8827 }
8828
8829 fn flattened_from(unit: &str, caps: &[&str]) -> HashMap<String, String> {
8830 caps.iter()
8831 .map(|c| (c.to_string(), unit.to_string()))
8832 .collect()
8833 }
8834
8835 fn scan(declaring_unit: &str, flattened: &HashMap<String, String>) -> BTreeMap<String, String> {
8836 let mut out = BTreeMap::new();
8837 scan_cross_caps(
8838 &mut out,
8839 &[bare("Events"), bare("Ledger")],
8840 declaring_unit,
8841 &[],
8842 &HashMap::new(),
8843 flattened,
8844 );
8845 out
8846 }
8847
8848 #[test]
8849 fn a_flattened_bynk_events_is_skipped_and_other_flattened_caps_are_kept() {
8850 let flattened = flattened_from("bynk", &["Events"]);
8851 let mut flattened = flattened;
8852 flattened.insert("Ledger".to_string(), "bank".to_string());
8853 let got = scan("shop", &flattened);
8854 assert_eq!(got.keys().collect::<Vec<_>>(), ["Ledger"]);
8855 }
8856
8857 #[test]
8858 fn an_events_declared_by_bynk_itself_is_skipped_without_being_flattened() {
8859 let mut flattened = HashMap::new();
8860 flattened.insert("Ledger".to_string(), "bank".to_string());
8861 let got = scan("bynk", &flattened);
8862 assert_eq!(got.keys().collect::<Vec<_>>(), ["Ledger"]);
8863 }
8864
8865 #[test]
8866 fn an_events_flattened_from_another_unit_is_not_first_party() {
8867 let flattened = flattened_from("other", &["Events", "Ledger"]);
8868 let got = scan("shop", &flattened);
8869 assert_eq!(got.keys().collect::<Vec<_>>(), ["Events", "Ledger"]);
8870 }
8871
8872 #[test]
8873 fn a_providers_given_skips_a_flattened_bynk_events_too() {
8874 let mut table = UnitTable::default();
8875 table.providers.insert(
8876 "Billing".to_string(),
8877 ProviderDecl {
8878 capability: ident("Billing"),
8879 provider_name: ident("BillingImpl"),
8880 given: vec![bare("Events"), bare("Ledger")],
8881 ops: Vec::new(),
8882 external: false,
8883 documentation: None,
8884 span: Span::default(),
8885 trivia: Default::default(),
8886 },
8887 );
8888 let mut flattened = flattened_from("bynk", &["Events"]);
8889 flattened.insert("Ledger".to_string(), "bank".to_string());
8890 let got = provider_cross_caps(&table, "shop", &[], &HashMap::new(), &flattened);
8891 assert_eq!(got.keys().collect::<Vec<_>>(), ["Ledger"]);
8892 }
8893}