1use std::collections::{BTreeMap, HashMap};
2use std::path::PathBuf;
3use std::sync::Arc;
4
5use crate::checker::CapabilityInfo;
6use crate::index::{IndexBuilder, ProjectIndex, RefSink, SiteRef, SymbolKind};
7use crate::project_model::UnitInfo;
8use crate::resolver::{self, MethodTable as ResolverMethodTable};
9use bynk_project::{ParsedFile, UnitKind};
10use bynk_syntax::ast::SourceUnit;
11use bynk_syntax::ast::{
12 ActorDecl, AgentDecl, AssetDecl, BaseType, Block, CapRef, CapabilityDecl, CommonsItem,
13 ConstDecl, EmbedDecl, EventDecl, ExportKind, Expr, ExprId, ExprKind, FnDecl, FnName,
14 HandlerKind, Ident, Param, ProviderDecl, ServiceDecl, ServiceProtocol, Trivia, TypeBody,
15 TypeDecl, TypeRef, Visibility,
16};
17use bynk_syntax::error::CompileError;
18use bynk_syntax::span::Span;
19
20pub fn assemble_index(
26 parsed: &[ParsedFile],
27 unit_uses: &HashMap<String, Vec<String>>,
28 unit_consumes: &HashMap<String, Vec<String>>,
29 unit_type_aliases: &HashMap<String, HashMap<String, ConsumedTypeAlias>>,
30 refs: RefSink,
31) -> ProjectIndex {
32 let mut builder = IndexBuilder::default();
33 let mut uses = unit_uses.clone();
34 uses.extend(refs.extra_uses);
35 builder.set_uses(uses);
36 builder.set_consumes(unit_consumes.clone());
37 let type_aliases = unit_type_aliases
39 .iter()
40 .map(|(unit, aliases)| {
41 let aliases = aliases
42 .iter()
43 .map(|(alias, a)| (alias.clone(), (a.target.clone(), a.original.clone())))
44 .collect();
45 (unit.clone(), aliases)
46 })
47 .collect();
48 builder.set_type_aliases(type_aliases);
49 for pf in parsed {
50 if let SourceUnit::Suite(suite) = pf.unit() {
54 let path = pf.identity_path();
55 let ns = crate::test_suites::suite_helper_namespace(&suite.target.joined(), &path);
56 for f in &suite.fixtures {
58 builder.add_leaf_def(
59 &ns,
60 SymbolKind::Embed,
61 &f.name.name,
62 SiteRef {
63 path: path.clone(),
64 span: f.name.span,
65 },
66 symbol_modifiers(&ns, None),
67 );
68 }
69 for t in &suite.types {
72 builder.add_def(
73 &ns,
74 SymbolKind::Type,
75 &t.name.name,
76 SiteRef {
77 path: path.clone(),
78 span: t.name.span,
79 },
80 symbol_modifiers(&ns, Some(t)),
81 );
82 }
83 for c in &suite.consts {
84 builder.add_leaf_def(
85 &ns,
86 SymbolKind::Const,
87 &c.name.name,
88 SiteRef {
89 path: path.clone(),
90 span: c.name.span,
91 },
92 symbol_modifiers(&ns, None),
93 );
94 }
95 for f in &suite.fns {
96 if let FnName::Free(id) = &f.name {
97 builder.add_def(
98 &ns,
99 SymbolKind::Fn,
100 &id.name,
101 SiteRef {
102 path: path.clone(),
103 span: id.span,
104 },
105 symbol_modifiers(&ns, None),
106 );
107 }
108 }
109 }
110 if matches!(pf.kind(), UnitKind::Test | UnitKind::Integration) {
111 continue;
112 }
113 let unit = pf.unit().name().joined();
114 if pf.is_synthetic() {
119 for item in pf.items() {
120 let (kind, name, modifiers) = match item {
121 CommonsItem::Type(t) => (
122 SymbolKind::Type,
123 &t.name.name,
124 symbol_modifiers(&unit, Some(t)),
125 ),
126 CommonsItem::Event(e) => (
132 SymbolKind::Type,
133 &e.name.name,
134 symbol_modifiers(&unit, None),
135 ),
136 CommonsItem::Fn(f) => match &f.name {
137 FnName::Free(id) => {
138 (SymbolKind::Fn, &id.name, symbol_modifiers(&unit, None))
139 }
140 FnName::Method { .. } => continue,
141 },
142 CommonsItem::Capability(c) => (
143 SymbolKind::Capability,
144 &c.name.name,
145 symbol_modifiers(&unit, None),
146 ),
147 CommonsItem::Service(s) => (
148 SymbolKind::Service,
149 &s.name.name,
150 symbol_modifiers(&unit, None),
151 ),
152 CommonsItem::Agent(a) => (
153 SymbolKind::Agent,
154 &a.name.name,
155 symbol_modifiers(&unit, None),
156 ),
157 CommonsItem::Provider(p) => (
158 SymbolKind::Provider,
159 &p.provider_name.name,
160 symbol_modifiers(&unit, None),
161 ),
162 CommonsItem::Actor(a) => (
163 SymbolKind::Actor,
164 &a.name.name,
165 symbol_modifiers(&unit, None),
166 ),
167 CommonsItem::Messages(m) => {
168 (SymbolKind::Messages, &m.tag, symbol_modifiers(&unit, None))
169 }
170 CommonsItem::Asset(a) => (
173 SymbolKind::Asset,
174 &a.name.name,
175 symbol_modifiers(&unit, None),
176 ),
177 CommonsItem::Embed(e) => (
180 SymbolKind::Embed,
181 &e.name.name,
182 symbol_modifiers(&unit, None),
183 ),
184 CommonsItem::Const(c) => (
187 SymbolKind::Const,
188 &c.name.name,
189 symbol_modifiers(&unit, None),
190 ),
191 };
192 builder.add_first_party_def(&unit, kind, name, modifiers);
193 }
194 continue;
195 }
196 let site = |id: &Ident| SiteRef {
197 path: pf.identity_path(),
198 span: id.span,
199 };
200 for item in pf.items() {
201 match item {
202 CommonsItem::Type(t) => {
203 builder.add_def(
204 &unit,
205 SymbolKind::Type,
206 &t.name.name,
207 site(&t.name),
208 symbol_modifiers(&unit, Some(t)),
209 );
210 if let TypeBody::Refined {
215 base, base_span, ..
216 }
217 | TypeBody::Opaque {
218 base, base_span, ..
219 } = &t.body
220 {
221 let opaque = matches!(t.body, TypeBody::Opaque { .. });
222 let base_site = SiteRef {
223 path: pf.identity_path(),
224 span: *base_span,
225 };
226 builder.add_refinement(&unit, &t.name.name, *base, opaque, base_site);
227 }
228 if let TypeBody::Record(r) = &t.body {
231 for field in &r.fields {
232 builder.add_def(
233 &unit,
234 SymbolKind::Field,
235 &format!("{}.{}", t.name.name, field.name.name),
236 site(&field.name),
237 symbol_modifiers(&unit, None),
238 );
239 }
240 }
241 }
242 CommonsItem::Event(e) => {
248 builder.add_def(
249 &unit,
250 SymbolKind::Type,
251 &e.name.name,
252 site(&e.name),
253 symbol_modifiers(&unit, None),
254 );
255 for field in &e.body.fields {
256 builder.add_def(
257 &unit,
258 SymbolKind::Field,
259 &format!("{}.{}", e.name.name, field.name.name),
260 site(&field.name),
261 symbol_modifiers(&unit, None),
262 );
263 }
264 }
265 CommonsItem::Fn(f) => match &f.name {
266 FnName::Free(id) => {
267 builder.add_def(
268 &unit,
269 SymbolKind::Fn,
270 &id.name,
271 site(id),
272 symbol_modifiers(&unit, None),
273 );
274 }
275 FnName::Method { .. } => {
276 builder.add_owner(&unit, &f.name.display(), &pf.identity_path());
280 builder.add_def(
281 &unit,
282 SymbolKind::Method,
283 &f.name.display(),
284 site(f.name.ident()),
285 symbol_modifiers(&unit, None),
286 );
287 }
288 },
289 CommonsItem::Capability(c) => {
290 builder.add_def(
291 &unit,
292 SymbolKind::Capability,
293 &c.name.name,
294 site(&c.name),
295 symbol_modifiers(&unit, None),
296 );
297 for op in &c.ops {
300 builder.add_def(
301 &unit,
302 SymbolKind::CapabilityOp,
303 &format!("{}.{}", c.name.name, op.name.name),
304 site(&op.name),
305 symbol_modifiers(&unit, None),
306 );
307 }
308 }
309 CommonsItem::Service(s) => add_service_defs(&mut builder, &unit, pf, s),
310 CommonsItem::Agent(a) => {
311 builder.add_def(
312 &unit,
313 SymbolKind::Agent,
314 &a.name.name,
315 site(&a.name),
316 symbol_modifiers(&unit, None),
317 );
318 for h in &a.handlers {
324 if let Some(name) = &h.method_name {
325 builder.add_def(
326 &unit,
327 SymbolKind::Handler,
328 &format!("{}.{}", a.name.name, name.name),
329 site(name),
330 symbol_modifiers(&unit, None),
331 );
332 }
333 }
334 }
335 CommonsItem::Provider(p) => {
336 builder.add_def(
337 &unit,
338 SymbolKind::Provider,
339 &p.provider_name.name,
340 site(&p.provider_name),
341 symbol_modifiers(&unit, None),
342 );
343 }
344 CommonsItem::Actor(a) => {
345 builder.add_def(
346 &unit,
347 SymbolKind::Actor,
348 &a.name.name,
349 site(&a.name),
350 symbol_modifiers(&unit, None),
351 );
352 }
353 CommonsItem::Messages(m) => {
354 builder.add_def(
357 &unit,
358 SymbolKind::Messages,
359 &m.tag,
360 SiteRef {
361 path: pf.identity_path(),
362 span: m.tag_span,
363 },
364 symbol_modifiers(&unit, None),
365 );
366 }
367 CommonsItem::Asset(a) => {
374 builder.add_leaf_def(
375 &unit,
376 SymbolKind::Asset,
377 &a.name.name,
378 site(&a.name),
379 symbol_modifiers(&unit, None),
380 );
381 }
382 CommonsItem::Embed(e) => {
386 builder.add_leaf_def(
387 &unit,
388 SymbolKind::Embed,
389 &e.name.name,
390 site(&e.name),
391 symbol_modifiers(&unit, None),
392 );
393 }
394 CommonsItem::Const(c) => {
397 builder.add_leaf_def(
398 &unit,
399 SymbolKind::Const,
400 &c.name.name,
401 site(&c.name),
402 symbol_modifiers(&unit, None),
403 );
404 }
405 }
406 }
407 }
408 builder.build(refs.edges)
409}
410
411fn add_service_defs(
417 builder: &mut IndexBuilder,
418 unit: &str,
419 pf: &ParsedFile,
420 service: &ServiceDecl,
421) {
422 let (path, source) = (pf.identity_path(), pf.source());
423 builder.add_def(
424 unit,
425 SymbolKind::Service,
426 &service.name.name,
427 SiteRef {
428 path: path.clone(),
429 span: service.name.span,
430 },
431 symbol_modifiers(unit, None),
432 );
433 for h in &service.handlers {
434 let label = match &h.kind {
435 HandlerKind::Call => "call".to_string(),
436 HandlerKind::Http { method, path } => format!("{} {path}", method.as_str()),
437 _ => continue,
438 };
439 let start = on_keyword_start(source, h);
440 let span = Span {
441 start,
442 end: start + 2,
443 ..h.span
444 };
445 builder.add_call_only_def(
446 unit,
447 &format!("{}.{label}", service.name.name),
448 SiteRef {
449 path: path.clone(),
450 span,
451 },
452 );
453 }
454}
455
456fn on_keyword_start(source: &str, h: &bynk_syntax::ast::Handler) -> usize {
460 let Some(last) = h.annotations.last() else {
461 return h.span.start;
462 };
463 let mut at = last.span.end;
464 while let Some(rest) = source.get(at..) {
465 let trimmed = rest.trim_start();
466 at += rest.len() - trimmed.len();
467 if trimmed.starts_with("//") {
468 at += trimmed.find('\n').map_or(trimmed.len(), |n| n + 1);
469 } else {
470 break;
471 }
472 }
473 if source.get(at..).is_some_and(|r| r.starts_with("on")) {
474 at
475 } else {
476 h.span.start
477 }
478}
479
480fn symbol_modifiers(unit: &str, type_decl: Option<&TypeDecl>) -> crate::index::SymbolModifiers {
486 let (refined, opaque) = match type_decl.map(|t| &t.body) {
487 Some(TypeBody::Refined { refinement, .. }) => (refinement.is_some(), false),
488 Some(TypeBody::Opaque { refinement, .. }) => (refinement.is_some(), true),
489 _ => (false, false),
490 };
491 crate::index::SymbolModifiers {
492 refined,
493 opaque,
494 platform_native: crate::firstparty::platform_of(unit).is_some(),
495 }
496}
497
498#[derive(Clone, Default)]
500pub struct UnitTable {
501 pub exec_plan: Arc<crate::exec_plan::ExecPlan>,
506 pub kind: Option<UnitKind>,
507 pub types: HashMap<String, Arc<TypeDecl>>,
508 pub fns: HashMap<String, Arc<FnDecl>>,
509 pub methods: HashMap<String, ResolverMethodTable>,
510 pub capabilities: HashMap<String, CapabilityDecl>,
512 pub providers: HashMap<String, ProviderDecl>,
515 pub services: HashMap<String, ServiceDecl>,
517 pub agents: HashMap<String, Arc<AgentDecl>>,
519 pub removed_agents: Vec<bynk_syntax::ast::RemovedAgentDecl>,
522 pub actors: HashMap<String, ActorDecl>,
524 pub exported_capabilities: std::collections::HashSet<String>,
527 pub events: HashMap<String, EventDecl>,
536 pub assets: HashMap<String, AssetDecl>,
541 pub embeds: HashMap<String, EmbedDecl>,
546 pub consts: HashMap<String, ConstDecl>,
552 pub flattened_caps: HashMap<String, String>,
557 pub consumed_type_aliases: HashMap<String, ConsumedTypeAlias>,
560 pub unselected_consumed_types: std::collections::BTreeSet<String>,
567 pub unlisted_consumed_types: std::collections::BTreeSet<String>,
572 pub derived: HashMap<String, DerivedInstance>,
578}
579
580pub(crate) type SortedMethods<'a> = (
582 &'a String,
583 Vec<(&'a String, &'a Arc<FnDecl>)>,
584 Vec<(&'a String, &'a Arc<FnDecl>)>,
585);
586
587pub(crate) fn sorted_methods(
591 methods: &HashMap<String, ResolverMethodTable>,
592) -> Vec<SortedMethods<'_>> {
593 fn sorted(m: &HashMap<String, Arc<FnDecl>>) -> Vec<(&String, &Arc<FnDecl>)> {
594 let mut v: Vec<_> = m.iter().collect();
595 v.sort_by(|a, b| a.0.cmp(b.0));
596 v
597 }
598 let mut out: Vec<_> = methods
599 .iter()
600 .map(|(k, t)| (k, sorted(&t.instance), sorted(&t.statics)))
601 .collect();
602 out.sort_by(|a, b| a.0.cmp(b.0));
603 out
604}
605
606impl UnitTable {
607 pub fn unselected_names(&self) -> std::collections::HashSet<String> {
609 self.unselected_consumed_types.iter().cloned().collect()
610 }
611
612 pub(crate) fn cross_unit_facts(&self) -> impl std::fmt::Debug + '_ {
621 fn sorted<K: Ord, V>(m: &HashMap<K, V>) -> Vec<(&K, &V)> {
622 let mut v: Vec<_> = m.iter().collect();
623 v.sort_by(|a, b| a.0.cmp(b.0));
624 v
625 }
626 let UnitTable {
627 exec_plan: _,
629 kind,
630 types: _,
632 fns: _,
633 methods: _,
634 capabilities: _,
635 providers: _,
636 services: _,
637 agents: _,
638 removed_agents: _,
639 actors: _,
640 exported_capabilities: _,
641 events: _,
642 assets: _,
643 embeds: _,
644 consts: _,
645 flattened_caps,
647 consumed_type_aliases,
648 unselected_consumed_types,
649 unlisted_consumed_types,
650 derived,
651 } = self;
652 (
653 *kind,
654 sorted(flattened_caps),
655 sorted(consumed_type_aliases),
656 unselected_consumed_types,
657 unlisted_consumed_types,
658 sorted(derived),
659 )
660 }
661
662 pub fn has_private(&self) -> bool {
664 self.types.values().any(|d| d.private.is_some())
665 || self.fns.values().any(|d| d.private.is_some())
666 || self.assets.values().any(|d| d.private.is_some())
667 || self.embeds.values().any(|d| d.private.is_some())
668 || self.consts.values().any(|d| d.private.is_some())
669 || self.methods.values().any(|mt| {
670 mt.instance
671 .values()
672 .chain(mt.statics.values())
673 .any(|d| d.private.is_some())
674 })
675 }
676
677 pub fn importable(&self) -> std::borrow::Cow<'_, UnitTable> {
685 if !self.has_private() {
686 return std::borrow::Cow::Borrowed(self);
687 }
688 let mut t = self.clone();
689 let private_types: std::collections::HashSet<String> = t
690 .types
691 .iter()
692 .filter(|(_, d)| d.private.is_some())
693 .map(|(n, _)| n.clone())
694 .collect();
695 t.types.retain(|n, _| !private_types.contains(n));
696 t.fns.retain(|_, d| d.private.is_none());
697 t.assets.retain(|_, d| d.private.is_none());
698 t.embeds.retain(|_, d| d.private.is_none());
699 t.consts.retain(|_, d| d.private.is_none());
700 t.methods.retain(|n, _| !private_types.contains(n));
701 for mt in t.methods.values_mut() {
702 mt.instance.retain(|_, d| d.private.is_none());
703 mt.statics.retain(|_, d| d.private.is_none());
704 }
705 std::borrow::Cow::Owned(t)
706 }
707
708 pub fn private_subjects(&self) -> Vec<(String, &'static str)> {
714 let mut out: Vec<(String, &'static str)> = Vec::new();
715 for (n, d) in &self.types {
716 if d.private.is_some() {
717 out.push((n.clone(), "type"));
718 }
719 }
720 for (n, d) in &self.fns {
721 if d.private.is_some() {
722 out.push((n.clone(), "function"));
723 }
724 }
725 for (n, d) in &self.assets {
726 if d.private.is_some() {
727 out.push((n.clone(), "asset"));
728 }
729 }
730 for (n, d) in &self.embeds {
731 if d.private.is_some() {
732 out.push((n.clone(), "embed"));
733 }
734 }
735 for (n, d) in &self.consts {
736 if d.private.is_some() {
737 out.push((n.clone(), "constant"));
738 }
739 }
740 for (ty, mt) in &self.methods {
741 let type_private = self.types.get(ty).is_some_and(|d| d.private.is_some());
742 for (m, d) in mt.instance.iter().chain(mt.statics.iter()) {
743 if d.private.is_some() || type_private {
744 out.push((format!("{ty}.{m}"), "method"));
745 }
746 }
747 }
748 out
749 }
750}
751
752#[derive(Debug, Clone, PartialEq, Eq)]
756pub struct DerivedInstance {
757 pub base_unit: String,
759 pub base_cap: String,
761 pub binding: String,
763 pub options: Vec<(String, OptionValue)>,
767 pub span: bynk_syntax::span::Span,
769}
770
771pub fn is_edge_cache_base(unit: &str, capability: &str) -> bool {
774 unit == crate::firstparty::CLOUDFLARE_UNIT && capability == "EdgeCache"
775}
776
777#[derive(Debug, Clone, PartialEq, Eq)]
779pub enum OptionValue {
780 Str(String),
782 Int(i64),
784 Seconds(i64),
786 List(Vec<String>),
789}
790
791impl DerivedInstance {
792 pub fn option(&self, name: &str) -> Option<&str> {
794 self.options
795 .iter()
796 .find(|(o, _)| o == name)
797 .and_then(|(_, v)| match v {
798 OptionValue::Str(s) => Some(s.as_str()),
799 _ => None,
800 })
801 }
802
803 pub fn list(&self, name: &str) -> &[String] {
806 self.options
807 .iter()
808 .find(|(o, _)| o == name)
809 .and_then(|(_, v)| match v {
810 OptionValue::List(items) => Some(items.as_slice()),
811 _ => None,
812 })
813 .unwrap_or_default()
814 }
815
816 pub fn number(&self, name: &str) -> Option<i64> {
819 self.options
820 .iter()
821 .find(|(o, _)| o == name)
822 .and_then(|(_, v)| match v {
823 OptionValue::Int(n) | OptionValue::Seconds(n) => Some(*n),
824 OptionValue::Str(_) | OptionValue::List(_) => None,
825 })
826 }
827
828 pub fn is_ratelimit(&self) -> bool {
830 self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "RateLimit"
831 }
832
833 pub fn is_edge_cache(&self) -> bool {
835 is_edge_cache_base(&self.base_unit, &self.base_cap)
836 }
837
838 pub fn rate_limit(&self) -> Option<(i64, i64)> {
841 if !self.is_ratelimit() {
842 return None;
843 }
844 Some((
845 self.number(crate::firstparty::RATELIMIT_LIMIT_OPTION)?,
846 self.number(crate::firstparty::RATELIMIT_PERIOD_OPTION)?,
847 ))
848 }
849
850 pub fn jurisdiction(&self) -> Option<&str> {
853 self.is_r2()
854 .then(|| self.option(crate::firstparty::R2_JURISDICTION_OPTION))
855 .flatten()
856 }
857
858 pub fn is_r2(&self) -> bool {
860 self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "R2"
861 }
862
863 pub fn worker(&self) -> Option<&str> {
866 (self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "Service")
867 .then(|| self.option(crate::firstparty::SERVICE_WORKER_OPTION))
868 .flatten()
869 }
870
871 pub fn store(&self) -> Option<&str> {
874 self.is_stored_secret()
875 .then(|| self.option(crate::firstparty::STORED_SECRET_STORE_OPTION))
876 .flatten()
877 }
878
879 pub fn stored_secret(&self) -> Option<&str> {
882 self.is_stored_secret()
883 .then(|| self.option(crate::firstparty::STORED_SECRET_SECRET_OPTION))
884 .flatten()
885 }
886
887 pub fn email_to(&self) -> Option<&str> {
890 self.is_email()
891 .then(|| self.option(crate::firstparty::EMAIL_TO_OPTION))
892 .flatten()
893 }
894
895 pub fn email_allowed_recipients(&self) -> &[String] {
898 self.list(crate::firstparty::EMAIL_ALLOWED_RECIPIENTS_OPTION)
899 }
900
901 pub fn email_allowed_senders(&self) -> &[String] {
904 self.list(crate::firstparty::EMAIL_ALLOWED_SENDERS_OPTION)
905 }
906
907 pub fn is_postgres(&self) -> bool {
909 self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "Postgres"
910 }
911
912 pub fn is_mysql(&self) -> bool {
914 self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "MySql"
915 }
916
917 pub fn tls(&self) -> Option<&str> {
920 self.is_mysql()
921 .then(|| self.option(crate::firstparty::MYSQL_TLS_OPTION))
922 .flatten()
923 }
924
925 pub fn is_vectorize(&self) -> bool {
927 self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "Vectorize"
928 }
929
930 pub fn vectorize_dimensions(&self) -> Option<i64> {
932 self.is_vectorize()
933 .then(|| self.number(crate::firstparty::VECTORIZE_DIMENSIONS_OPTION))
934 .flatten()
935 }
936
937 pub fn vectorize_metric(&self) -> Option<&str> {
939 self.is_vectorize()
940 .then(|| self.option(crate::firstparty::VECTORIZE_METRIC_OPTION))
941 .flatten()
942 }
943
944 pub fn vectorize_indexed(&self) -> &[String] {
947 self.list(crate::firstparty::VECTORIZE_INDEXED_OPTION)
948 }
949
950 pub fn is_container(&self) -> bool {
952 self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "Container"
953 }
954
955 pub fn container_build(&self) -> Option<&str> {
958 self.is_container()
959 .then(|| self.option(crate::firstparty::CONTAINER_BUILD_OPTION))
960 .flatten()
961 }
962
963 pub fn container_port(&self) -> Option<i64> {
965 self.is_container()
966 .then(|| self.number(crate::firstparty::CONTAINER_PORT_OPTION))
967 .flatten()
968 }
969
970 pub fn container_sleep_after(&self) -> Option<i64> {
972 self.is_container()
973 .then(|| self.number(crate::firstparty::CONTAINER_SLEEP_AFTER_OPTION))
974 .flatten()
975 }
976
977 pub fn container_instance_type(&self) -> Option<&str> {
979 self.is_container()
980 .then(|| self.option(crate::firstparty::CONTAINER_INSTANCE_TYPE_OPTION))
981 .flatten()
982 }
983
984 pub fn container_forward(&self) -> &[String] {
987 self.list(crate::firstparty::CONTAINER_FORWARD_OPTION)
988 }
989
990 pub fn is_email(&self) -> bool {
992 self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "Email"
993 }
994
995 pub fn ai_search_instance(&self) -> Option<&str> {
998 (self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "AiSearch")
999 .then(|| self.option(crate::firstparty::AI_SEARCH_INSTANCE_OPTION))
1000 .flatten()
1001 }
1002
1003 pub fn mtls_certificate(&self) -> Option<&str> {
1006 (self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "MtlsCertificate")
1007 .then(|| self.option(crate::firstparty::MTLS_CERTIFICATE_OPTION))
1008 .flatten()
1009 }
1010
1011 pub fn is_stored_secret(&self) -> bool {
1013 self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "StoredSecret"
1014 }
1015
1016 pub fn queue(&self) -> Option<&str> {
1020 (self.base_unit == crate::firstparty::CLOUDFLARE_UNIT && self.base_cap == "Queue")
1021 .then(|| self.option(crate::firstparty::QUEUE_NAME_OPTION))
1022 .flatten()
1023 }
1024}
1025
1026#[derive(Clone, Debug, PartialEq, Eq)]
1029pub struct ConsumedTypeAlias {
1030 pub target: String,
1031 pub original: String,
1032}
1033
1034pub fn record_flattened_caps(
1037 unit_tables: &mut HashMap<String, UnitTable>,
1038 unit_flattened: &HashMap<String, HashMap<String, String>>,
1039 unit_type_aliases: &HashMap<String, HashMap<String, ConsumedTypeAlias>>,
1040) {
1041 for (name, flattened) in unit_flattened {
1042 if let Some(t) = unit_tables.get_mut(name) {
1043 t.flattened_caps = flattened.clone();
1044 }
1045 }
1046 for (name, aliases) in unit_type_aliases {
1047 if let Some(t) = unit_tables.get_mut(name) {
1048 t.consumed_type_aliases = aliases.clone();
1049 }
1050 }
1051}
1052
1053pub type ConsumeSelections = HashMap<String, Vec<(String, Option<Vec<String>>)>>;
1061
1062pub fn record_unselected_consumed_types(
1063 unit_tables: &mut HashMap<String, UnitTable>,
1064 consumes: &ConsumeSelections,
1065) {
1066 type Sets = std::collections::BTreeSet<String>;
1067 let mut out: HashMap<String, (Sets, Sets)> = HashMap::new();
1068 for (unit, clauses) in consumes {
1069 let mut selection: HashMap<&str, Option<std::collections::HashSet<&str>>> = HashMap::new();
1071 for (target, names) in clauses {
1072 if !is_first_party_name(target) {
1073 continue;
1074 }
1075 match (names, selection.get_mut(target.as_str())) {
1076 (None, _) => {
1077 selection.insert(target, None);
1078 }
1079 (Some(_), Some(None)) => {}
1080 (Some(names), Some(Some(listed))) => {
1081 listed.extend(names.iter().map(String::as_str))
1082 }
1083 (Some(names), None) => {
1084 selection.insert(target, Some(names.iter().map(String::as_str).collect()));
1085 }
1086 }
1087 }
1088 for (target, listed) in selection {
1089 let (Some(listed), Some(table)) = (listed, unit_tables.get(target)) else {
1090 continue;
1091 };
1092 let unlisted: Vec<&String> = table
1093 .types
1094 .keys()
1095 .filter(|t| !listed.contains(t.as_str()))
1096 .collect();
1097 let reached = signature_types(table, &listed);
1101 let entry = out.entry(unit.clone()).or_default();
1102 entry.0.extend(unlisted.iter().map(|t| (*t).clone()));
1103 entry.1.extend(
1104 unlisted
1105 .into_iter()
1106 .filter(|t| !reached.contains(*t))
1107 .cloned(),
1108 );
1109 }
1110 }
1111 for (unit, (unlisted, unselected)) in out {
1112 if let Some(t) = unit_tables.get_mut(&unit) {
1113 t.unlisted_consumed_types = unlisted;
1114 t.unselected_consumed_types = unselected;
1115 }
1116 }
1117}
1118
1119fn signature_types(
1122 table: &UnitTable,
1123 listed: &std::collections::HashSet<&str>,
1124) -> std::collections::HashSet<String> {
1125 fn names(r: &TypeRef, out: &mut Vec<String>) {
1126 match r {
1127 TypeRef::Named(id) => out.push(id.name.clone()),
1128 TypeRef::App { name, args, .. } => {
1129 out.push(name.name.clone());
1130 args.iter().for_each(|a| names(a, out));
1131 }
1132 TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
1133 names(a, out);
1134 names(b, out);
1135 }
1136 TypeRef::Option(t, _)
1137 | TypeRef::Effect(t, _)
1138 | TypeRef::HttpResult(t, _)
1139 | TypeRef::List(t, _)
1140 | TypeRef::Set(t, _)
1141 | TypeRef::Query(t, _)
1142 | TypeRef::Stream(t, _)
1143 | TypeRef::Connection(t, _)
1144 | TypeRef::History(t, _) => names(t, out),
1145 TypeRef::Fn(params, ret, _) => {
1146 params.iter().for_each(|p| names(p, out));
1147 names(ret, out);
1148 }
1149 _ => {}
1150 }
1151 }
1152 let mut todo: Vec<String> = Vec::new();
1153 for cap in table
1154 .capabilities
1155 .values()
1156 .filter(|c| listed.contains(c.name.name.as_str()))
1157 {
1158 for op in &cap.ops {
1159 op.params.iter().for_each(|p| names(&p.type_ref, &mut todo));
1160 names(&op.return_type, &mut todo);
1161 }
1162 }
1163 let mut seen = std::collections::HashSet::new();
1164 while let Some(n) = todo.pop() {
1165 if !seen.insert(n.clone()) {
1166 continue;
1167 }
1168 match table.types.get(&n).map(|t| &t.body) {
1169 Some(TypeBody::Record(r)) => {
1170 r.fields.iter().for_each(|f| names(&f.type_ref, &mut todo))
1171 }
1172 Some(TypeBody::Sum(s)) => s
1173 .variants
1174 .iter()
1175 .flat_map(|v| &v.payload)
1176 .for_each(|p| names(&p.type_ref, &mut todo)),
1177 _ => {}
1178 }
1179 }
1180 seen
1181}
1182
1183pub(crate) fn is_first_party_name(unit: &str) -> bool {
1185 unit == "bynk" || unit.starts_with("bynk.")
1186}
1187
1188pub fn build_unit_table(
1194 _name: &str,
1195 kind: UnitKind,
1196 indices: &[usize],
1197 parsed: &[ParsedFile],
1198 out: &mut Vec<(PathBuf, CompileError)>,
1199) -> UnitTable {
1200 let mut table = UnitTable {
1201 kind: Some(kind),
1202 ..UnitTable::default()
1203 };
1204 for &i in indices {
1205 let mut errors: Vec<CompileError> = Vec::new();
1206 table
1207 .removed_agents
1208 .extend(parsed[i].removed_agents().iter().cloned());
1209 for item in parsed[i].items() {
1210 if let CommonsItem::Event(e) = item
1217 && kind != UnitKind::Context
1218 {
1219 errors.push(CompileError::new(
1220 "bynk.event.outside_context",
1221 e.span,
1222 "`event` declarations are only allowed inside a context",
1223 ));
1224 continue;
1225 }
1226 let as_type: Option<(&Ident, TypeDecl, bool)> = match item {
1227 CommonsItem::Type(t) => Some((&t.name, t.clone(), false)),
1228 CommonsItem::Event(e) => Some((&e.name, e.as_type_decl(), true)),
1229 _ => None,
1230 };
1231 if let Some((name, decl, is_event)) = as_type {
1232 if let Some(prev) = table.types.get(&name.name) {
1233 errors.push(
1234 CompileError::new(
1235 "bynk.resolve.duplicate_type",
1236 name.span,
1237 format!("type `{}` is already declared", name.name),
1238 )
1239 .with_label(prev.name.span, "previously declared here"),
1240 );
1241 } else {
1242 table.methods.entry(name.name.clone()).or_default();
1243 if is_event {
1244 let CommonsItem::Event(e) = item else {
1245 unreachable!("is_event only set for CommonsItem::Event")
1246 };
1247 table.events.insert(name.name.clone(), e.clone());
1248 }
1249 table.types.insert(name.name.clone(), Arc::new(decl));
1250 }
1251 }
1252 }
1253 out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1254 }
1255 for &i in indices {
1258 {
1259 for clause in parsed[i].exports() {
1260 if matches!(clause.kind, ExportKind::Capability) {
1261 for n in clause.names.iter().map(|e| &e.name) {
1262 table.exported_capabilities.insert(n.name.clone());
1263 }
1264 }
1265 }
1266 }
1267 }
1268 for &i in indices {
1270 let mut errors: Vec<CompileError> = Vec::new();
1271 for item in parsed[i].items() {
1272 match item {
1273 CommonsItem::Capability(c) => {
1274 if kind != UnitKind::Context && kind != UnitKind::Adapter {
1275 errors.push(CompileError::new(
1276 "bynk.capability.outside_context",
1277 c.span,
1278 "`capability` declarations are only allowed inside a context or adapter",
1279 ));
1280 continue;
1281 }
1282 if let Some(prev) = table.capabilities.get(&c.name.name) {
1283 errors.push(
1284 CompileError::new(
1285 "bynk.resolve.duplicate_capability",
1286 c.name.span,
1287 format!("capability `{}` is already declared", c.name.name),
1288 )
1289 .with_label(prev.name.span, "previously declared here"),
1290 );
1291 } else {
1292 table.capabilities.insert(c.name.name.clone(), c.clone());
1293 }
1294 }
1295 CommonsItem::Provider(p) => {
1296 match kind {
1297 UnitKind::Context => {
1298 if p.external {
1301 errors.push(CompileError::new(
1302 "bynk.context.external_provider",
1303 p.span,
1304 "an external (bodiless) provider is only allowed inside an `adapter` — a context provider must have a Bynk body",
1305 ));
1306 continue;
1307 }
1308 }
1309 UnitKind::Adapter => {
1310 if !p.external {
1313 errors.push(CompileError::new(
1314 "bynk.adapter.provider_has_body",
1315 p.span,
1316 "a provider inside an `adapter` must be external (no body) — its implementation is supplied by the binding",
1317 ));
1318 continue;
1319 }
1320 }
1321 _ => continue,
1325 }
1326 if let Some(prev) = table.providers.get(&p.capability.name) {
1327 errors.push(
1328 CompileError::new(
1329 "bynk.resolve.duplicate_provider",
1330 p.span,
1331 format!(
1332 "capability `{}` already has a provider in this context",
1333 p.capability.name
1334 ),
1335 )
1336 .with_label(prev.span, "previously provided here"),
1337 );
1338 } else {
1339 table.providers.insert(p.capability.name.clone(), p.clone());
1340 }
1341 }
1342 CommonsItem::Service(s) => {
1343 if kind == UnitKind::Adapter {
1344 errors.push(CompileError::new(
1345 "bynk.adapter.disallowed_item",
1346 s.span,
1347 "an `adapter` may not declare a `service` — adapters contain only capabilities, boundary types, external providers, and helpers",
1348 ));
1349 continue;
1350 }
1351 if kind != UnitKind::Context {
1357 continue;
1358 }
1359 if let Some(prev) = table.services.get(&s.name.name) {
1360 errors.push(
1361 CompileError::new(
1362 "bynk.resolve.duplicate_service",
1363 s.name.span,
1364 format!("service `{}` is already declared", s.name.name),
1365 )
1366 .with_label(prev.name.span, "previously declared here"),
1367 );
1368 } else {
1369 table.services.insert(s.name.name.clone(), s.clone());
1370 }
1371 }
1372 CommonsItem::Agent(a) => {
1373 if kind == UnitKind::Adapter {
1374 errors.push(CompileError::new(
1375 "bynk.adapter.disallowed_item",
1376 a.span,
1377 "an `adapter` may not declare an `agent` — adapters contain only capabilities, boundary types, external providers, and helpers",
1378 ));
1379 continue;
1380 }
1381 if kind != UnitKind::Context {
1387 continue;
1388 }
1389 if let Some(prev) = table.agents.get(&a.name.name) {
1390 errors.push(
1391 CompileError::new(
1392 "bynk.resolve.duplicate_agent",
1393 a.name.span,
1394 format!("agent `{}` is already declared", a.name.name),
1395 )
1396 .with_label(prev.name.span, "previously declared here"),
1397 );
1398 } else {
1399 table
1400 .agents
1401 .insert(a.name.name.clone(), Arc::new(a.clone()));
1402 }
1403 }
1404 CommonsItem::Actor(a) => {
1405 if kind == UnitKind::Adapter {
1406 errors.push(CompileError::new(
1407 "bynk.adapter.disallowed_item",
1408 a.span,
1409 "an `adapter` may not declare an `actor` — adapters contain only capabilities, boundary types, external providers, and helpers",
1410 ));
1411 continue;
1412 }
1413 if let Some(prev) = table.actors.get(&a.name.name) {
1414 errors.push(
1415 CompileError::new(
1416 "bynk.resolve.duplicate_actor",
1417 a.name.span,
1418 format!("actor `{}` is already declared", a.name.name),
1419 )
1420 .with_label(prev.name.span, "previously declared here"),
1421 );
1422 } else {
1423 table.actors.insert(a.name.name.clone(), a.clone());
1424 }
1425 }
1426 _ => {}
1427 }
1428 }
1429 out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1430 }
1431 for &i in indices {
1432 let mut errors: Vec<CompileError> = Vec::new();
1433 for item in parsed[i].items() {
1434 let CommonsItem::Fn(f) = item else { continue };
1435 match &f.name {
1436 FnName::Free(id) => {
1437 if let Some(prev) = table.fns.get(&id.name) {
1438 errors.push(
1439 CompileError::new(
1440 "bynk.resolve.duplicate_fn",
1441 id.span,
1442 format!("function `{}` is already declared", id.name),
1443 )
1444 .with_label(prev.name.ident().span, "previously declared here"),
1445 );
1446 } else if let Some(prev) = table.types.get(&id.name) {
1447 errors.push(
1448 CompileError::new(
1449 "bynk.resolve.name_conflict",
1450 id.span,
1451 format!(
1452 "function `{}` conflicts with a type of the same name",
1453 id.name
1454 ),
1455 )
1456 .with_label(prev.name.span, "type declared here"),
1457 );
1458 } else {
1459 table.fns.insert(id.name.clone(), Arc::new(f.clone()));
1460 }
1461 }
1462 FnName::Method {
1463 type_name,
1464 method_name,
1465 } => {
1466 if !table.types.contains_key(&type_name.name) {
1467 errors.push(
1468 CompileError::new(
1469 "bynk.resolve.method_unknown_type",
1470 type_name.span,
1471 format!(
1472 "method `{}.{}` attached to an unknown type `{}`",
1473 type_name.name, method_name.name, type_name.name
1474 ),
1475 )
1476 .with_note(
1477 "methods can only be declared on types defined in the same commons or context (across all of its files)",
1478 ),
1479 );
1480 continue;
1481 }
1482 let mt = table.methods.entry(type_name.name.clone()).or_default();
1483 let bucket = if f.has_self {
1484 &mut mt.instance
1485 } else {
1486 &mut mt.statics
1487 };
1488 if let Some(prev) = bucket.get(&method_name.name) {
1489 errors.push(
1490 CompileError::new(
1491 "bynk.resolve.duplicate_method",
1492 method_name.span,
1493 format!(
1494 "method `{}.{}` is already declared",
1495 type_name.name, method_name.name
1496 ),
1497 )
1498 .with_label(prev.name.ident().span, "previously declared here"),
1499 );
1500 } else {
1501 bucket.insert(method_name.name.clone(), Arc::new(f.clone()));
1502 }
1503 }
1504 }
1505 }
1506 out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1507 }
1508 for &i in indices {
1513 let mut errors: Vec<CompileError> = Vec::new();
1514 for item in parsed[i].items() {
1515 let CommonsItem::Asset(a) = item else {
1516 continue;
1517 };
1518 if !matches!(kind, UnitKind::Context | UnitKind::Commons) {
1519 errors.push(
1520 CompileError::new(
1521 "bynk.asset.outside_context_or_commons",
1522 a.span,
1523 "`asset` declarations are only allowed inside a context or a commons",
1524 )
1525 .with_note(
1526 "an asset ships with the Worker of each context that declares it or `uses` a commons that does",
1527 ),
1528 );
1529 continue;
1530 }
1531 errors.extend(crate::assets::at_path_error(a));
1532 if let Some(err) = crate::assets::path_errors(a) {
1533 errors.push(err);
1534 }
1538 let key = &a.name.name;
1539 match crate::assets::name_error(
1540 a,
1541 table.assets.get(key).map(|p| &p.name),
1542 table.fns.get(key).map(|f| f.name.ident()),
1543 table.types.get(key).map(|t| &t.name),
1544 ) {
1545 Some(err) => errors.push(err),
1546 None => {
1547 table.assets.insert(key.clone(), a.clone());
1548 }
1549 }
1550 }
1551 out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1552 }
1553 for &i in indices {
1558 let mut errors: Vec<CompileError> = Vec::new();
1559 for item in parsed[i].items() {
1560 let CommonsItem::Embed(e) = item else {
1561 continue;
1562 };
1563 if !matches!(kind, UnitKind::Context | UnitKind::Commons) {
1564 errors.push(crate::embeds::placement_error(e));
1565 continue;
1566 }
1567 if let Some(err) = crate::embeds::path_errors(e) {
1568 errors.push(err);
1569 }
1573 let key = &e.name.name;
1574 match crate::embeds::name_error(
1575 e,
1576 table.embeds.get(key).map(|p| &p.name),
1577 table.assets.get(key).map(|a| &a.name),
1578 table.fns.get(key).map(|f| f.name.ident()),
1579 table.types.get(key).map(|t| &t.name),
1580 ) {
1581 Some(err) => errors.push(err),
1582 None => {
1583 table.embeds.insert(key.clone(), e.clone());
1584 }
1585 }
1586 }
1587 out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1588 }
1589 for &i in indices {
1592 let mut errors: Vec<CompileError> = Vec::new();
1593 for item in parsed[i].items() {
1594 let CommonsItem::Const(c) = item else {
1595 continue;
1596 };
1597 if !matches!(kind, UnitKind::Context | UnitKind::Commons) {
1598 errors.push(crate::consts::placement_error(c));
1599 continue;
1600 }
1601 let key = &c.name.name;
1602 match crate::consts::name_error(
1603 c,
1604 table.consts.get(key).map(|p| &p.name),
1605 table.embeds.get(key).map(|p| &p.name),
1606 table.assets.get(key).map(|a| &a.name),
1607 table.fns.get(key).map(|f| f.name.ident()),
1608 table.types.get(key).map(|t| &t.name),
1609 )
1610 .or_else(|| crate::consts::builtin_name_error(c))
1611 {
1612 Some(err) => errors.push(err),
1613 None => {
1614 table.consts.insert(key.clone(), c.clone());
1615 }
1616 }
1617 }
1618 out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1619 }
1620 let mut providers_seen: HashMap<&str, Span> = HashMap::new();
1628 for &i in indices {
1629 let mut errors: Vec<CompileError> = Vec::new();
1630 for item in parsed[i].items() {
1631 let (what, name) = match item {
1635 CommonsItem::Service(s)
1636 if table.services.get(&s.name.name).map(|p| p.name.span)
1637 == Some(s.name.span) =>
1638 {
1639 (ValueKind::Service, &s.name)
1640 }
1641 CommonsItem::Agent(a)
1642 if table.agents.get(&a.name.name).map(|p| p.name.span) == Some(a.name.span) =>
1643 {
1644 (ValueKind::Agent, &a.name)
1645 }
1646 CommonsItem::Provider(p)
1647 if !p.external
1648 && table.providers.get(&p.capability.name).map(|q| q.span)
1649 == Some(p.span) =>
1650 {
1651 (ValueKind::Provider, &p.provider_name)
1652 }
1653 _ => continue,
1654 };
1655 let earlier_provider = (what == ValueKind::Provider)
1659 .then(|| providers_seen.get(name.name.as_str()).copied())
1660 .flatten();
1661 if let Some(err) = value_namespace_error(&table, what, name, earlier_provider) {
1662 errors.push(err);
1663 }
1664 if what == ValueKind::Provider {
1665 providers_seen.entry(&name.name).or_insert(name.span);
1666 }
1667 }
1668 out.extend(errors.into_iter().map(|e| (parsed[i].identity_path(), e)));
1669 }
1670 if kind == UnitKind::Commons
1685 && let Some(m) = indices.iter().find_map(|&i| {
1686 parsed[i].items().iter().find_map(|item| match item {
1687 CommonsItem::Messages(m) => Some(m),
1688 _ => None,
1689 })
1690 })
1691 {
1692 if let Some(prev) = table.fns.get("render") {
1693 out.push((
1694 parsed[indices[0]].identity_path(),
1695 CompileError::new(
1696 "bynk.resolve.duplicate_fn",
1697 m.span,
1698 "function `render` is already declared",
1699 )
1700 .with_label(prev.name.ident().span, "previously declared here")
1701 .with_note(
1702 "a `messages` block in this commons implicitly declares its own \
1703 `render(tag, msg) -> String` — name it something else",
1704 ),
1705 ));
1706 } else {
1707 table
1708 .fns
1709 .insert("render".to_string(), Arc::new(synthetic_render_fn()));
1710 }
1711 }
1712 table
1713}
1714
1715pub fn local_value_kind(table: &UnitTable, name: &str) -> Option<(&'static str, Span)> {
1722 if let Some(f) = table.fns.get(name) {
1723 Some(("function", f.name.ident().span))
1724 } else if let Some(a) = table.assets.get(name) {
1725 Some(("asset", a.name.span))
1726 } else if let Some(e) = table.embeds.get(name) {
1727 Some(("embed", e.name.span))
1728 } else if let Some(c) = table.consts.get(name) {
1729 Some(("constant", c.name.span))
1730 } else if let Some(e) = table.events.get(name) {
1731 Some(("event", e.name.span))
1732 } else if let Some(t) = table.types.get(name) {
1733 Some(("type", t.name.span))
1734 } else if let Some(s) = table.services.get(name) {
1735 Some(("service", s.name.span))
1736 } else if let Some(a) = table.agents.get(name) {
1737 Some(("agent", a.name.span))
1738 } else {
1739 table
1740 .providers
1741 .values()
1742 .find(|p| !p.external && p.provider_name.name == name)
1743 .map(|p| ("provider", p.provider_name.span))
1744 }
1745}
1746
1747#[derive(Clone, Copy, PartialEq, Eq)]
1750enum ValueKind {
1751 Service,
1752 Agent,
1753 Provider,
1754}
1755
1756fn value_namespace_error(
1762 table: &UnitTable,
1763 what: ValueKind,
1764 name: &Ident,
1765 earlier_provider: Option<Span>,
1766) -> Option<CompileError> {
1767 let key = &name.name;
1768 let services = || table.services.get(key).map(|s| s.name.span);
1769 let agents = || table.agents.get(key).map(|a| a.name.span);
1770 let (other, prev) = if let Some(f) = table.fns.get(key) {
1771 ("function", f.name.ident().span)
1772 } else if let Some(a) = table.assets.get(key) {
1773 ("asset", a.name.span)
1774 } else if let Some(e) = table.embeds.get(key) {
1775 ("embed", e.name.span)
1776 } else if let Some(c) = table.consts.get(key) {
1777 ("constant", c.name.span)
1778 } else if let Some(e) = table.events.get(key) {
1779 ("event", e.name.span)
1780 } else if let Some(t) = table.types.get(key) {
1781 ("type", t.name.span)
1782 } else if let Some(span) = (what != ValueKind::Service).then(services).flatten() {
1783 ("service", span)
1784 } else if let Some(span) = (what == ValueKind::Provider).then(agents).flatten() {
1785 ("agent", span)
1786 } else if let Some(span) = earlier_provider {
1787 ("provider", span)
1788 } else {
1789 return None;
1790 };
1791 let what = match what {
1792 ValueKind::Service => "service",
1793 ValueKind::Agent => "agent",
1794 ValueKind::Provider => "provider",
1795 };
1796 let other_article = if matches!(other, "asset" | "embed" | "event" | "agent") {
1797 "an"
1798 } else {
1799 "a"
1800 };
1801 Some(
1802 CompileError::new(
1803 "bynk.resolve.name_conflict",
1804 name.span,
1805 format!("{what} `{key}` conflicts with {other_article} {other} of the same name"),
1806 )
1807 .with_label(prev, format!("{other} declared here"))
1808 .with_note(
1809 "a unit's services, agents, providers, functions, assets, embeds, constants, types and events share one namespace",
1810 ),
1811 )
1812}
1813
1814fn synthetic_render_fn() -> FnDecl {
1819 let span = Span::default();
1820 FnDecl {
1821 type_params: Vec::new(),
1822 name: FnName::Free(Ident {
1823 name: "render".to_string(),
1824 span,
1825 }),
1826 params: vec![
1827 Param {
1828 name: Ident {
1829 name: "tag".to_string(),
1830 span,
1831 },
1832 type_ref: TypeRef::Named(Ident {
1833 name: "LocaleTag".to_string(),
1834 span,
1835 }),
1836 span,
1837 },
1838 Param {
1839 name: Ident {
1840 name: "msg".to_string(),
1841 span,
1842 },
1843 type_ref: TypeRef::Named(Ident {
1844 name: "Message".to_string(),
1845 span,
1846 }),
1847 span,
1848 },
1849 ],
1850 return_type: TypeRef::Base(BaseType::String, span),
1851 given: Vec::new(),
1852 where_bounds: Vec::new(),
1853 requires: Vec::new(),
1854 ensures: Vec::new(),
1855 body: Block {
1856 statements: Vec::new(),
1857 tail: Box::new(Expr {
1858 id: ExprId::SYNTHETIC,
1859 kind: ExprKind::StrLit(String::new()),
1860 span,
1861 }),
1862 span,
1863 tail_leading_comments: Vec::new(),
1864 implicit_tail: false,
1865 },
1866 has_self: false,
1867 documentation: None,
1868 span,
1869 trivia: Trivia::default(),
1870 private: None,
1871 }
1872}
1873
1874pub fn is_synthetic_render(f: &FnDecl) -> bool {
1880 matches!(&f.name, FnName::Free(n) if n.name == "render")
1881 && f.span == Span::default()
1882 && f.body.tail.id == ExprId::SYNTHETIC
1883}
1884
1885#[derive(Clone)]
1888pub struct FileDeclIndex {
1889 pub types: HashMap<String, PathBuf>,
1890 pub fns: HashMap<String, PathBuf>,
1891 pub methods: HashMap<String, HashMap<String, PathBuf>>,
1892 pub agents: HashMap<String, PathBuf>,
1895 pub capabilities: HashMap<String, PathBuf>,
1899}
1900
1901pub fn build_file_decl_index(indices: &[usize], parsed: &[ParsedFile]) -> FileDeclIndex {
1909 let mut idx = FileDeclIndex {
1910 types: HashMap::new(),
1911 fns: HashMap::new(),
1912 methods: HashMap::new(),
1913 agents: HashMap::new(),
1914 capabilities: HashMap::new(),
1915 };
1916 for &i in indices {
1917 let path = parsed[i].source_path();
1918 for item in parsed[i].items() {
1919 match item {
1920 CommonsItem::Type(t) => {
1921 idx.types
1922 .entry(t.name.name.clone())
1923 .or_insert_with(|| path.clone());
1924 }
1925 CommonsItem::Event(e) => {
1930 idx.types
1931 .entry(e.name.name.clone())
1932 .or_insert_with(|| path.clone());
1933 }
1934 CommonsItem::Fn(f) => match &f.name {
1935 FnName::Free(id) => {
1936 idx.fns
1937 .entry(id.name.clone())
1938 .or_insert_with(|| path.clone());
1939 }
1940 FnName::Method {
1941 type_name,
1942 method_name,
1943 } => {
1944 idx.methods
1945 .entry(type_name.name.clone())
1946 .or_default()
1947 .entry(method_name.name.clone())
1948 .or_insert_with(|| path.clone());
1949 }
1950 },
1951 CommonsItem::Agent(a) => {
1952 idx.agents
1953 .entry(a.name.name.clone())
1954 .or_insert_with(|| path.clone());
1955 }
1956 CommonsItem::Capability(c) => {
1957 idx.capabilities
1958 .entry(c.name.name.clone())
1959 .or_insert_with(|| path.clone());
1960 }
1961 CommonsItem::Provider(_)
1962 | CommonsItem::Service(_)
1963 | CommonsItem::Actor(_)
1964 | CommonsItem::Messages(_) => {}
1967 CommonsItem::Asset(a) => {
1971 idx.fns
1972 .entry(a.name.name.clone())
1973 .or_insert_with(|| path.clone());
1974 }
1975 CommonsItem::Embed(e) => {
1978 idx.fns
1979 .entry(e.name.name.clone())
1980 .or_insert_with(|| path.clone());
1981 }
1982 CommonsItem::Const(c) => {
1985 idx.fns
1986 .entry(c.name.name.clone())
1987 .or_insert_with(|| path.clone());
1988 }
1989 }
1990 }
1991 }
1992 idx
1993}
1994
1995pub fn uses_span_of(
1998 parsed: &[ParsedFile],
1999 indices: &[usize],
2000 target: &str,
2001) -> Option<(usize, Span)> {
2002 for &i in indices {
2003 for u in parsed[i].uses() {
2004 if u.target.joined() == target {
2005 return Some((i, u.span));
2006 }
2007 }
2008 }
2009 None
2010}
2011
2012pub fn build_cross_context_info(
2016 name: &str,
2017 unit_consumes: &HashMap<String, Vec<String>>,
2018 unit_consumes_aliases: &HashMap<String, HashMap<String, String>>,
2019 unit_uses: &HashMap<String, Vec<String>>,
2020 unit_tables: &HashMap<String, UnitTable>,
2021) -> resolver::CrossContextInfo {
2022 let consumed_contexts: Vec<String> = unit_consumes.get(name).cloned().unwrap_or_default();
2023 let aliases: HashMap<String, String> =
2024 unit_consumes_aliases.get(name).cloned().unwrap_or_default();
2025 let mut consumed_services: HashMap<String, HashMap<String, resolver::CrossContextService>> =
2026 HashMap::new();
2027 let mut consumed_types: HashMap<String, HashMap<String, Arc<TypeDecl>>> = HashMap::new();
2028 let mut consumed_capabilities: HashMap<
2029 String,
2030 HashMap<String, resolver::CrossContextCapability>,
2031 > = HashMap::new();
2032 let mut consumed_event_names: HashMap<String, std::collections::HashSet<String>> =
2037 HashMap::new();
2038 let mut consumed_type_owners: HashMap<String, HashMap<String, String>> = HashMap::new();
2039 let mut consumed_type_aliases: HashMap<String, HashMap<String, String>> = HashMap::new();
2040 let mut callee_type_aliases: HashMap<String, HashMap<String, String>> = HashMap::new();
2041 let mut callee_alias_keys_out: HashMap<String, HashMap<String, String>> = HashMap::new();
2042 for t in &consumed_contexts {
2043 if let Some(own) = unit_tables
2044 .get(t)
2045 .map(|table| &table.consumed_type_aliases)
2046 .filter(|own| !own.is_empty())
2047 {
2048 callee_type_aliases.insert(
2049 t.clone(),
2050 own.iter()
2051 .map(|(alias, a)| (alias.clone(), a.original.clone()))
2052 .collect(),
2053 );
2054 }
2055 let (mut other_types_combined, mut owners) =
2056 contract_types_for(t, unit_tables, unit_uses, unit_consumes);
2057 let callee_keys = callee_alias_keys(t, unit_tables, &other_types_combined);
2060 let renames: HashMap<String, String> = unit_tables
2065 .get(name)
2066 .map(|table| {
2067 table
2068 .consumed_type_aliases
2069 .iter()
2070 .filter(|(_, a)| a.target == *t)
2071 .map(|(alias, a)| (a.original.clone(), alias.clone()))
2072 .collect()
2073 })
2074 .unwrap_or_default();
2075 if !renames.is_empty() {
2076 other_types_combined = other_types_combined
2077 .into_iter()
2078 .map(|(key, decl)| {
2079 let key = renames.get(&key).cloned().unwrap_or(key);
2080 let decl = rename_consumed_decl(&decl, &key, &renames);
2081 (key, decl)
2082 })
2083 .collect();
2084 }
2085 if !renames.is_empty() {
2086 consumed_type_aliases.insert(
2087 t.clone(),
2088 renames
2089 .iter()
2090 .map(|(o, a)| (a.clone(), o.clone()))
2091 .collect(),
2092 );
2093 }
2094 for (alias, (key, decl)) in &callee_keys {
2102 if let Some(owner) = owners.get(alias).cloned() {
2103 owners.entry(key.clone()).or_insert(owner);
2104 }
2105 other_types_combined
2106 .entry(key.clone())
2107 .or_insert_with(|| decl.clone());
2108 }
2109 let key_of: HashMap<String, String> = callee_keys
2110 .iter()
2111 .map(|(alias, (key, _))| (alias.clone(), key.clone()))
2112 .collect();
2113 if !key_of.is_empty() {
2114 callee_alias_keys_out.insert(
2115 t.clone(),
2116 key_of
2117 .iter()
2118 .map(|(alias, key)| (key.clone(), alias.clone()))
2119 .collect(),
2120 );
2121 }
2122 consumed_types.insert(t.clone(), other_types_combined);
2123 if !owners.is_empty() {
2124 consumed_type_owners.insert(t.clone(), owners);
2125 }
2126 let Some(other_table) = unit_tables.get(t) else {
2127 continue;
2128 };
2129 consumed_event_names.insert(t.clone(), other_table.events.keys().cloned().collect());
2130 let mut svcs: HashMap<String, resolver::CrossContextService> = HashMap::new();
2131 for (sname, sdecl) in &other_table.services {
2132 if let Some(mut svc) = resolver::cross_context_service_for(sname, sdecl) {
2133 for (_, tr) in svc.params.iter_mut() {
2134 rename_type_ref(tr, &renames);
2135 }
2136 rename_type_ref(&mut svc.return_type, &renames);
2137 for (_, tr) in svc.params.iter_mut() {
2138 rename_type_ref(tr, &key_of);
2139 }
2140 rename_type_ref(&mut svc.return_type, &key_of);
2141 svc.foreign_callers = sdecl
2142 .handlers
2143 .iter()
2144 .find_map(|h| crate::actors::call_admission_for(h, &other_table.actors))
2145 .map(|a| a.foreign.into_iter().map(|f| f.actor).collect())
2146 .unwrap_or_default();
2147 svcs.insert(sname.clone(), svc);
2148 }
2149 }
2150 consumed_services.insert(t.clone(), svcs);
2151
2152 let mut caps: HashMap<String, resolver::CrossContextCapability> = HashMap::new();
2155 for cap_name in &other_table.exported_capabilities {
2156 let Some(decl) = other_table.capabilities.get(cap_name) else {
2157 continue;
2158 };
2159 let Some(provider) = other_table.providers.get(cap_name) else {
2160 continue;
2161 };
2162 let ops = decl
2163 .ops
2164 .iter()
2165 .map(|op| resolver::CrossContextCapabilityOp {
2166 name: op.name.name.clone(),
2167 type_params: op.type_params.iter().map(|p| p.name.name.clone()).collect(),
2168 params: op
2169 .params
2170 .iter()
2171 .map(|p| {
2172 let mut tr = p.type_ref.clone();
2173 rename_type_ref(&mut tr, &renames);
2174 rename_type_ref(&mut tr, &key_of);
2175 (p.name.name.clone(), tr)
2176 })
2177 .collect(),
2178 return_type: {
2179 let mut tr = op.return_type.clone();
2180 rename_type_ref(&mut tr, &renames);
2181 rename_type_ref(&mut tr, &key_of);
2182 tr
2183 },
2184 codable_params: crate::checker::codable::codable_op_params(op),
2185 reply_policy: crate::checker::codable::op_reply_policy(op),
2186 })
2187 .collect();
2188 caps.insert(
2189 cap_name.clone(),
2190 resolver::CrossContextCapability {
2191 name: cap_name.clone(),
2192 ops,
2193 provider_name: provider.provider_name.name.clone(),
2194 provider_given: provider
2195 .given
2196 .iter()
2197 .filter(|c| !c.is_cross_context())
2198 .map(|c| c.key().to_string())
2199 .collect(),
2200 span: decl.span,
2201 },
2202 );
2203 }
2204 consumed_capabilities.insert(t.clone(), caps);
2205 }
2206 resolver::CrossContextInfo {
2207 self_context: Some(name.to_string()),
2208 consumed_contexts,
2209 aliases,
2210 consumed_services,
2211 consumed_types,
2212 consumed_type_renames: HashMap::new(),
2214 consumed_capabilities,
2215 flattened_caps: unit_tables
2217 .get(name)
2218 .map(|t| t.flattened_caps.clone())
2219 .unwrap_or_default(),
2220 consumed_event_names,
2221 consumed_type_owners,
2222 consumed_type_aliases,
2223 callee_type_aliases,
2224 callee_alias_keys: callee_alias_keys_out,
2225 cookie_records: unit_tables
2226 .get(name)
2227 .map(crate::context_checks::cookie_records_of)
2228 .unwrap_or_default(),
2229 signed_cookie_names: unit_tables
2230 .get(name)
2231 .map(|t| {
2232 t.actors
2233 .values()
2234 .filter_map(|a| crate::actors::signed_cookie_seam_of(a, None))
2235 .map(|seam| seam.cookie)
2236 .collect()
2237 })
2238 .unwrap_or_default(),
2239 }
2240}
2241
2242fn callee_alias_keys(
2252 t: &str,
2253 unit_tables: &HashMap<String, UnitTable>,
2254 view: &HashMap<String, Arc<TypeDecl>>,
2255) -> HashMap<String, (String, Arc<TypeDecl>)> {
2256 let Some(table) = unit_tables.get(t) else {
2257 return HashMap::new();
2258 };
2259 let mut out = HashMap::new();
2260 for (alias, a) in &table.consumed_type_aliases {
2261 let Some(decl) = view.get(alias) else {
2262 continue;
2263 };
2264 let same = |d: &Arc<TypeDecl>| Arc::ptr_eq(d, decl) || d.span == decl.span;
2265 let (key, decl) = if view.get(&a.original).is_some_and(same) {
2266 (a.original.clone(), decl.clone())
2267 } else {
2268 let key = format!("{}__{}", a.target.replace('.', "_"), a.original);
2269 let mut renamed = (**decl).clone();
2270 renamed.name.name = key.clone();
2271 (key, Arc::new(renamed))
2272 };
2273 out.insert(alias.clone(), (key, decl));
2274 }
2275 out
2276}
2277
2278pub fn discover_event_subscribers(
2291 unit_tables: &HashMap<String, UnitTable>,
2292 unit_consumes: &HashMap<String, Vec<String>>,
2293) -> BTreeMap<(String, String), Vec<(String, String)>> {
2294 let mut out: BTreeMap<(String, String), Vec<(String, String)>> = BTreeMap::new();
2295 for (ctx_name, table) in unit_tables {
2296 for (svc_name, svc) in &table.services {
2297 let ServiceProtocol::Events { event_type, .. } = &svc.protocol else {
2298 continue;
2299 };
2300 let TypeRef::Named(id) = event_type else {
2301 continue;
2302 };
2303 let name = &id.name;
2304 let owner = if table.events.contains_key(name) {
2305 Some(ctx_name.clone())
2306 } else {
2307 unit_consumes.get(ctx_name).and_then(|consumed| {
2308 consumed
2309 .iter()
2310 .find(|c| {
2311 unit_tables
2312 .get(c.as_str())
2313 .is_some_and(|t| t.events.contains_key(name))
2314 })
2315 .cloned()
2316 })
2317 };
2318 if let Some(owner) = owner {
2319 out.entry((owner, name.clone()))
2320 .or_default()
2321 .push((ctx_name.clone(), svc_name.clone()));
2322 }
2323 }
2324 }
2325 for subs in out.values_mut() {
2330 subs.sort();
2331 }
2332 out
2333}
2334
2335pub fn cron_and_queue_triggers(table: &UnitTable) -> (Vec<String>, Vec<String>) {
2340 let mut crons: Vec<String> = Vec::new();
2341 let mut queues: Vec<String> = Vec::new();
2342 for service in table.services.values() {
2343 for handler in &service.handlers {
2344 if let HandlerKind::Cron { expr } = &handler.kind {
2345 crons.push(expr.clone());
2346 }
2347 }
2348 if let ServiceProtocol::Queue { name } = &service.protocol {
2349 queues.push(name.clone());
2350 }
2351 }
2352 crons.sort();
2353 crons.dedup();
2354 queues.sort();
2355 queues.dedup();
2356 (crons, queues)
2357}
2358
2359pub fn record_capability_clause_ref(
2369 name: &Ident,
2370 cross_context: &resolver::CrossContextInfo,
2371 refs: &mut RefSink,
2372) {
2373 record_capability_clause_ref_inner(name, cross_context, refs, false);
2374}
2375
2376pub fn record_provides_clause_ref(
2381 name: &Ident,
2382 cross_context: &resolver::CrossContextInfo,
2383 refs: &mut RefSink,
2384) {
2385 record_capability_clause_ref_inner(name, cross_context, refs, true);
2386}
2387
2388fn record_capability_clause_ref_inner(
2389 name: &Ident,
2390 cross_context: &resolver::CrossContextInfo,
2391 refs: &mut RefSink,
2392 provides: bool,
2393) {
2394 let unit = cross_context.flattened_caps.get(&name.name);
2395 if provides {
2396 refs.record_provides(name.span, &name.name, unit.map(String::as_str));
2397 } else if let Some(unit) = unit {
2398 refs.record_in_unit(name.span, SymbolKind::Capability, &name.name, unit);
2399 } else {
2400 refs.record(name.span, SymbolKind::Capability, &name.name);
2401 }
2402}
2403
2404pub fn resolve_given_cap_ref(
2405 cap_ref: &CapRef,
2406 capability_info_map: &HashMap<String, CapabilityInfo>,
2407 cross_context: &resolver::CrossContextInfo,
2408 errors: &mut Vec<CompileError>,
2409 refs: &mut RefSink,
2410) -> Option<CapabilityInfo> {
2411 let Some(prefix) = cap_ref.prefix() else {
2412 match capability_info_map.get(cap_ref.key()) {
2414 Some(info) => {
2415 record_capability_clause_ref(&cap_ref.name, cross_context, refs);
2416 if let Some(unit) = cross_context.flattened_caps.get(cap_ref.key())
2421 && let Some(kind) = crate::firstparty::instantiable(unit, cap_ref.key())
2422 && !kind.bare
2423 {
2424 let example = crate::project_model::instance_example(kind);
2425 errors.push(
2426 CompileError::new(
2427 "bynk.capability.instance_only",
2428 cap_ref.span,
2429 format!(
2430 "`{unit}.{}` is used only through a named instance",
2431 cap_ref.key()
2432 ),
2433 )
2434 .with_note(format!("declare one and use it instead: `{example}`")),
2435 );
2436 }
2437 return Some(info.clone());
2438 }
2439 None => {
2440 errors.push(CompileError::new(
2441 "bynk.given.unknown_capability",
2442 cap_ref.span,
2443 format!(
2444 "capability `{}` is not declared in this context",
2445 cap_ref.key()
2446 ),
2447 ));
2448 return None;
2449 }
2450 }
2451 };
2452 let Some(ctx_name) = cross_context.resolve_prefix(&prefix) else {
2454 errors.push(
2455 CompileError::new(
2456 "bynk.resolve.unconsumed_context",
2457 cap_ref.span,
2458 format!(
2459 "`given {}.{}` refers to a context that this context does not `consumes`",
2460 prefix,
2461 cap_ref.key()
2462 ),
2463 )
2464 .with_note(
2465 "add a `consumes` clause for the providing context (optionally with an alias) at the top of this context",
2466 ),
2467 );
2468 return None;
2469 };
2470 let exports_it = cross_context
2471 .consumed_capabilities
2472 .get(&ctx_name)
2473 .is_some_and(|m| m.contains_key(cap_ref.key()));
2474 if exports_it {
2475 refs.record_in_unit(
2478 cap_ref.name.span,
2479 SymbolKind::Capability,
2480 cap_ref.key(),
2481 &ctx_name,
2482 );
2483 }
2484 if !exports_it {
2485 errors.push(
2486 CompileError::new(
2487 "bynk.given.cross_context_unknown_capability",
2488 cap_ref.span,
2489 format!(
2490 "context `{}` does not export a capability named `{}`",
2491 ctx_name,
2492 cap_ref.key()
2493 ),
2494 )
2495 .with_note(
2496 "the providing context must list the capability in an `exports capability { … }` clause",
2497 ),
2498 );
2499 }
2500 None
2501}
2502
2503pub fn contract_types_for(
2536 unit: &str,
2537 unit_tables: &HashMap<String, UnitTable>,
2538 unit_uses: &HashMap<String, Vec<String>>,
2539 unit_consumes: &HashMap<String, Vec<String>>,
2540) -> (HashMap<String, Arc<TypeDecl>>, HashMap<String, String>) {
2541 let mut walk = ContractWalk::default();
2542 let (table, owners, _) =
2543 contract_types_inner(unit, unit_tables, unit_uses, unit_consumes, &mut walk);
2544 (table, owners)
2545}
2546
2547pub fn display_type_name(name: &str) -> &str {
2555 match name.rsplit_once("__") {
2556 Some((prefix, last))
2557 if prefix.starts_with(|c: char| c.is_ascii_lowercase())
2558 && prefix
2559 .chars()
2560 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
2561 && last.starts_with(|c: char| c.is_ascii_uppercase()) =>
2562 {
2563 last
2564 }
2565 _ => name,
2566 }
2567}
2568
2569pub fn display_type_names_in(text: &str) -> String {
2572 let mut out = String::with_capacity(text.len());
2573 let mut word = String::new();
2574 let flush = |word: &mut String, out: &mut String| {
2575 out.push_str(display_type_name(word));
2576 word.clear();
2577 };
2578 for c in text.chars() {
2579 if c.is_ascii_alphanumeric() || c == '_' {
2580 word.push(c);
2581 } else {
2582 flush(&mut word, &mut out);
2583 out.push(c);
2584 }
2585 }
2586 flush(&mut word, &mut out);
2587 out
2588}
2589
2590type ContractView = (HashMap<String, Arc<TypeDecl>>, HashMap<String, String>);
2592
2593#[derive(Default)]
2598struct ContractWalk {
2599 visiting: std::collections::HashSet<String>,
2600 memo: HashMap<String, ContractView>,
2601}
2602
2603fn contract_types_inner(
2605 unit: &str,
2606 unit_tables: &HashMap<String, UnitTable>,
2607 unit_uses: &HashMap<String, Vec<String>>,
2608 unit_consumes: &HashMap<String, Vec<String>>,
2609 walk: &mut ContractWalk,
2610) -> (
2611 HashMap<String, Arc<TypeDecl>>,
2612 HashMap<String, String>,
2613 bool,
2614) {
2615 if let Some((table, owners)) = walk.memo.get(unit) {
2616 return (table.clone(), owners.clone(), false);
2617 }
2618 let mut out = combined_types_for(unit, unit_tables, unit_uses);
2619 let mut owners: HashMap<String, String> = HashMap::new();
2620 if !walk.visiting.insert(unit.to_string()) {
2621 return (out, owners, true);
2623 }
2624 let mut consumed: Vec<&String> = unit_consumes
2625 .get(unit)
2626 .into_iter()
2627 .flatten()
2628 .filter(|u| {
2629 unit_tables
2630 .get(*u)
2631 .is_some_and(|t| t.kind == Some(UnitKind::Context))
2632 })
2633 .collect();
2634 consumed.sort();
2635 consumed.dedup();
2636 let mut cyclic = false;
2638 let views: HashMap<String, ContractView> = consumed
2639 .iter()
2640 .map(|u| {
2641 let (table, owners, met) =
2642 contract_types_inner(u, unit_tables, unit_uses, unit_consumes, walk);
2643 cyclic |= met;
2644 ((*u).clone(), (table, owners))
2645 })
2646 .collect();
2647 let declarer = |owner: &str, r: &str, target: &Arc<TypeDecl>| -> Option<String> {
2651 if unit_tables
2652 .get(owner)
2653 .and_then(|t| t.types.get(r))
2654 .is_some_and(|d| Arc::ptr_eq(d, target) || d.span == target.span)
2655 {
2656 return Some(owner.to_string());
2657 }
2658 views.get(owner).and_then(|(_, o)| o.get(r).cloned())
2659 };
2660 let mut by_name: std::collections::BTreeMap<&String, Vec<&String>> = Default::default();
2661 for u in &consumed {
2662 for n in unit_tables[*u].types.keys() {
2663 if !out.contains_key(n) {
2664 by_name.entry(n).or_default().push(u);
2665 }
2666 }
2667 }
2668 let mut queue: Vec<(String, String)> = Vec::new();
2669 for (n, us) in by_name {
2670 if let [u] = us.as_slice() {
2671 out.insert(n.clone(), unit_tables[*u].types[n].clone());
2672 owners.insert(n.clone(), (*u).clone());
2673 queue.push((n.clone(), (*u).clone()));
2674 }
2675 }
2676 if let Some(table) = unit_tables.get(unit) {
2681 for (alias, a) in &table.consumed_type_aliases {
2682 let Some((view, view_owners)) = views.get(&a.target) else {
2683 continue;
2684 };
2685 let Some(decl) = view.get(&a.original) else {
2686 continue;
2687 };
2688 let renames: HashMap<String, String> = table
2689 .consumed_type_aliases
2690 .iter()
2691 .filter(|(_, o)| o.target == a.target)
2692 .map(|(alias, o)| (o.original.clone(), alias.clone()))
2693 .collect();
2694 out.insert(alias.clone(), rename_consumed_decl(decl, alias, &renames));
2695 owners.insert(
2696 alias.clone(),
2697 view_owners
2698 .get(&a.original)
2699 .cloned()
2700 .unwrap_or_else(|| a.target.clone()),
2701 );
2702 queue.push((alias.clone(), a.target.clone()));
2703 }
2704 }
2705 queue.sort();
2706 let same = |a: &Arc<TypeDecl>, b: &Arc<TypeDecl>| Arc::ptr_eq(a, b) || a.span == b.span;
2707 while let Some((key, via)) = queue.pop() {
2711 let owner = via;
2712 let Some((view, _)) = views.get(&owner) else {
2713 continue;
2714 };
2715 let decl = out[&key].clone();
2716 let mut subst: HashMap<String, String> = HashMap::new();
2717 for r in crate::project_model::type_decl_ref_names(&decl) {
2718 let Some(target) = view.get(&r) else {
2719 continue;
2720 };
2721 match out.get(&r) {
2722 Some(here) if same(here, target) => {}
2723 None => {
2724 out.insert(r.clone(), target.clone());
2725 if let Some(d) = declarer(&owner, &r, target) {
2726 owners.insert(r.clone(), d);
2727 }
2728 queue.push((r, owner.clone()));
2729 }
2730 Some(_) => {
2731 let d = declarer(&owner, &r, target);
2732 let qualified = format!(
2733 "{}__{r}",
2734 d.as_deref().unwrap_or(owner.as_str()).replace('.', "_")
2735 );
2736 if !out.contains_key(&qualified) {
2737 let mut renamed = (**target).clone();
2742 renamed.name.name = qualified.clone();
2743 out.insert(qualified.clone(), Arc::new(renamed));
2744 if let Some(d) = d {
2745 owners.insert(qualified.clone(), d);
2746 }
2747 queue.push((qualified.clone(), owner.clone()));
2748 }
2749 subst.insert(r, qualified);
2750 }
2751 }
2752 }
2753 if !subst.is_empty() {
2754 out.insert(key, Arc::new(rename_decl_refs(&decl, &subst)));
2755 }
2756 }
2757 walk.visiting.remove(unit);
2758 if !cyclic {
2759 walk.memo
2760 .insert(unit.to_string(), (out.clone(), owners.clone()));
2761 }
2762 (out, owners, cyclic)
2763}
2764
2765pub fn rename_consumed_decl(
2769 decl: &Arc<TypeDecl>,
2770 key: &str,
2771 renames: &HashMap<String, String>,
2772) -> Arc<TypeDecl> {
2773 if renames.is_empty() {
2774 return decl.clone();
2775 }
2776 let mut out = rename_decl_refs(decl, renames);
2777 out.name.name = key.to_string();
2778 Arc::new(out)
2779}
2780
2781fn rename_decl_refs(decl: &TypeDecl, subst: &HashMap<String, String>) -> TypeDecl {
2784 let mut out = decl.clone();
2785 match &mut out.body {
2786 TypeBody::Record(r) => {
2787 for f in &mut r.fields {
2788 rename_type_ref(&mut f.type_ref, subst);
2789 }
2790 }
2791 TypeBody::Sum(sum) => {
2792 for v in &mut sum.variants {
2793 for f in &mut v.payload {
2794 rename_type_ref(&mut f.type_ref, subst);
2795 }
2796 }
2797 }
2798 TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {}
2799 }
2800 out
2801}
2802
2803pub fn rename_type_ref(r: &mut TypeRef, subst: &HashMap<String, String>) {
2806 match r {
2807 TypeRef::Named(id) => {
2808 if let Some(to) = subst.get(&id.name) {
2809 id.name = to.clone();
2810 }
2811 }
2812 TypeRef::App { name, args, .. } => {
2813 if let Some(to) = subst.get(&name.name) {
2814 name.name = to.clone();
2815 }
2816 for a in args {
2817 rename_type_ref(a, subst);
2818 }
2819 }
2820 TypeRef::Result(a, b, _) | TypeRef::Map(a, b, _) => {
2821 rename_type_ref(a, subst);
2822 rename_type_ref(b, subst);
2823 }
2824 TypeRef::Option(t, _)
2825 | TypeRef::Effect(t, _)
2826 | TypeRef::HttpResult(t, _)
2827 | TypeRef::List(t, _)
2828 | TypeRef::Set(t, _)
2829 | TypeRef::Query(t, _)
2830 | TypeRef::Stream(t, _)
2831 | TypeRef::Connection(t, _)
2832 | TypeRef::History(t, _) => rename_type_ref(t, subst),
2833 TypeRef::Fn(params, ret, _) => {
2834 for p in params {
2835 rename_type_ref(p, subst);
2836 }
2837 rename_type_ref(ret, subst);
2838 }
2839 TypeRef::Base(..)
2840 | TypeRef::QueueResult(_)
2841 | TypeRef::Asset(_)
2842 | TypeRef::RequestHeaders(_)
2843 | TypeRef::RequestQuery(_)
2844 | TypeRef::RequestCookies(_)
2845 | TypeRef::TokenClaims(_)
2846 | TypeRef::BoundaryRejection(_)
2847 | TypeRef::ValidationError(_)
2848 | TypeRef::DecodeError(_)
2849 | TypeRef::Unit(_) => {}
2850 }
2851}
2852
2853pub fn combined_types_for(
2854 unit: &str,
2855 unit_tables: &HashMap<String, UnitTable>,
2856 unit_uses: &HashMap<String, Vec<String>>,
2857) -> HashMap<String, Arc<TypeDecl>> {
2858 let mut out: HashMap<String, Arc<TypeDecl>> = HashMap::new();
2859 if let Some(table) = unit_tables.get(unit) {
2860 for (n, d) in &table.types {
2861 out.insert(n.clone(), d.clone());
2862 }
2863 }
2864 if let Some(targets) = unit_uses.get(unit) {
2865 for t in targets {
2866 if let Some(used) = unit_tables.get(t) {
2867 for (n, d) in &used.types {
2868 out.entry(n.clone()).or_insert_with(|| d.clone());
2869 }
2870 }
2871 }
2872 }
2873 out
2874}
2875
2876pub fn combined_types_for_unit_info(
2887 unit: &str,
2888 unit_info: &BTreeMap<String, UnitInfo>,
2889) -> HashMap<String, Arc<TypeDecl>> {
2890 let mut out: HashMap<String, Arc<TypeDecl>> = HashMap::new();
2891 let Some(info) = unit_info.get(unit) else {
2892 return out;
2893 };
2894 for (n, d) in &info.table.types {
2895 out.insert(n.clone(), d.clone());
2896 }
2897 for t in &info.uses {
2898 if let Some(used) = unit_info.get(t) {
2899 for (n, d) in &used.table.types {
2900 out.entry(n.clone()).or_insert_with(|| d.clone());
2901 }
2902 }
2903 }
2904 out
2905}
2906
2907pub enum ContextMessageBundle {
2920 None,
2922 One(MessageBundleInfo),
2924 Many(Vec<String>),
2926}
2927
2928pub struct MessageBundleInfo {
2929 pub commons: String,
2931 pub source_path: PathBuf,
2939}
2940
2941pub fn detect_context_message_bundle(
2947 ctx: &str,
2948 unit_uses: &HashMap<String, Vec<String>>,
2949 groups: &BTreeMap<String, Vec<usize>>,
2950 kinds: &BTreeMap<String, UnitKind>,
2951 parsed: &[ParsedFile],
2952) -> ContextMessageBundle {
2953 let mut found: Vec<MessageBundleInfo> = Vec::new();
2954 for target in unit_uses.get(ctx).into_iter().flatten() {
2955 if kinds.get(target) != Some(&UnitKind::Commons) {
2956 continue;
2957 }
2958 let Some(indices) = groups.get(target) else {
2959 continue;
2960 };
2961 for &i in indices {
2962 let has_reference = parsed[i].items().iter().any(|item| {
2963 matches!(item, CommonsItem::Messages(m) if m.private.is_none() && m.annotations.iter().any(|a| a.name.name == "reference"))
2965 });
2966 if has_reference {
2967 found.push(MessageBundleInfo {
2968 commons: target.clone(),
2969 source_path: parsed[i].source_path(),
2970 });
2971 break;
2972 }
2973 }
2974 }
2975 match found.len() {
2976 0 => ContextMessageBundle::None,
2977 1 => ContextMessageBundle::One(found.pop().expect("len == 1")),
2978 _ => ContextMessageBundle::Many(found.into_iter().map(|b| b.commons).collect()),
2979 }
2980}
2981
2982#[cfg(test)]
2983mod detect_context_message_bundle_tests {
2984 use super::*;
2985 use bynk_syntax::ast::{
2986 Annotation, Commons, CommonsForm, Context, MessagesDecl, QualifiedName, SourceUnit,
2987 UsesDecl,
2988 };
2989
2990 fn ident(name: &str) -> Ident {
2991 Ident {
2992 name: name.to_string(),
2993 span: Span::default(),
2994 }
2995 }
2996
2997 fn qualified(name: &str) -> QualifiedName {
2998 QualifiedName {
2999 parts: name.split('.').map(ident).collect(),
3000 span: Span::default(),
3001 }
3002 }
3003
3004 fn commons_with_messages(name: &str, tag: &str, is_reference: bool) -> ParsedFile {
3009 let annotations = if is_reference {
3010 vec![Annotation {
3011 name: ident("reference"),
3012 args: Vec::new(),
3013 span: Span::default(),
3014 }]
3015 } else {
3016 Vec::new()
3017 };
3018 let messages = MessagesDecl {
3019 tag: tag.to_string(),
3020 tag_span: Span::default(),
3021 annotations,
3022 entries: Vec::new(),
3023 documentation: None,
3024 span: Span::default(),
3025 trivia: Trivia::default(),
3026 private: None,
3027 };
3028 ParsedFile::new(
3029 PathBuf::from(format!("{}.bynk", name.replace('.', "/"))),
3030 PathBuf::from(format!("src/{}.bynk", name.replace('.', "/"))),
3031 None,
3032 String::new(),
3033 SourceUnit::Commons(Commons {
3034 name: qualified(name),
3035 items: vec![CommonsItem::Messages(messages)],
3036 uses: Vec::new(),
3037 documentation: None,
3038 form: CommonsForm::Brace,
3039 span: Span::default(),
3040 trivia: Trivia::default(),
3041 trailing_comments: Vec::new(),
3042 }),
3043 UnitKind::Commons,
3044 false,
3045 )
3046 }
3047
3048 fn context_using(name: &str, targets: &[&str]) -> ParsedFile {
3051 ParsedFile::new(
3052 PathBuf::from(format!("{}.bynk", name.replace('.', "/"))),
3053 PathBuf::from(format!("src/{}.bynk", name.replace('.', "/"))),
3054 None,
3055 String::new(),
3056 SourceUnit::Context(Context {
3057 removed_agents: Vec::new(),
3058 name: qualified(name),
3059 uses: targets
3060 .iter()
3061 .map(|t| UsesDecl {
3062 target: qualified(t),
3063 span: Span::default(),
3064 trivia: Trivia::default(),
3065 blank_before: false,
3066 })
3067 .collect(),
3068 consumes: Vec::new(),
3069 exports: Vec::new(),
3070 items: Vec::new(),
3071 documentation: None,
3072 form: CommonsForm::Brace,
3073 span: Span::default(),
3074 trivia: Trivia::default(),
3075 trailing_comments: Vec::new(),
3076 }),
3077 UnitKind::Context,
3078 false,
3079 )
3080 }
3081
3082 struct Scenario {
3086 parsed: Vec<ParsedFile>,
3087 groups: BTreeMap<String, Vec<usize>>,
3088 kinds: BTreeMap<String, UnitKind>,
3089 unit_uses: HashMap<String, Vec<String>>,
3090 }
3091
3092 fn scenario(ctx_name: &str, ctx_uses: &[&str], bundles: Vec<(&str, ParsedFile)>) -> Scenario {
3094 let mut parsed = vec![context_using(ctx_name, ctx_uses)];
3095 let mut groups: BTreeMap<String, Vec<usize>> = BTreeMap::new();
3096 let mut kinds: BTreeMap<String, UnitKind> = BTreeMap::new();
3097 groups.insert(ctx_name.to_string(), vec![0]);
3098 kinds.insert(ctx_name.to_string(), UnitKind::Context);
3099 for (name, pf) in bundles {
3100 let idx = parsed.len();
3101 parsed.push(pf);
3102 groups.entry(name.to_string()).or_default().push(idx);
3103 kinds.insert(name.to_string(), UnitKind::Commons);
3104 }
3105 let mut unit_uses: HashMap<String, Vec<String>> = HashMap::new();
3106 unit_uses.insert(
3107 ctx_name.to_string(),
3108 ctx_uses.iter().map(|s| s.to_string()).collect(),
3109 );
3110 Scenario {
3111 parsed,
3112 groups,
3113 kinds,
3114 unit_uses,
3115 }
3116 }
3117
3118 #[test]
3119 fn zero_bundles_when_uses_reaches_no_messages_commons() {
3120 let Scenario {
3121 parsed,
3122 groups,
3123 kinds,
3124 unit_uses,
3125 } = scenario("app.web", &["app.other"], vec![]);
3126 assert!(matches!(
3127 detect_context_message_bundle("app.web", &unit_uses, &groups, &kinds, &parsed),
3128 ContextMessageBundle::None
3129 ));
3130 }
3131
3132 #[test]
3133 fn zero_bundles_when_uses_is_empty() {
3134 let Scenario {
3135 parsed,
3136 groups,
3137 kinds,
3138 unit_uses,
3139 } = scenario("app.web", &[], vec![]);
3140 assert!(matches!(
3141 detect_context_message_bundle("app.web", &unit_uses, &groups, &kinds, &parsed),
3142 ContextMessageBundle::None
3143 ));
3144 }
3145
3146 #[test]
3147 fn one_bundle_is_found_by_its_reference_block() {
3148 let bundle = commons_with_messages("app.msgs", "en", true);
3149 let Scenario {
3150 parsed,
3151 groups,
3152 kinds,
3153 unit_uses,
3154 } = scenario("app.web", &["app.msgs"], vec![("app.msgs", bundle)]);
3155 let found = detect_context_message_bundle("app.web", &unit_uses, &groups, &kinds, &parsed);
3156 let ContextMessageBundle::One(info) = found else {
3157 panic!("expected exactly one bundle");
3158 };
3159 assert_eq!(info.commons, "app.msgs");
3160 assert_eq!(info.source_path, PathBuf::from("app/msgs.bynk"));
3161 }
3162
3163 #[test]
3164 fn a_bundle_missing_its_reference_block_is_not_counted() {
3165 let bundle = commons_with_messages("app.msgs", "en", false);
3169 let Scenario {
3170 parsed,
3171 groups,
3172 kinds,
3173 unit_uses,
3174 } = scenario("app.web", &["app.msgs"], vec![("app.msgs", bundle)]);
3175 assert!(matches!(
3176 detect_context_message_bundle("app.web", &unit_uses, &groups, &kinds, &parsed),
3177 ContextMessageBundle::None
3178 ));
3179 }
3180
3181 #[test]
3182 fn two_bundles_report_both_commons_names() {
3183 let a = commons_with_messages("app.msgs_a", "en", true);
3184 let b = commons_with_messages("app.msgs_b", "en", true);
3185 let Scenario {
3186 parsed,
3187 groups,
3188 kinds,
3189 unit_uses,
3190 } = scenario(
3191 "app.web",
3192 &["app.msgs_a", "app.msgs_b"],
3193 vec![("app.msgs_a", a), ("app.msgs_b", b)],
3194 );
3195 let found = detect_context_message_bundle("app.web", &unit_uses, &groups, &kinds, &parsed);
3196 let ContextMessageBundle::Many(names) = found else {
3197 panic!("expected two bundles");
3198 };
3199 let mut names = names;
3200 names.sort();
3201 assert_eq!(
3202 names,
3203 vec!["app.msgs_a".to_string(), "app.msgs_b".to_string()]
3204 );
3205 }
3206
3207 #[test]
3208 fn a_commons_reached_only_transitively_is_not_counted() {
3209 let bundle = commons_with_messages("app.msgs", "en", true);
3213 let mut mid = context_using("app.mid", &["app.msgs"]);
3214 mid.set_kind(UnitKind::Commons);
3220 let Scenario {
3221 mut parsed,
3222 mut groups,
3223 mut kinds,
3224 unit_uses,
3225 } = scenario("app.web", &["app.mid"], vec![("app.msgs", bundle)]);
3226 let mid_idx = parsed.len();
3227 parsed.push(mid);
3228 groups.insert("app.mid".to_string(), vec![mid_idx]);
3229 kinds.insert("app.mid".to_string(), UnitKind::Commons);
3230 assert!(matches!(
3231 detect_context_message_bundle("app.web", &unit_uses, &groups, &kinds, &parsed),
3232 ContextMessageBundle::None
3233 ));
3234 }
3235}
3236
3237pub fn consumes_span_of(
3240 parsed: &[ParsedFile],
3241 indices: &[usize],
3242 target: &str,
3243) -> Option<(usize, Span)> {
3244 for &i in indices {
3245 for c in parsed[i].consumes() {
3246 if c.target.joined() == target {
3247 return Some((i, c.span));
3248 }
3249 }
3250 }
3251 None
3252}
3253
3254pub fn parsed_alias_span(
3257 parsed: &[ParsedFile],
3258 indices: &[usize],
3259 alias: &str,
3260) -> Option<(usize, Span)> {
3261 for &i in indices {
3262 for c in parsed[i].consumes() {
3263 if let Some(a) = &c.alias
3264 && a.name == alias
3265 {
3266 return Some((i, a.span));
3267 }
3268 }
3269 }
3270 None
3271}
3272
3273#[derive(Debug, Clone)]
3276pub struct ConsumedType {
3277 pub owning_context: String,
3278 pub visibility: Visibility,
3279}
3280
3281#[cfg(test)]
3286mod value_namespace_tests {
3287 use super::*;
3288 use crate::testkit::analyse;
3289
3290 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
3291 enum Kind {
3292 Fn,
3293 Type,
3294 Event,
3295 Asset,
3296 Embed,
3297 Const,
3298 Service,
3299 Agent,
3300 Provider,
3301 Capability,
3302 Actor,
3303 }
3304
3305 const ALL: [Kind; 11] = [
3306 Kind::Fn,
3307 Kind::Type,
3308 Kind::Event,
3309 Kind::Asset,
3310 Kind::Embed,
3311 Kind::Const,
3312 Kind::Service,
3313 Kind::Agent,
3314 Kind::Provider,
3315 Kind::Capability,
3316 Kind::Actor,
3317 ];
3318
3319 fn kind_of(item: &CommonsItem) -> Option<Kind> {
3323 match item {
3324 CommonsItem::Fn(_) => Some(Kind::Fn),
3325 CommonsItem::Type(_) => Some(Kind::Type),
3326 CommonsItem::Event(_) => Some(Kind::Event),
3327 CommonsItem::Asset(_) => Some(Kind::Asset),
3328 CommonsItem::Embed(_) => Some(Kind::Embed),
3329 CommonsItem::Const(_) => Some(Kind::Const),
3330 CommonsItem::Service(_) => Some(Kind::Service),
3331 CommonsItem::Agent(_) => Some(Kind::Agent),
3332 CommonsItem::Provider(_) => Some(Kind::Provider),
3333 CommonsItem::Capability(_) => Some(Kind::Capability),
3334 CommonsItem::Actor(_) => Some(Kind::Actor),
3335 CommonsItem::Messages(_) => None,
3337 }
3338 }
3339
3340 fn shares_the_value_namespace(k: Kind) -> bool {
3341 !matches!(k, Kind::Capability | Kind::Actor)
3342 }
3343
3344 fn decl(kind: Kind, n: &str) -> String {
3347 match kind {
3348 Kind::Fn => format!("fn {n}() -> Int {{\n 1\n}}\n"),
3349 Kind::Type => format!("type {n} = {{ n: Int }}\n"),
3350 Kind::Event => format!("event {n} = {{ n: Int }}\n"),
3351 Kind::Asset => format!("asset {n} = \"assets/x.json\"\n"),
3352 Kind::Embed => format!("embed {n} = \"embeds/x.txt\"\n"),
3353 Kind::Const => format!("const {n}: Int = 1\n"),
3354 Kind::Service => {
3355 format!(
3356 "service {n} {{\n on call() -> Effect[Int] by Caller {{\n Effect.pure(1)\n }}\n}}\n"
3357 )
3358 }
3359 Kind::Agent => format!(
3360 "agent {n} {{\n key id: String\n\n store hits: Cell[Int]\n\n on call ping() -> Effect[Int] {{\n 1\n }}\n}}\n"
3361 ),
3362 Kind::Provider => format!(
3363 "capability ProbeCap {{\n fn go() -> Effect[Int]\n}}\n\nprovides ProbeCap = {n} {{\n fn go() -> Effect[Int] {{\n Effect.pure(1)\n }}\n}}\n"
3364 ),
3365 Kind::Capability => format!("capability {n} {{\n fn go() -> Effect[Int]\n}}\n"),
3366 Kind::Actor => {
3367 format!("actor {n} {{ auth = Bearer(secret = \"S\"), identity = ProbeId }}\n")
3368 }
3369 }
3370 }
3371
3372 const HEADER: &str = "context app\n\ntype ProbeId = opaque String\n\n";
3373
3374 #[test]
3375 fn each_snippet_declares_its_kind() {
3376 for k in ALL {
3377 let src = format!("{HEADER}{}", decl(k, "Thing"));
3378 let tokens = bynk_syntax::lexer::tokenize(&src).expect("lexes");
3379 let unit = bynk_syntax::parser::parse_unit(&tokens, &src).expect("parses");
3380 let bynk_syntax::ast::SourceUnit::Context(c) = unit else {
3381 panic!("a context")
3382 };
3383 assert!(
3384 c.items.iter().any(|i| kind_of(i) == Some(k)),
3385 "the {k:?} snippet declares no {k:?}"
3386 );
3387 }
3388 }
3389
3390 #[test]
3391 fn every_pair_of_kinds_against_the_value_namespace() {
3392 for (x, &a) in ALL.iter().enumerate() {
3393 for &b in &ALL[x + 1..] {
3394 for (first, second) in [(a, b), (b, a)] {
3396 for n in ["thing", "Thing"] {
3397 if n == "thing" && (a == Kind::Const || b == Kind::Const) {
3400 continue;
3401 }
3402 let src = format!("{HEADER}{}\n{}", decl(first, n), decl(second, n));
3403 let r = analyse(&[
3404 ("app/main.bynk", &src),
3405 ("assets/x.json", "{}"),
3406 ("embeds/x.txt", "x"),
3407 ]);
3408 let cats = r.error_categories();
3409 if shares_the_value_namespace(a) && shares_the_value_namespace(b) {
3410 let want = if matches!((a, b), (Kind::Type, Kind::Event)) {
3411 "bynk.resolve.duplicate_type"
3412 } else {
3413 "bynk.resolve.name_conflict"
3414 };
3415 assert_eq!(cats, vec![want], "{first:?} then {second:?} `{n}`");
3416 } else {
3417 assert!(
3418 cats.is_empty(),
3419 "{first:?} then {second:?} `{n}` should check clean: {cats:?}"
3420 );
3421 }
3422 }
3423 }
3424 }
3425 }
3426 }
3427
3428 #[test]
3431 fn a_split_context_is_one_namespace() {
3432 for (svc_file, asset_file) in [("a.bynk", "z.bynk"), ("z.bynk", "a.bynk")] {
3433 let svc = format!("context app\n\n{}", decl(Kind::Service, "api"));
3434 let asset = format!("context app\n\n{}", decl(Kind::Asset, "api"));
3435 let svc_path = format!("app/{svc_file}");
3436 let asset_path = format!("app/{asset_file}");
3437 let r = analyse(&[
3438 (svc_path.as_str(), svc.as_str()),
3439 (asset_path.as_str(), asset.as_str()),
3440 ("assets/x.json", "{}"),
3441 ]);
3442 assert_eq!(r.error_categories(), vec!["bynk.resolve.name_conflict"]);
3443 let d = &r.analysis.errors[0];
3444 assert!(
3445 d.source_path
3446 .as_deref()
3447 .is_some_and(|p| p.ends_with(svc_file)),
3448 "reported in the service's file: {:?}",
3449 d.source_path
3450 );
3451 }
3452 }
3453
3454 #[test]
3457 fn two_providers_under_one_name_conflict() {
3458 let src = "context app\n\ncapability A {\n fn go() -> Effect[Int]\n}\n\ncapability B {\n fn go() -> Effect[Int]\n}\n\nprovides A = Impl {\n fn go() -> Effect[Int] {\n Effect.pure(1)\n }\n}\n\nprovides B = Impl {\n fn go() -> Effect[Int] {\n Effect.pure(2)\n }\n}\n";
3459 let r = analyse(&[("app/main.bynk", src)]);
3460 assert_eq!(r.error_categories(), vec!["bynk.resolve.name_conflict"]);
3461 }
3462}
3463
3464#[cfg(test)]
3467mod contract_types_tests {
3468 use crate::testkit::analyse;
3469
3470 const ORDER: &str = "context shop.order\n\nexports transparent { Order }\n\ntype Region = enum { Domestic, International }\n\ntype Order = { id: String, region: Region }\n";
3471 const POST: &str = "context shop.post\n\nexports transparent { Parcel }\n\ntype Region = enum { North, South }\n\ntype Parcel = { ref: String, region: Region }\n";
3472 const LEDGER: &str = "context shop.ledger\n\nconsumes shop.order\nconsumes shop.post\n\ntype Region = enum { Here, There }\n\nservice orderId {\n on call(o: Order) -> Effect[String] by Caller {\n o.id\n }\n}\n\nservice parcelRef {\n on call(p: Parcel) -> Effect[String] by Caller {\n p.ref\n }\n}\n";
3473
3474 fn normal_form(service: &str) -> String {
3475 let a = analyse(&[
3476 ("shop/order.bynk", ORDER),
3477 ("shop/post.bynk", POST),
3478 ("shop/ledger.bynk", LEDGER),
3479 ]);
3480 a.assert_clean();
3481 let info = &a.analysis.boundary_info["shop.ledger"];
3482 let svc = crate::resolver::cross_context_service_for(service, &info.services[service])
3483 .expect("an `on call` service");
3484 crate::contract::service_normal_form(&svc, &info.types)
3485 }
3486
3487 #[test]
3491 fn a_qualified_key_displays_as_its_declarations_name() {
3492 use super::{display_type_name, display_type_names_in};
3493 assert_eq!(display_type_name("shop_order__Code"), "Code");
3494 assert_eq!(display_type_name("shop_ledger__shop_order__Code"), "Code");
3495 assert_eq!(display_type_name("Code"), "Code");
3496 assert_eq!(display_type_name("My__Thing"), "My__Thing");
3497 assert_eq!(display_type_name("shop_order__lower"), "shop_order__lower");
3498 assert_eq!(
3499 display_type_names_in("orderId(o: Order{code: shop_order__Code(String)})"),
3500 "orderId(o: Order{code: Code(String)})"
3501 );
3502 let tys = crate::checker::Types::default();
3503 let key = tys.intern(crate::checker::Ty::Named {
3504 name: "shop_order__Code".to_string(),
3505 kind: crate::checker::NamedKind::Opaque(bynk_syntax::ast::BaseType::String),
3506 args: Vec::new(),
3507 });
3508 assert_eq!(tys.display(key), "Code");
3509 let listed = tys.intern(crate::checker::Ty::List(key));
3510 assert_eq!(tys.display(listed), "List[Code]");
3511 }
3512
3513 #[test]
3514 fn a_borrowed_record_names_its_own_contexts_field_type() {
3515 let order = normal_form("orderId");
3516 assert!(
3517 order.contains("Domestic") && !order.contains("Here") && !order.contains("North"),
3518 "{order}"
3519 );
3520 let parcel = normal_form("parcelRef");
3521 assert!(
3522 parcel.contains("North") && !parcel.contains("Here") && !parcel.contains("Domestic"),
3523 "{parcel}"
3524 );
3525 }
3526}