Skip to main content

bynk_model/
entry.rs

1//! #2695: the signatures of a unit's entry handlers - every `on call(...)` of a
2//! `service` - described structurally from the checker's resolved types, so a
3//! host (the playground's Arguments row) never re-parses the source to learn
4//! what a run can be passed.
5//!
6//! Each parameter's declared `TypeRef` is resolved with [`resolve_type_ref`]
7//! (the checker's own resolution, against the unit's visible types) and the
8//! resulting [`Ty`] is walked into an [`EntryShape`]; a named type's fields or
9//! variants come from its `TypeDecl` in the same table. Plain data: the
10//! consumer chooses the wire format (`bynk-wasm` renders JSON).
11//!
12//! Crate-hygiene B3 (#2999, DECISION C): this was `bynk_check::entry_signature`
13//! until the signatures became system-model items. It moved verbatim, so its
14//! syntax-tree reads (the `call` handler filter, `TypeBody`'s records and
15//! sums) are now the model builder's, which is where M-1 puts them.
16//!
17//! [`EntryShape`] and [`crate::TypeShape`] both describe a record's fields and
18//! a sum's variants, from two builders. Rebuilding this one over `TypeShape` is
19//! deferred past 1.0 (crate-hygiene B4, #3012): `build_output` holds no
20//! `CheckedProgram` or type arena to lower it from. *Trigger:* a type-shape
21//! change that has to be made in both, or the model becoming public.
22
23use std::collections::HashMap;
24use std::sync::Arc;
25
26use bynk_syntax::ast::{HandlerKind, ServiceProtocol, TypeBody, TypeDecl, TypeRef};
27
28use bynk_check::checker::{NamedKind, Ty, TyId, Types, resolve_type_ref};
29use bynk_check::symbols::{UnitTable, combined_types_for};
30
31/// One `service`'s `on call(...)` handler.
32#[derive(Debug, Clone, PartialEq)]
33pub struct EntryHandler {
34    /// The unit the service is declared in (`app.demo`).
35    pub unit: String,
36    pub service: String,
37    pub params: Vec<EntryParam>,
38    /// The declared return type, as the checker displays it.
39    pub returns: String,
40}
41
42#[derive(Debug, Clone, PartialEq)]
43pub struct EntryParam {
44    pub name: String,
45    /// The declared type, as the checker displays it (`Slug`, `List[Int]`).
46    pub ty: String,
47    pub shape: EntryShape,
48}
49
50/// What a value of a parameter's type looks like, resolved to its leaves.
51#[derive(Debug, Clone, PartialEq)]
52pub enum EntryShape {
53    /// `Int`, `String`, `Bool`, `Float`, `Duration`, `Instant`, `Bytes`, `Decimal`.
54    Base(&'static str),
55    /// `type Slug = String where ...` - a value is a `base` value that passes
56    /// the type's validator.
57    Refined {
58        name: String,
59        base: &'static str,
60    },
61    /// `type Token = opaque String` - minted only through its own `.of`.
62    Opaque {
63        name: String,
64        base: &'static str,
65    },
66    Record {
67        name: String,
68        fields: Vec<(String, EntryShape)>,
69    },
70    Sum {
71        name: String,
72        variants: Vec<(String, Vec<(String, EntryShape)>)>,
73    },
74    List(Box<EntryShape>),
75    Set(Box<EntryShape>),
76    Option(Box<EntryShape>),
77    Map(Box<EntryShape>, Box<EntryShape>),
78    Result(Box<EntryShape>, Box<EntryShape>),
79    Unit,
80    /// A type already being described further up (a self-referential record or
81    /// sum): named, not expanded again.
82    Recursive(String),
83    /// A named record or sum left unexpanded because it sits deeper than
84    /// this module's `MAX_DEPTH` nested records/sums (a wide DAG of
85    /// non-recursive types would otherwise grow exponentially).
86    Named(String),
87    /// Anything else (a generic record instantiation, a function, an effect),
88    /// as the checker displays it. Not something a host can build a value for.
89    Other(String),
90}
91
92/// How many records/sums may nest before a further one is reported as
93/// [`EntryShape::Named`] instead of expanded.
94pub(crate) const MAX_DEPTH: usize = 6;
95
96type Scope = HashMap<String, Arc<TypeDecl>>;
97
98/// Resolution scopes: a type's own fields are resolved in the scope of the unit
99/// that *declares* it (its `combined_types_for`), not the entry unit's.
100struct Scopes<'a> {
101    unit_tables: &'a HashMap<String, UnitTable>,
102    unit_uses: &'a HashMap<String, Vec<String>>,
103    cache: HashMap<String, Arc<Scope>>,
104    /// (declaring unit, name) already expanded within the current parameter.
105    seen: std::collections::HashSet<(String, String)>,
106    tys: Types,
107}
108
109impl Scopes<'_> {
110    fn scope(&mut self, unit: &str) -> Arc<Scope> {
111        let (t, u) = (self.unit_tables, self.unit_uses);
112        self.cache
113            .entry(unit.to_string())
114            .or_insert_with(|| Arc::new(combined_types_for(unit, t, u)))
115            .clone()
116    }
117
118    /// The unit declaring `decl` (found by identity among the unit tables),
119    /// falling back to `visible_from`.
120    fn declaring_unit(&self, name: &str, decl: &Arc<TypeDecl>, visible_from: &str) -> String {
121        let mut units: Vec<&String> = self.unit_tables.keys().collect();
122        units.sort();
123        units
124            .into_iter()
125            .find(|u| {
126                self.unit_tables[*u]
127                    .types
128                    .get(name)
129                    .is_some_and(|d| Arc::ptr_eq(d, decl))
130            })
131            .cloned()
132            .unwrap_or_else(|| visible_from.to_string())
133    }
134}
135
136/// The entry handlers of the unit `unit`'s services, ordered by service name
137/// then declaration order. Types are resolved in the entry unit's scope; the
138/// fields of a named type in its declaring unit's.
139pub fn entry_handlers(
140    unit: &str,
141    unit_tables: &HashMap<String, UnitTable>,
142    unit_uses: &HashMap<String, Vec<String>>,
143) -> Vec<EntryHandler> {
144    let Some(table) = unit_tables.get(unit) else {
145        return Vec::new();
146    };
147    let mut sc = Scopes {
148        unit_tables,
149        unit_uses,
150        cache: HashMap::new(),
151        seen: Default::default(),
152        tys: Types::new(),
153    };
154    let entry_scope = sc.scope(unit);
155    let mut names: Vec<&String> = table.services.keys().collect();
156    names.sort();
157    let mut out = Vec::new();
158    for name in names {
159        let svc = &table.services[name];
160        if !matches!(svc.protocol, ServiceProtocol::Call) {
161            continue;
162        }
163        for h in svc
164            .handlers
165            .iter()
166            .filter(|h| matches!(h.kind, HandlerKind::Call))
167        {
168            let params = h
169                .params
170                .iter()
171                .map(|p| {
172                    sc.seen.clear();
173                    let resolved = resolve_type_ref(&p.type_ref, &entry_scope, &sc.tys);
174                    EntryParam {
175                        name: p.name.name.clone(),
176                        ty: display_or_unknown(resolved, &sc.tys),
177                        shape: shape_of_ref(resolved, unit, &mut sc, &mut Vec::new()),
178                    }
179                })
180                .collect();
181            let returns = display_or_unknown(
182                resolve_type_ref(&h.return_type, &entry_scope, &sc.tys),
183                &sc.tys,
184            );
185            out.push(EntryHandler {
186                unit: unit.to_string(),
187                service: name.clone(),
188                params,
189                returns,
190            });
191        }
192    }
193    out
194}
195
196fn display_or_unknown(id: Option<TyId>, tys: &Types) -> String {
197    id.map(|t| t.display(tys))
198        .unwrap_or_else(|| "?".to_string())
199}
200
201/// `open` holds the (declaring unit, name) of the records/sums being expanded.
202type Open = Vec<(String, String)>;
203
204fn shape_of_ref(
205    id: Option<TyId>,
206    scope_unit: &str,
207    sc: &mut Scopes,
208    open: &mut Open,
209) -> EntryShape {
210    match id {
211        Some(t) => shape_of(t, scope_unit, sc, open),
212        None => EntryShape::Other("?".to_string()),
213    }
214}
215
216/// `scope_unit` is the unit whose scope `id`'s named types are visible in.
217fn shape_of(id: TyId, scope_unit: &str, sc: &mut Scopes, open: &mut Open) -> EntryShape {
218    let ty = sc.tys.get(id);
219    let sub =
220        |t: TyId, sc: &mut Scopes, open: &mut Open| Box::new(shape_of(t, scope_unit, sc, open));
221    match &*ty {
222        Ty::Base(b) => EntryShape::Base(b.name()),
223        Ty::Unit => EntryShape::Unit,
224        Ty::List(t) => EntryShape::List(sub(*t, sc, open)),
225        Ty::Set(t) => EntryShape::Set(sub(*t, sc, open)),
226        Ty::Option(t) => EntryShape::Option(sub(*t, sc, open)),
227        Ty::Map(k, v) => EntryShape::Map(sub(*k, sc, open), sub(*v, sc, open)),
228        Ty::Result(t, e) => EntryShape::Result(sub(*t, sc, open), sub(*e, sc, open)),
229        Ty::Named { name, kind, args } => {
230            if !args.is_empty() {
231                return EntryShape::Other(id.display(&sc.tys));
232            }
233            match kind {
234                NamedKind::Refined(b) => EntryShape::Refined {
235                    name: name.clone(),
236                    base: b.name(),
237                },
238                NamedKind::Opaque(b) => EntryShape::Opaque {
239                    name: name.clone(),
240                    base: b.name(),
241                },
242                NamedKind::Record | NamedKind::Sum => {
243                    let visible = sc.scope(scope_unit);
244                    let Some(decl) = visible.get(name) else {
245                        return EntryShape::Other(id.display(&sc.tys));
246                    };
247                    let home = sc.declaring_unit(name, decl, scope_unit);
248                    let key = (home.clone(), name.clone());
249                    if open.contains(&key) {
250                        return EntryShape::Recursive(name.clone());
251                    }
252                    if open.len() >= MAX_DEPTH || !sc.seen.insert(key.clone()) {
253                        return EntryShape::Named(name.clone());
254                    }
255                    open.push(key);
256                    let decl = decl.clone();
257                    let field = |tr: &TypeRef, sc: &mut Scopes, open: &mut Open| {
258                        let scope = sc.scope(&home);
259                        let r = resolve_type_ref(tr, &scope, &sc.tys);
260                        shape_of_ref(r, &home, sc, open)
261                    };
262                    let shape = match &decl.body {
263                        TypeBody::Record(r) => EntryShape::Record {
264                            name: name.clone(),
265                            fields: r
266                                .fields
267                                .iter()
268                                .map(|f| (f.name.name.clone(), field(&f.type_ref, sc, open)))
269                                .collect(),
270                        },
271                        TypeBody::Sum(s) => EntryShape::Sum {
272                            name: name.clone(),
273                            variants: s
274                                .variants
275                                .iter()
276                                .map(|v| {
277                                    let payload = v
278                                        .payload
279                                        .iter()
280                                        .map(|f| {
281                                            (f.name.name.clone(), field(&f.type_ref, sc, open))
282                                        })
283                                        .collect();
284                                    (v.name.name.clone(), payload)
285                                })
286                                .collect(),
287                        },
288                        TypeBody::Refined { .. } | TypeBody::Opaque { .. } => {
289                            EntryShape::Other(id.display(&sc.tys))
290                        }
291                    };
292                    open.pop();
293                    shape
294                }
295            }
296        }
297        Ty::Error
298        | Ty::Never
299        | Ty::Effect(_)
300        | Ty::HttpResult(_)
301        | Ty::QueueResult
302        | Ty::HttpOutcome(_)
303        | Ty::BoundaryRejection
304        | Ty::Asset
305        | Ty::RequestHeaders
306        | Ty::RequestQuery
307        | Ty::RequestCookies
308        | Ty::TokenClaims
309        | Ty::Query(_)
310        | Ty::Stream(_)
311        | Ty::Connection(_)
312        | Ty::TestConnection(_)
313        | Ty::ValidationError
314        | Ty::DecodeError
315        | Ty::Actor(_)
316        | Ty::ActorSum(_)
317        | Ty::Fn { .. }
318        | Ty::Var(_) => EntryShape::Other(id.display(&sc.tys)),
319    }
320}