1use 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#[derive(Debug, Clone, PartialEq)]
33pub struct EntryHandler {
34 pub unit: String,
36 pub service: String,
37 pub params: Vec<EntryParam>,
38 pub returns: String,
40}
41
42#[derive(Debug, Clone, PartialEq)]
43pub struct EntryParam {
44 pub name: String,
45 pub ty: String,
47 pub shape: EntryShape,
48}
49
50#[derive(Debug, Clone, PartialEq)]
52pub enum EntryShape {
53 Base(&'static str),
55 Refined {
58 name: String,
59 base: &'static str,
60 },
61 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 Recursive(String),
83 Named(String),
87 Other(String),
90}
91
92pub(crate) const MAX_DEPTH: usize = 6;
95
96type Scope = HashMap<String, Arc<TypeDecl>>;
97
98struct Scopes<'a> {
101 unit_tables: &'a HashMap<String, UnitTable>,
102 unit_uses: &'a HashMap<String, Vec<String>>,
103 cache: HashMap<String, Arc<Scope>>,
104 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 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
136pub 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
201type 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
216fn 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}