bynk_model/vocabulary.rs
1//! `bynk_model::vocabulary` (the `bynk-ir` crate until crate-hygiene B1,
2//! #2939): the resolved *declaration-level* vocabulary the model's readers
3//! (the emitter, the editor's analysis, the CLIs) get through the builder,
4//! [`crate::lower`], instead of re-deriving the same facts from
5//! `bynk_syntax::ast` a second time.
6//!
7//! Every type here is a value some [`crate::lower`] function returns from a
8//! syntax-tree node plus the checker's own `TypedCommons`, and some
9//! `bynk-emit` site consumes — a service's protocol ([`ProtocolIr`]), a
10//! handler's kind ([`IrHandlerKind`]) and route cache ([`CacheIr`]), a
11//! `type` declaration's structure ([`TypeShape`]), an agent store field's
12//! storage shape ([`StoreFieldIr`]/[`StoreKindIr`]), a
13//! capability op's or attached method's signature ([`OpSig`]/[`FnSig`]), a
14//! `given` capability reference ([`CapRefIr`]), an actor's authentication
15//! seam ([`ActorSeamIr`]), an events subscription's pattern and shape
16//! ([`EventPatternIr`]/[`EventPatternValueIr`]/[`EventSubscriberShape`]),
17//! and the literal values a pattern can carry ([`ConstVal`]). Alongside
18//! them: four AST-walk helpers `bynk-emit` reads ([`block_uses_emit`],
19//! [`walk_block_exprs`], [`walk_exprs`], [`match_needs_if_chain`] — they
20//! live here rather than in the emitter because they were written to be
21//! shared with the builder, and `bynk-emit` is the consumer that remains).
22//!
23//! **Every `pub` item here has a reader outside `bynk-model`**, and the gated
24//! `unconsumed_ir_items` probe (`cargo xtask greenfield-status`) fails CI if one
25//! ever does not. The builder ([`crate::lower`]) can't vouch for this
26//! vocabulary, because both sit inside the one excluded crate. A type
27//! constructed only by a builder function nobody calls is exactly the shape
28//! phase 6 shipped. (Until B1 these were two crates, `bynk-ir` and `bynk-lower`,
29//! and the probe's two-owner rule kept either from vouching for the other.)
30//!
31//! **What this crate is not, and was.** Phase 6 of
32//! `design/bynk-compiler-trajectory.md` (`the-ir.md`, #1137) built here a
33//! full typed expression IR — `IrExpr`/`IrExprKind`/`IrStmt`, patterns and
34//! match compilation, `IrItem` with every declaration variant, `IrHandler`,
35//! `CommitShape` — and the builder (then the `bynk-lower` crate) built the
36//! `&CheckedProgram → Ir` pass that constructed it. The emitter never consumed any of it: its own
37//! string-emitting lowerer kept reading the AST, and the one production
38//! route into the IR constructors lowered every events-service handler body
39//! and discarded the result. The follow-on track (the IR cutover,
40//! #1542) priced finishing that cutover, found it was a second code
41//! generator rather than a retype, and re-settled on deletion: Slices D0–D2
42//! removed the detour, the constructors and those 23 types. The refusal is
43//! recorded with a trigger in `design/bynk-greenfield-compiler.md` Part 15.1
44//! (Slice D3). `design/archive/retired-tracks.md` has both tracks' closing
45//! summaries.
46//!
47//! **Identity fields are adapted, not literal** (Decision B of P6.1,
48//! extending ADR 0333's own precedent): the reference's
49//! `DefId`/`FieldId`/`VariantId` arena does not exist in this codebase, so
50//! every such slot is whatever cheap resolved handle the checker already
51//! has — a [`TyId`] for a type, a `String` for a name with no arena of its
52//! own.
53//!
54//! **Two AST types are embedded on purpose** (ADR 0366, P6.41):
55//! [`TypeShape::Refined`] carries `bynk_syntax::ast::BaseType` and
56//! `Refinement` directly, because the refinement predicate is rendered from
57//! its syntax and an IR mirror would be a field-for-field copy with no
58//! consumer of its own. The `ast_importers` probe's own doc comment
59//! (`xtask/src/greenfield_status.rs`) records that this embedding is
60//! invisible to it by construction.
61
62use std::collections::HashMap;
63
64use bynk_check::checker::TyId;
65use bynk_syntax::ast::{
66 BaseType, Block, Expr, ExprId, MatchArm, Pattern, Refinement, expr_children, statement_exprs,
67};
68
69/// A literal value an event-subscription pattern can match on
70/// ([`EventPatternValueIr::Const`]). Adapted from the
71/// reference's own `ConstVal` (`Int Float Str Bool Unit Bytes`, Part 6.2's
72/// comment): `DurationMillis` replaces `Bytes` because Bynk has a real
73/// `<int>.<unit>` duration *literal* (`ExprKind::DurationLit`) `Const` must
74/// cover, while `Bytes` has no literal AST form at all in this language —
75/// every `Bytes` value comes from a static-constructor *call*
76/// (`Bytes.fromUtf8`/`fromBase64`/`empty()`, `Callee::Intrinsic` territory,
77/// not a literal).
78#[derive(Debug, Clone, PartialEq)]
79pub enum ConstVal {
80 Int(i64),
81 Float(f64),
82 DurationMillis(i64),
83 Str(String),
84 Bool(bool),
85 Unit,
86}
87
88/// P6.14's real `CapRefIr` ([DECISION A], #1174, review of #1186) — one
89/// `bynk_syntax::ast::CapRef` entry of a provider's own `given` clause,
90/// under this module's usual "no arena, bare name" substitution:
91/// `context: Option<QualifiedName>` flattens to `Option<String>` via
92/// `QualifiedName::joined()` (the same `.`-joined form
93/// `resolve_consume_prefix` — `bynk-driver/src/project.rs` — already
94/// resolves against `consumes`/aliases), and `name: Ident` flattens to
95/// `String`, mirroring every other bare-name identity field in this module.
96/// Deliberately **not** resolved further here: which context a `Some`
97/// prefix actually names is whole-project `consumes`/alias data, a phase
98/// boundary this crate sits below — this type only preserves what `CapRef`
99/// itself carries, unresolved.
100#[derive(Debug, Clone)]
101pub struct CapRefIr {
102 pub context: Option<String>,
103 pub name: String,
104}
105
106/// A capability op's resolved signature (P6.12, [DECISION A], #1173) —
107/// `bynk_model::lower_capability_ops_ir`'s per-op return value, read by
108/// `emit_capability` (`bynk-emit/src/emitter/emit.rs`). The reference's own
109/// sketch named `ops: Vec<OpSig>` (`bynk-greenfield-compiler.md:1134`)
110/// without defining the type; this is that shape, adapted from
111/// `bynk_syntax::ast::CapabilityOp` — a signature only, no body — under
112/// this crate's "no arena" substitutions: `params: Vec<(String, TyId)>`,
113/// and `type_params: Vec<String>` mirroring the checker's own
114/// already-resolved `CapabilityOpInfo::type_params`
115/// (`bynk-check/src/checker.rs`) — a bare rigid-variable name, not a
116/// `TypeParam` AST node, since nothing here re-derives bounds a capability
117/// op's own `[T, …]` list never carries in the first place (#926).
118/// `bynk_model::lower_op_sig_ir` resolves `params`/`return_ty` in the scope
119/// `type_params` names, mirroring `context_checks::build_capability_op_info`'s
120/// own `vars` treatment (`bynk-check/src/context_checks.rs`) so a generic
121/// op's own `T` survives as `Ty::Var("T")` rather than collapsing to
122/// `Ty::Unit`. On a genuinely unresolvable name a `params`/`return_ty` entry
123/// *is* `Ty::Unit`, deliberately — see `bynk_model::lower_op_sig_ir`'s own doc
124/// comment for why that mirrors the checker's own fallback rather than
125/// panicking.
126#[derive(Debug, Clone)]
127pub struct OpSig {
128 pub name: String,
129 /// The op's own type parameters (#926) — empty for a non-generic op.
130 /// Scoped to the op itself, not the capability: `CapabilityDecl` carries
131 /// no `type_params` of its own (`bynk-syntax/src/ast.rs:556-562`), so
132 /// this is never merged with anything above it, unlike an attached
133 /// method, whose receiver type's own params are in scope too.
134 pub type_params: Vec<String>,
135 pub params: Vec<(String, TyId)>,
136 pub return_ty: TyId,
137}
138
139/// A `fn`'s own resolved signature, with no `body` and no `receiver` —
140/// the [`OpSig`]-shaped value a *foreign* unit's attached method needs when
141/// only its signature will ever be rendered (`emit_attached_methods`'
142/// delegating forward at `bynk_emit::emitter::emit::emit_forwarded_methods`),
143/// never its body (P6.18). `bynk_model::lower_attached_fn_sig_ir_from_types`
144/// resolves `params`/`return_ty` in the scope of the receiver type's own
145/// `[T, …]` list plus the method's, so a generic type's attached fn
146/// (`Bag.largest -> Option[A]`) resolves `A` to a type variable. A name that
147/// still does not resolve is an internal error (#3213).
148#[derive(Debug, Clone)]
149pub struct FnSig {
150 pub name: String,
151 pub has_self: bool,
152 pub params: Vec<(String, TyId)>,
153 pub return_ty: TyId,
154}
155
156/// P6.11's real `ProtocolIr` ([DECISION A], #1171) — one variant per
157/// `bynk_syntax::ast::ServiceProtocol` variant, `bynk_model::lower_protocol_ir`'s
158/// own return value. The reference's own sketch specifies only two of the
159/// six: `Events { event, pattern, schema_dispatch }`
160/// (`bynk-greenfield-compiler.md:1881`) and `WebSocket { in_ty, out_ty }`
161/// (`:1959`) — field names taken verbatim from those two rows. `Call`/
162/// `Http`/`Cron` carry no payload, not because one was dropped: the actual
163/// per-trigger binding (a route, a schedule) lives on each *handler*
164/// (`HandlerKind::Http { method, path }`/`Cron { expr }`), already
165/// reachable through [`IrHandlerKind`] — `ServiceProtocol`'s own doc
166/// comment says this in as many words ("the endpoint lives on each
167/// handler"), which is why the reference never spells these three out
168/// either. E2 (`:1737`) constrains the *set*, not the shape: "a closed
169/// nominal set … grows one variant per real trigger" — the AST's own closed
170/// `ServiceProtocol` already satisfies that exactly, so this type is total
171/// over what a certified program's own service can declare, the same claim
172/// [`StoreKindIr`]'s own doc makes about `Queue` being gated pre-`certify`.
173#[derive(Debug, Clone)]
174pub enum ProtocolIr {
175 Call,
176 Http,
177 Cron,
178 /// `from queue("name")`.
179 Queue {
180 name: String,
181 },
182 /// `from email("addr")` (#3328): the claimed recipient address or
183 /// `*@domain` catch-all.
184 Email {
185 address: String,
186 },
187 /// `from websocket(in: …, out: …)` — the two frame types, resolved
188 /// (each through the `Ty::Unit` fallback `bynk_model::lower_protocol_ir`
189 /// documents, since the checker itself does not reject an unresolvable
190 /// frame type).
191 WebSocket {
192 in_ty: TyId,
193 out_ty: TyId,
194 },
195 /// `from Events(E)` — the subscribed event type, resolved, plus the
196 /// two independent, optional filters a subscription may carry.
197 Events {
198 event: TyId,
199 pattern: Option<EventPatternIr>,
200 /// P6.40 (design/tracks/the-ir.md §6a): the `SchemaDispatch` wrapper
201 /// is dropped — it carried only the pattern plus a parse-only `span`.
202 /// The pattern widened from a bare `i64` to [`SchemaVersionIr`] when
203 /// `via schema(...)` gained ranges and `_` (events slice 4b, #990).
204 schema_dispatch: Option<SchemaVersionIr>,
205 },
206}
207
208/// What a `via schema(...)` clause matches the envelope's `schemaVersion`
209/// against (events slice 4b, #990; patterns slice 5, #2699). Both bounds of a
210/// range are inclusive, and an open end is `None`.
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
212pub enum SchemaVersionIr {
213 /// `via schema(2)`.
214 Exact(i64),
215 /// `via schema(2..4)`, `(2..)`, `(..4)`.
216 Range { lo: Option<i64>, hi: Option<i64> },
217 /// `via schema(_)`: every version, so no guard, but the envelope is still
218 /// forwarded to the handler.
219 Any,
220}
221
222/// #1226/#1187 slice 6: the two facts a service's own event-subscriber
223/// *shape* needs, captured at that unit's own check time (its
224/// `CheckedProgram` does not survive past `check_unit_files`'s per-file loop)
225/// so a *different* unit's own composition root can later decide whether its
226/// subscriber to this service wants the event envelope forwarded, without
227/// re-walking this unit's raw `UnitTable`. Pure syntax, zero `TyId`
228/// dependency. Produced by `bynk_model::lower_event_subscriber_shapes_ir`, sized
229/// like #1187's own `unit_callees` (#1202) accumulator.
230#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
231pub struct EventSubscriberShape {
232 pub two_param_handler: bool,
233 pub schema_dispatch: bool,
234}
235
236impl EventSubscriberShape {
237 /// The one envelope rule (back-half paydown 1B.1c, Decision F of #3928):
238 /// whether a delivery forwards the event's envelope to this subscriber.
239 ///
240 /// It does when the `on event` handler declared the optional second
241 /// `env: EventEnvelope` parameter (events track, slice 2), and also when
242 /// the protocol carries a `via schema(N)` clause (slice 4, #985): the
243 /// callee then inserts a synthetic `__bynkSchemaEnv` parameter in the same
244 /// position (`emit_service`, which reads `ProtocolIr::Events`'
245 /// `schema_dispatch` for that), and needs the value to line up
246 /// positionally. Every site that decides whether to pass the envelope reads
247 /// this method, so the callers and that callee cannot disagree.
248 pub fn wants_envelope(&self) -> bool {
249 self.two_param_handler || self.schema_dispatch
250 }
251}
252
253#[cfg(test)]
254mod event_subscriber_shape_tests {
255 use super::EventSubscriberShape;
256
257 fn shape(two_param_handler: bool, schema_dispatch: bool) -> EventSubscriberShape {
258 EventSubscriberShape {
259 two_param_handler,
260 schema_dispatch,
261 }
262 }
263
264 #[test]
265 fn the_envelope_is_wanted_by_a_second_parameter_or_a_schema_guard() {
266 assert!(!shape(false, false).wants_envelope());
267 assert!(shape(true, false).wants_envelope());
268 assert!(shape(false, true).wants_envelope());
269 assert!(shape(true, true).wants_envelope());
270 }
271}
272
273/// The payload of `ProtocolIr::Events`'s own `pattern` — a `from
274/// Events(E { field: value, .. })` structural filter, [DECISION C] (#1171).
275/// **Not** `bynk_syntax::ast::EventPattern` reused verbatim, unlike
276/// `SchemaVersionPattern`: that type carries `rest_span` (a parse artefact
277/// for the grammar-required trailing `..`, giving a later reader nothing to
278/// act on) and its own `EventPatternValue::Variant` is an *unresolved,
279/// optionally-qualified* name pair — exactly the shape this module's whole
280/// posture rejects everywhere else.
281#[derive(Debug, Clone)]
282pub struct EventPatternIr {
283 /// `(field name, matched value)`, in source order — no dedicated
284 /// `EventPatternFieldIr` struct: a two-part fact with no further
285 /// structure, the same plain-tuple shape `TypeShape::Sum::embeds` uses.
286 pub fields: Vec<(String, EventPatternValueIr)>,
287}
288
289/// One [`EventPatternIr`] field's own matched value.
290#[derive(Debug, Clone)]
291pub enum EventPatternValueIr {
292 /// Reuses [`ConstVal`] for the closed `Int`/`Str`/`Bool` literal set —
293 /// `Pattern::Literal`'s own closed set, and the only reason `ConstVal`
294 /// is still a type of its own.
295 Const(ConstVal),
296 /// A nullary sum-variant tag, resolved and unqualified — a bare
297 /// `tag: String`. The AST's own optional qualifying `type_name` is
298 /// dropped, not lost: the sole consumer
299 /// (`bynk_emit::emitter::lower::event_pattern_guard_ir`, #1187's slice 5)
300 /// already destructures down to the bare tag alone — the qualification
301 /// is disambiguation for the *checker*, resolved against the field's
302 /// declared sum type before this point.
303 Variant { tag: String },
304}
305
306/// A GET handler's own `@cache(maxAge:, scope:)` freshness policy (#1228),
307/// interpreted — raw `{name, value: Expr}` annotation pairs mean nothing on
308/// their own, so the seconds and the scope are resolved here once.
309/// Handler-scoped, not service-scoped: `bynk_model::lower_route_cache_ir` is
310/// a standalone per-route reader, wired directly into
311/// `emitter/workers_entry.rs`'s own route construction — the same live,
312/// standalone-consumer shape `lower_protocol_ir`/`lower_handler_given_ir`/
313/// `lower_actor_seam_ir` already established. (A service-level policy
314/// struct existed beside it until Slice D2 of #1542; it had no consumer.)
315#[derive(Debug, Clone)]
316pub struct CacheIr {
317 /// `maxAge` in whole seconds (the `Cache-Control: max-age`).
318 pub max_age_secs: i64,
319 /// `"public"` or `"private"` — defaults to `"private"` so a *shared*
320 /// cache never stores unless the author opts into `public`. Bare
321 /// `&'static str`, not an enum: mirrors `emitter/workers_entry.rs`'s
322 /// own former `CachePolicy::scope` shape verbatim (the two literal
323 /// values this route's own generated `Cache-Control` header ever
324 /// spells), not a new representation invented here — `CachePolicy`
325 /// itself is gone, superseded by this struct (#1228).
326 pub scope: &'static str,
327 /// `immutable: true` (caching raw responses) — appends the RFC 8246
328 /// `immutable` directive to the `Cache-Control`. Defaults to `false`.
329 pub immutable: bool,
330}
331
332/// A declared type's own resolved structure (Part 6.6, #1161) —
333/// `bynk_model::lower_type_shape_ir`'s return value. Covers the AST's
334/// four `TypeBody` variants (`Refined`/`Record`/`Sum`/`Opaque`) with the
335/// reference's own three ([DECISION A]): `Opaque` unifies into `Refined`
336/// via its own `opaque: bool` field, mirroring `emitter/emit.rs`'s own
337/// `RefinedShape { base, refinement, is_opaque }` — the shipped emitter's
338/// own precedent for exactly this unification (`emit_type`,
339/// `emitter/emit.rs:19`).
340#[derive(Debug, Clone)]
341pub enum TypeShape {
342 /// Every field the record declares, in declaration order ([DECISION B]
343 /// extended: a field's own inline `refinement` is dropped — a
344 /// construction-time constraint the checker already enforces, not part
345 /// of the emitted shape. Scoped claim: no reader on the record-*type*
346 /// emission path (`emit_record_type`, `emitter/emit.rs:234-263`, reads
347 /// `type_ref` alone). There *is* one `.refinement` reader in the
348 /// emitter overall — `emitter/emit.rs:2781`, agent-state zero-value
349 /// construction — but that is `StoreFieldIr` territory (P6.7), out of
350 /// this variant's scope; do not read this comment as licence to drop
351 /// `refinement` from a future store field too.
352 Record { fields: Vec<(String, TyId)> },
353 /// Every variant the sum declares, each with its own payload field
354 /// list, plus any `embeds` clauses ([DECISION C], #1161) — each a
355 /// `(source type, target variant tag)` pair, a two-part fact with no
356 /// further structure and so a plain tuple, not a dedicated struct.
357 Sum {
358 variants: Vec<(String, Vec<(String, TyId)>)>,
359 embeds: Vec<(TyId, String)>,
360 },
361 /// `type X = base where refinement` (`Refined`) or `type X = unsafe
362 /// base ...` (`Opaque`, `opaque: true`). `refinement` is `Option`, not
363 /// the reference's own bare `RefinementId` ([DECISION B]) — a bare
364 /// `type X = Int` (no `where` clause) is legal and carries none.
365 Refined {
366 base: BaseType,
367 refinement: Option<Refinement>,
368 opaque: bool,
369 },
370}
371
372/// An agent `store` field's storage shape (`design/bynk-greenfield-compiler.md`
373/// §6.6, R6.14, #1163) — `bynk_model::lower_store_field_shape_ir`'s return
374/// value, read by `emit_agent`'s state section. Mirrors
375/// `checker::StoreField`'s own five-kind dispatch
376/// (`bynk-check/src/checker.rs`) in shape, but is persistent IR data, not
377/// that checking pass's own ephemeral, per-agent scratch value — the two are
378/// deliberately not unified. Shape only: a `Cell` field's initialiser
379/// expression is rendered by the emitter from the AST (the `init` slot that
380/// once carried it as an `IrExpr` went with the expression IR in Slice D2 of
381/// #1542).
382#[derive(Debug, Clone)]
383pub struct StoreFieldIr {
384 /// The field's own declared name ([DECISION A]: `String`, sourced
385 /// directly from `StoreField.name.name` — this module's own "no arena
386 /// exists in this codebase" substitution, applied to the reference's
387 /// own `FieldId` arena slot).
388 pub field: String,
389 pub kind: StoreKindIr,
390 /// `@indexed(by: …)` sibling-table keys, in the annotation's own
391 /// `by:`-argument order — one entry per *distinct* `by:` argument
392 /// ([DECISION C]), no sort ([DECISION E]). Deduplicated: the checker
393 /// validates each `by:` argument independently with no duplicate check
394 /// (`validate_indexed_keys`), so `@indexed(by: k, by: k)` certifies —
395 /// `bynk_model::lower_store_field_shape_ir` guards against it, mirroring the
396 /// shipped emitter's own `store_map_indexes` dedup. Empty for every kind
397 /// but `Map`, the only kind `@indexed` attaches to (`ANNOTATIONS`'s own
398 /// registry, `bynk-check/src/context_checks.rs`). Each key is the
399 /// indexed value-field's own name, a bare `String` ([DECISION C],
400 /// #1163): the sibling table's own emitted shape
401 /// (`Record<string, string[]>`) is fixed by the *map's own key type*,
402 /// not the indexed field's, so the indexed field's resolved type is not
403 /// needed downstream — the same "no further structure" plain-value
404 /// shape `TypeShape::Sum::embeds` uses.
405 pub indexed: Vec<String>,
406}
407
408/// P6.7's real `StoreKindIr` (Part 6.6, R6.14, #1163) — five variants, one
409/// per functional storage kind (`Cell`/`Map`/`Set`/`Cache`/`Log`). `Queue`
410/// is not a variant here: `bynk.store.kind_unsupported` gates it before
411/// `certify` (R3.10), so this type is total over what a certified program's
412/// own store fields can actually contain, not a subset some later slice
413/// needs to extend. [DECISION B]: `Duration` substitutes to `i64`
414/// milliseconds throughout — the same substitution [`ConstVal::DurationMillis`]
415/// and `checker::StoreField::Cache`'s own already-resolved TTL already made.
416#[derive(Debug, Clone)]
417pub enum StoreKindIr {
418 /// `Cell[T]` — element type.
419 Cell(TyId),
420 /// `Map[K, V]` — key, value.
421 Map(TyId, TyId),
422 /// `Set[T]` — element type.
423 Set(TyId),
424 /// `Cache[K, V] @ttl(...)` — key, value, TTL in milliseconds.
425 Cache(TyId, TyId, i64),
426 /// `Log[T] [@retain(...)]` — element type, optional retain millis.
427 Log(TyId, Option<i64>),
428}
429
430impl StoreKindIr {
431 /// The value type of a `Map[K, V]` field; `None` for every other kind.
432 pub fn map_value(&self) -> Option<TyId> {
433 match self {
434 StoreKindIr::Map(_, value) => Some(*value),
435 StoreKindIr::Cell(_)
436 | StoreKindIr::Set(_)
437 | StoreKindIr::Cache(..)
438 | StoreKindIr::Log(..) => None,
439 }
440 }
441
442 /// The element type of a `Log[T]` field; `None` for every other kind.
443 pub fn log_element(&self) -> Option<TyId> {
444 match self {
445 StoreKindIr::Log(element, _) => Some(*element),
446 StoreKindIr::Cell(_)
447 | StoreKindIr::Map(..)
448 | StoreKindIr::Set(_)
449 | StoreKindIr::Cache(..) => None,
450 }
451 }
452}
453
454#[cfg(test)]
455mod store_kind_accessor_tests {
456 use super::*;
457 use bynk_check::checker::{Ty, Types};
458
459 #[test]
460 fn map_value_and_log_element_answer_for_their_own_kind_only() {
461 let tys = Types::new();
462 let k = tys.intern(Ty::Unit);
463 let v = tys.intern(Ty::Base(bynk_syntax::ast::BaseType::Int));
464 let kinds = [
465 StoreKindIr::Cell(v),
466 StoreKindIr::Map(k, v),
467 StoreKindIr::Set(v),
468 StoreKindIr::Cache(k, v, 1),
469 StoreKindIr::Log(v, None),
470 ];
471 let map_values: Vec<Option<TyId>> = kinds.iter().map(StoreKindIr::map_value).collect();
472 assert_eq!(map_values, vec![None, Some(v), None, None, None]);
473 let log_elements: Vec<Option<TyId>> = kinds.iter().map(StoreKindIr::log_element).collect();
474 assert_eq!(log_elements, vec![None, None, None, None, Some(v)]);
475 }
476}
477
478/// #1187's slice 3: a handler's resolved actor-verification seam, wrapping
479/// `bynk-check`'s own five already-resolved seam structs
480/// (`bynk-check/src/actors.rs`) by value — confirmed none carry any
481/// `bynk_syntax::ast`/`TypeRef`/`Expr`: every field is `String`/`bool`/
482/// `i64`/`Option`/`Vec` (or, for `BearerSeam::authorization`,
483/// `ClaimPredicate`, itself a plain recursive `String`/`Box` enum). Built by
484/// `bynk_model::lower_actor_seam_ir`, which tries the five resolvers in the one
485/// priority order that actually matters — `sum_members_for` first, since
486/// it's the only resolver whose result can otherwise collide with
487/// `bearer_seam_for`'s (a sum's own first peer can itself be Bearer-schemed;
488/// `bearer_seam_for` has no `by.is_sum()` guard of its own to prevent that).
489/// The other three pairs are mutually exclusive by construction — each
490/// single-actor resolver requires the primary actor's own `auth` scheme to
491/// match one specific `Scheme` variant, a closed set — so their relative
492/// order here is a no-op, not a second load-bearing decision.
493///
494/// No `Signature` variant, deliberately: neither call site this slice
495/// converts (`emit_service`'s `deps`-identity-binder chain, `emit.rs`;
496/// `emit_worker_compose`'s HTTP-dispatch match, `workers.rs`) ever consults
497/// `signature_seam_for` as part of this priority chain — Signature is a
498/// separate, request-verification-only concept there (see
499/// `workers_entry.rs`'s own `HttpRoute.signature` field), not one this
500/// enum's callers need. Adding an unreachable variant this slice's own
501/// `lower_actor_seam_ir` never constructs would be exactly the kind of
502/// premature surface `bynk-design-notes.md`'s own conventions ask this
503/// codebase to avoid.
504#[derive(Debug, Clone)]
505pub enum ActorSeamIr {
506 /// No `by` clause resolves to any of the four seams below (`Visitor`/
507 /// `None`-schemed, or no `by` clause at all).
508 None,
509 /// `by who: A | B` — an ordered sum of peer actors, first-wins.
510 Sum(Vec<bynk_check::actors::SumMember>),
511 /// I3 (#1971): an `on call` handler's sum, `by who: Caller | Legacy`.
512 /// The call is already authenticated; the sum names which verified
513 /// caller it was (`bynk_check::actors::call_admission_for`).
514 CallSum(Vec<bynk_check::actors::CallSumMember>),
515 Bearer(bynk_check::actors::BearerSeam),
516 Oidc(bynk_check::actors::OidcSeam),
517 /// #3386: a single `SignedCookie` actor: the session cookie is read, verified
518 /// and its `sub` minted into the identity at the edge.
519 SignedCookie(bynk_check::actors::SignedCookieSeam),
520 /// A cross-context `on call … by c: Caller` handler's own binder name —
521 /// `caller_binder_for`'s return type is already the bare `Option<String>`
522 /// the other four resolvers reduce a whole struct down to one field for.
523 Caller(String),
524 /// #3328: a `from email` handler's `by s: Sender` binder. The Worker's
525 /// `email()` entry mints the `SenderIdentity` and threads it through
526 /// `deps.identity`, as `Caller` threads the calling context's name.
527 Sender(String),
528}
529
530impl ActorSeamIr {
531 /// The identity type a Bearer or `SignedCookie` seam mints from the verified `sub`
532 /// and threads into `deps.identity`, when the handler's `by` clause binds it.
533 pub fn captured_identity_type(&self) -> Option<&str> {
534 match self {
535 ActorSeamIr::Bearer(s) if s.binder.is_some() => Some(&s.identity_type),
536 ActorSeamIr::SignedCookie(s) if s.binder.is_some() => Some(&s.identity_type),
537 ActorSeamIr::None
538 | ActorSeamIr::Sum(_)
539 | ActorSeamIr::CallSum(_)
540 | ActorSeamIr::Bearer(_)
541 | ActorSeamIr::Oidc(_)
542 | ActorSeamIr::SignedCookie(_)
543 | ActorSeamIr::Caller(_)
544 | ActorSeamIr::Sender(_) => None,
545 }
546 }
547}
548
549/// P6.24a: an IR-native mirror of [`bynk_syntax::ast::HandlerKind`] — a
550/// field-for-field copy, not a re-export. Every field (`HttpMethod`, a
551/// route `path: String`, a cron `expr: String`) is already fully resolved
552/// at parse time; nothing here ever needed `TyId`/`CheckedProgram`, so
553/// `bynk_model::lower_handler_kind_ir` is a pure, unconditional conversion —
554/// unlike almost everything else in this module, it carries no ADR 0334
555/// totality story because it can never fail to resolve.
556///
557/// Exists so `emitter.rs`'s several purely-structural handler-kind scans
558/// ("is this an HTTP handler", "which cron expression") have somewhere
559/// IR-native to route through instead of matching `bynk_syntax::ast`
560/// directly (#1184's review; R6.16, handler-invocation
561/// origin-independence). With 70-odd references across `bynk-emit` it is
562/// this crate's most-consumed type.
563#[derive(Debug, Clone, PartialEq, Eq)]
564pub enum IrHandlerKind {
565 Call,
566 Http {
567 method: IrHttpMethod,
568 path: String,
569 },
570 Cron {
571 expr: String,
572 },
573 Message,
574 Open,
575 Close,
576 Event,
577 /// `on rejected` (#2341, decision C).
578 Rejected,
579}
580
581/// [`IrHandlerKind::Http`]'s own method field — a field-for-field mirror of
582/// [`bynk_syntax::ast::HttpMethod`], same reasoning as [`IrHandlerKind`]
583/// itself.
584#[derive(Debug, Clone, Copy, PartialEq, Eq)]
585pub enum IrHttpMethod {
586 Get,
587 Post,
588 Put,
589 Patch,
590 Delete,
591}
592
593impl IrHttpMethod {
594 /// P6.51 (design/tracks/the-ir.md §6b): field-for-field mirror of
595 /// [`bynk_syntax::ast::HttpMethod::as_str`].
596 pub fn as_str(self) -> &'static str {
597 match self {
598 IrHttpMethod::Get => "GET",
599 IrHttpMethod::Post => "POST",
600 IrHttpMethod::Put => "PUT",
601 IrHttpMethod::Patch => "PATCH",
602 IrHttpMethod::Delete => "DELETE",
603 }
604 }
605
606 /// P6.57 (design/tracks/the-ir.md §6b): field-for-field mirror of
607 /// [`bynk_syntax::ast::HttpMethod::from_ident`].
608 pub fn from_ident(s: &str) -> Option<IrHttpMethod> {
609 match s {
610 "GET" => Some(IrHttpMethod::Get),
611 "POST" => Some(IrHttpMethod::Post),
612 "PUT" => Some(IrHttpMethod::Put),
613 "PATCH" => Some(IrHttpMethod::Patch),
614 "DELETE" => Some(IrHttpMethod::Delete),
615 _ => None,
616 }
617 }
618}
619
620impl From<bynk_syntax::ast::HttpMethod> for IrHttpMethod {
621 /// The method the checker resolved (a typed `HandlerAddress`, say), without a spelling in between.
622 fn from(m: bynk_syntax::ast::HttpMethod) -> IrHttpMethod {
623 use bynk_syntax::ast::HttpMethod;
624 match m {
625 HttpMethod::Get => IrHttpMethod::Get,
626 HttpMethod::Post => IrHttpMethod::Post,
627 HttpMethod::Put => IrHttpMethod::Put,
628 HttpMethod::Patch => IrHttpMethod::Patch,
629 HttpMethod::Delete => IrHttpMethod::Delete,
630 }
631 }
632}
633
634/// Events track, slice 0 (spine #936): does this block contain a real
635/// `Events.emit[...]` call anywhere — including nested branches, match arms,
636/// lambdas, and any other expression position (a `Paren`, an `Ok`/`Err`
637/// wrapper, a `Call`/`RecordConstruction` argument, a `BinOp` operand, …)?
638/// Gates release-at-commit buffer threading (`deps.__events`) so a handler
639/// that never emits keeps byte-identical output, mirroring the old send gate's
640/// gate on `deps.__exec`.
641///
642/// Driven off the exhaustive `walk_block_exprs`/`walk_exprs` visitor rather
643/// than a hand-rolled `ExprKind` match — a bespoke match here previously
644/// covered only `MethodCall`/`Block`/`If`/`Match`/`Lambda` and silently
645/// disagreed with `lower_expr_into` (which recurses into every expression
646/// position), so `do (Events.emit[E](event))` — one added paren — compiled
647/// clean but emitted a body that referenced an undeclared `__events` local
648/// (`tsc`-only failure, no bynk diagnostic). Riding the walker means this
649/// can't drift from the lowering again: a new `ExprKind` variant fails to
650/// compile here until `walk_exprs` itself is taught to visit it.
651///
652/// #1187's slice 6 plumbing (review of #1202): reads the checker's own
653/// already-resolved `Callee::Capability{cap:"Events",op:"emit"}` for each
654/// visited call site instead of a bare-`Ident("Events")`-receiver name
655/// match. Was deliberately syntactic before this — this function's own
656/// prior doc comment named the locally-shadowed-`Events` false positive an
657/// "accepted approximation," matching the old send gate's own precedent —
658/// but that approximation stopped being harmless once `crate::project::
659/// unit_table_uses_emit` (the project-wide compose-gating twin this
660/// function's own callers must agree with) became precise first: the two
661/// disagreeing on exactly the shadowed case produces a real `tsc` type
662/// error (a `deps.__eventsDispatch` call site with nothing supplying it),
663/// not just an unused interface field.
664pub fn block_uses_emit(b: &Block, callees: &HashMap<ExprId, bynk_check::checker::Callee>) -> bool {
665 let mut found = false;
666 walk_block_exprs(b, &mut |e| {
667 if !found
668 && matches!(
669 callees.get(&e.id),
670 Some(bynk_check::checker::Callee::Capability {
671 op,
672 first_party: Some(bynk_check::firstparty::FirstPartyCap::Events),
673 ..
674 }) if op == "emit"
675 )
676 {
677 found = true;
678 }
679 });
680 found
681}
682
683/// #1960: whether a body reaches the Worker `env` on the Workers target: it
684/// calls a consumed context's service (through its Service Binding) or
685/// constructs a local agent (through its Durable Object namespace).
686pub fn block_reaches_worker_env(
687 b: &Block,
688 callees: &HashMap<ExprId, bynk_check::checker::Callee>,
689) -> bool {
690 let mut found = false;
691 walk_block_exprs(b, &mut |e| {
692 if !found
693 && matches!(
694 callees.get(&e.id),
695 Some(
696 bynk_check::checker::Callee::Cross { .. }
697 | bynk_check::checker::Callee::AgentInit(_)
698 )
699 )
700 {
701 found = true;
702 }
703 });
704 found
705}
706
707pub fn walk_block_exprs(b: &Block, f: &mut impl FnMut(&Expr)) {
708 let mut exprs = Vec::new();
709 for s in &b.statements {
710 statement_exprs(s, &mut exprs);
711 }
712 exprs.push(&b.tail);
713 for e in exprs {
714 walk_exprs(e, f);
715 }
716}
717
718/// v0.22b: pre-order expression visitor — visits `e`, then every
719/// sub-expression, including statements and tails of nested blocks. Driven by
720/// `ast::expr_children`, the exhaustive total child iterator, rather than a
721/// hand-matched recursion duplicating it — a new `ExprKind` variant fails to
722/// compile in `expr_children` until it is taught to visit it, instead of
723/// silently under-visiting here.
724pub fn walk_exprs(e: &Expr, f: &mut impl FnMut(&Expr)) {
725 f(e);
726 for child in expr_children(e) {
727 walk_exprs(child, f);
728 }
729}
730
731/// A match needs the if/else-if lowering (ADR 0169) when any arm carries a guard
732/// or a refutable nested payload pattern — a JS `switch` on `.tag` can express
733/// neither. Flat, unguarded matches keep the `switch` (zero churn to existing
734/// output).
735///
736/// Consumed only by `bynk-emit`'s string emitter today (`emitter/lower.rs`'s
737/// two match-lowering sites). It became `pub` and moved here at P6.5/P7.12
738/// so the IR lowering pass could reuse the identical predicate to record its
739/// own match form and the two could never silently disagree; that second
740/// consumer went with Slices D1/D2 of #1542. It stays in the model rather
741/// than moving back because it is a pure predicate over the AST with no
742/// emitter state, the same footing as its three sibling walk helpers above,
743/// and moving it would be churn with no reader gained.
744pub fn match_needs_if_chain(arms: &[MatchArm]) -> bool {
745 arms.iter().any(|a| {
746 a.guard.is_some()
747 || pattern_has_nested_test(&a.pattern)
748 || matches!(a.pattern, Pattern::Refined { .. })
749 })
750}
751
752/// True when `pat` carries a payload sub-pattern that is itself refutable (a
753/// nested variant/literal) — i.e. it cannot be tested by a single `.tag` switch.
754fn pattern_has_nested_test(pat: &Pattern) -> bool {
755 match pat {
756 Pattern::Variant { bindings, .. } => bindings.iter().any(|b| {
757 let sp = b.pattern();
758 !sp.is_irrefutable() || pattern_has_nested_test(sp)
759 }),
760 // #2641: a record has no tag to switch on, and its fields are read off
761 // the scrutinee (`.field`), so a record pattern always needs the
762 // if-chain.
763 Pattern::Record { .. } => true,
764 // #2680: a list is tested by its length and indexed, never switched on.
765 Pattern::List { .. } => true,
766 // #2699: a range is a pair of comparisons, never a `case` label.
767 Pattern::Range(_) => true,
768 // #472: a refined pattern is never a top-level irrefutable/nested
769 // payload today (the parser admits only `_` as `inner`, and only at a
770 // match arm's top level), but keep this exhaustive and correct for
771 // when nesting is admitted. (An `Or`'s alternatives can never
772 // themselves be `Refined` — #472/#474's merged parser design only
773 // ever wraps a *whole*, already-folded `|`-chain in `Refined`, never
774 // the other way around — so this arm only matters nested under a
775 // payload, e.g. a hypothetical `Some(_ where P)`.)
776 Pattern::Refined { inner, .. } => !inner.is_irrefutable() || pattern_has_nested_test(inner),
777 // #474: a bindingless, non-nested or-pattern (`1 | 2 | 3`,
778 // `Pending | Cancelled(_, _)`) stays on the flat switch — it lowers to
779 // fall-through `case` labels sharing one body. One with bindings or a
780 // nested refutable payload needs the if-chain (a `switch` can't bind
781 // different alternatives' fields to the same name).
782 Pattern::Or(alts, _) => alts
783 .iter()
784 .any(|p| !p.bound_names().is_empty() || pattern_has_nested_test(p)),
785 Pattern::Wildcard(_) | Pattern::Binding(_) | Pattern::Literal { .. } => false,
786 }
787}