Skip to main content

bynk_check/
firstparty.rs

1//! First-party standard adapters embedded in the toolchain (v0.17 ยง4.2).
2//!
3//! The sources, bindings and metadata live in the data-only `bynk-std` crate
4//! (standard-library track, #1940). This module re-exports them unchanged, so
5//! `bynk_check::firstparty::*` keeps resolving for every consumer. Parsing and
6//! injecting the sources is checker logic, and stays here in `project_model`.
7
8pub use bynk_std::*;
9
10/// Whether a unit is first-party: the `bynk` root namespace is reserved for the
11/// toolchain (`bynk.namespace.reserved`), so a unit under it is the standard
12/// library's own (#3458).
13pub fn is_first_party_unit(name: &bynk_syntax::ast::QualifiedName) -> bool {
14    name.parts.first().is_some_and(|p| p.name == "bynk")
15}
16
17/// A capability that is bynk's own: one the toolchain's `bynk` unit declares and a
18/// consumer flattens in with `consumes bynk { Cap }` (1A.33, Decision A).
19///
20/// The question "is this capability bynk's own `Idempotency` (or `Events`, `Clock`,
21/// `Locale`)?" has one definition, [`resolve`]. The checker records its answer on
22/// each capability call ([`crate::checker::Callee::Capability::first_party`]); the
23/// emitter asks `resolve` where it has a unit but no call (the unit-level
24/// decisions). A same-named capability from any other adapter or context is not
25/// first-party and resolves to `None` (#934).
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub enum FirstPartyCap {
28    /// `Idempotency`: `claim`, `dedup` and `remember`, whose keys the emitter scopes.
29    Idempotency,
30    /// `Events`: `emit`, buffered and flushed to the fan-out.
31    Events,
32    /// `Clock`: the harness clock substitutes for it in a `system` test build.
33    Clock,
34    /// `Locale`, provided by `LocaleProvider`, which receives the negotiation arguments.
35    Locale,
36}
37
38impl FirstPartyCap {
39    /// The capability's declared name in the `bynk` unit.
40    pub const fn name(self) -> &'static str {
41        match self {
42            FirstPartyCap::Idempotency => "Idempotency",
43            FirstPartyCap::Events => "Events",
44            FirstPartyCap::Clock => "Clock",
45            FirstPartyCap::Locale => "Locale",
46        }
47    }
48
49    /// The first-party capability named `name`, ignoring where it comes from.
50    fn from_name(name: &str) -> Option<FirstPartyCap> {
51        [
52            FirstPartyCap::Idempotency,
53            FirstPartyCap::Events,
54            FirstPartyCap::Clock,
55            FirstPartyCap::Locale,
56        ]
57        .into_iter()
58        .find(|c| c.name() == name)
59    }
60}
61
62/// Whether the capability `name`, as seen from the unit `declaring_unit` (the unit
63/// whose source the name appears in, or the provider's own unit), is bynk's own, and
64/// which one. `flattened_caps` is that unit's flattened-consume map (a bare
65/// `consumes bynk { Cap }` makes `Cap` a local name for the `bynk` unit's).
66///
67/// First-party when the name is one of [`FirstPartyCap`]'s and either this unit *is*
68/// `bynk` (the capability is declared right here) or `consumes bynk { name }`
69/// flattened it in. This is the single copy of the rule (#934): a same-named
70/// capability from another unit (the #926/#931 generic-operation fixtures' own
71/// illustrative `capability Idempotency`) must not be scoped.
72pub fn resolve(
73    name: &str,
74    declaring_unit: &str,
75    flattened_caps: &std::collections::HashMap<String, String>,
76) -> Option<FirstPartyCap> {
77    let cap = FirstPartyCap::from_name(name)?;
78    (declaring_unit == BYNK_UNIT || flattened_caps.get(name).map(String::as_str) == Some(BYNK_UNIT))
79        .then_some(cap)
80}
81
82/// Whether a parsed unit reaches `reach`: it is a context that declares a
83/// service of the protocol `reach` names, or an instance of the capability it
84/// names. Decided on the parsed declarations, so a comment or a string literal
85/// that spells the words reaches nothing.
86pub fn unit_reaches(unit: &bynk_syntax::ast::SourceUnit, reach: &Reach) -> bool {
87    use bynk_syntax::ast::{CommonsItem, ServiceProtocol, SourceUnit};
88    let SourceUnit::Context(ctx) = unit else {
89        return false;
90    };
91    ctx.items.iter().any(|item| match (item, reach) {
92        (CommonsItem::Service(s), Reach::ServiceProtocol(wanted)) => matches!(
93            (&s.protocol, *wanted),
94            (ServiceProtocol::Email { .. }, "email")
95        ),
96        (CommonsItem::Capability(d), Reach::CapabilityInstance(base)) => d
97            .derived
98            .as_ref()
99            .is_some_and(|derived| derived.base.name == *base),
100        _ => false,
101    })
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    fn parse(src: &str) -> bynk_syntax::ast::SourceUnit {
109        let tokens = bynk_syntax::lexer::tokenize(src).expect("lexes");
110        bynk_syntax::parser::parse_unit(&tokens, src).expect("parses")
111    }
112
113    fn flattened(entries: &[(&str, &str)]) -> std::collections::HashMap<String, String> {
114        entries
115            .iter()
116            .map(|(k, v)| (k.to_string(), v.to_string()))
117            .collect()
118    }
119
120    /// #934 / 1A.33 Decision A: a capability is first-party when this unit is `bynk`
121    /// or flattened it in from `bynk`, and a same-named one from anywhere else is not.
122    #[test]
123    fn resolve_is_first_party_only_for_bynks_own_capability() {
124        let none = flattened(&[]);
125        // Declared in the `bynk` unit itself: each first-party capability resolves.
126        assert_eq!(
127            resolve("Idempotency", "bynk", &none),
128            Some(FirstPartyCap::Idempotency)
129        );
130        assert_eq!(
131            resolve("Events", "bynk", &none),
132            Some(FirstPartyCap::Events)
133        );
134        assert_eq!(resolve("Clock", "bynk", &none), Some(FirstPartyCap::Clock));
135        assert_eq!(
136            resolve("Locale", "bynk", &none),
137            Some(FirstPartyCap::Locale)
138        );
139        // Flattened in with `consumes bynk { Idempotency }`.
140        let from_bynk = flattened(&[("Idempotency", "bynk"), ("Events", "bynk")]);
141        assert_eq!(
142            resolve("Idempotency", "shop.orders", &from_bynk),
143            Some(FirstPartyCap::Idempotency)
144        );
145        assert_eq!(
146            resolve("Events", "shop.orders", &from_bynk),
147            Some(FirstPartyCap::Events)
148        );
149        // Not flattened: unscoped.
150        assert_eq!(resolve("Idempotency", "shop.orders", &none), None);
151        // A same-named capability flattened from another unit: unscoped.
152        let other = flattened(&[("Idempotency", "vendor.keys"), ("Events", "vendor.bus")]);
153        assert_eq!(resolve("Idempotency", "shop.orders", &other), None);
154        assert_eq!(resolve("Events", "shop.orders", &other), None);
155        // Flattened from `bynk` under a different name: nothing to resolve.
156        assert_eq!(resolve("Cache", "bynk", &none), None);
157        assert_eq!(
158            resolve("Cache", "shop.orders", &flattened(&[("Cache", "bynk")])),
159            None
160        );
161    }
162
163    /// Hyperdrive H1 (#3318): a `Postgres` instance reaches `postgres`, decided
164    /// on the declaration; a comment or a string that spells it, another kind's
165    /// instance and a bare `given` reach nothing.
166    #[test]
167    fn a_postgres_instance_reaches_the_driver_and_nothing_else_does() {
168        let reach = Reach::CapabilityInstance("Postgres");
169        let declared = parse(
170            "context shop.orders\nconsumes bynk.cloudflare { Postgres }\ncapability Main = Postgres\n",
171        );
172        assert!(unit_reaches(&declared, &reach));
173        let mentioned = parse(
174            "context shop.orders\n// capability Main = Postgres\nconsumes bynk.cloudflare { Kv }\ncapability Cache = Kv\nfn label() -> String { \"capability Main = Postgres\" }\n",
175        );
176        assert!(!unit_reaches(&mentioned, &reach));
177        assert!(!unit_reaches(&declared, &Reach::ServiceProtocol("email")));
178        let pg = FIRST_PARTY_NPM
179            .iter()
180            .find(|d| d.package == "postgres")
181            .expect("postgres is a first-party dependency");
182        assert_eq!(pg.runtime_module, "postgres");
183        assert!(is_exact_version(pg.version));
184    }
185
186    /// Hyperdrive H5 (#3322): a `MySql` instance reaches `mysql2`, decided on
187    /// the declaration, and `Postgres` does not.
188    #[test]
189    fn a_mysql_instance_reaches_mysql2_and_a_postgres_one_does_not() {
190        let reach = Reach::CapabilityInstance("MySql");
191        let declared = parse(
192            "context shop.orders\nconsumes bynk.cloudflare { MySql }\ncapability Legacy = MySql @tls(\"required\")\n",
193        );
194        assert!(unit_reaches(&declared, &reach));
195        let other = parse(
196            "context shop.orders\nconsumes bynk.cloudflare { Postgres }\ncapability Main = Postgres\n",
197        );
198        assert!(!unit_reaches(&other, &reach));
199        let my = FIRST_PARTY_NPM
200            .iter()
201            .find(|d| d.package == "mysql2")
202            .expect("mysql2 is a first-party dependency");
203        assert_eq!(my.runtime_module, "mysql");
204        assert!(is_exact_version(my.version));
205        // Cloudflare's mysql2 guide needs 3.13.0 or later.
206        let parts: Vec<u32> = my.version.split('.').map(|p| p.parse().unwrap()).collect();
207        assert!(parts >= vec![3, 13, 0], "{}", my.version);
208    }
209}