1use std::collections::{HashMap, HashSet};
26
27use crate::names::{NameIndex, Spelling};
28
29use crate::nested::{Fold, Nested};
30use crate::types::{Body, Decl, DeclId, Type};
31
32#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
37pub enum Crossing {
38 #[default]
40 Stays,
41 Crosses,
43 HeldByOption,
47}
48
49#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
51pub struct Settings {
52 pub data: bool,
56 pub host_ok: bool,
58 pub no_opaque: bool,
60 pub crossing: Crossing,
62 pub names: Spelling,
66}
67
68#[derive(Clone, Copy, PartialEq, Eq, Debug)]
70pub enum Reason {
71 Function,
73 Host,
75 Task,
77 NotData,
79 Opaque,
81 JsonValue,
84 OptionalJson,
86 SharedKey,
89}
90
91#[derive(Clone, Copy, PartialEq, Eq, Debug)]
93pub enum Step {
94 Field {
96 decl: DeclId,
98 index: usize,
100 },
101 Payload {
103 decl: DeclId,
105 ctor: usize,
107 index: usize,
109 },
110 Base(DeclId),
112 Index(usize),
114 Element,
116}
117
118#[derive(Clone, PartialEq, Eq, Debug)]
121pub struct Refusal {
122 pub part: Type,
124 pub reason: Reason,
126 pub path: Vec<Step>,
128}
129
130pub fn judge(
138 decls: &[Decl],
139 ty: &Type,
140 settings: Settings,
141 on_param: &mut dyn FnMut(u32, Settings),
142) -> Option<Refusal> {
143 Walk::new(decls, on_param).judge(ty, settings)
144}
145
146struct Walk<'a> {
152 decls: &'a [Decl],
153 on_param: &'a mut dyn FnMut(u32, Settings),
154 nodes: Vec<Node>,
155 ids: HashMap<Node, Id>,
156 walked: HashSet<(Id, Crossing)>,
157 #[cfg(test)]
159 steps: usize,
160}
161
162#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
164struct Id(usize);
165
166#[derive(Clone, PartialEq, Eq, Hash, Debug)]
168enum Node {
169 Leaf(Type),
172 List(Id),
173 Set(Id),
174 Option(Id),
175 Task(Id),
176 Dict(Id, Id),
177 Tuple(Vec<Id>),
178 Named(DeclId, Vec<Id>),
179 Param(u32),
180 Function(Vec<Id>, Id),
181}
182
183type Part = (Option<Step>, Id, Settings);
186
187struct Found {
189 part: Id,
190 reason: Reason,
191 path: Vec<Step>,
192}
193
194enum Entered {
196 Refused(Found),
198 Parts(Vec<Part>, OnRefusal),
200}
201
202enum OnRefusal {
204 Through,
206 Optional(Id),
209}
210
211struct Open {
213 parts: std::vec::IntoIter<Part>,
214 step: Option<Step>,
216 on_refusal: OnRefusal,
217}
218
219impl Open {
220 fn refused(self, mut found: Found) -> Found {
222 found.path.splice(0..0, self.step);
223 match self.on_refusal {
224 OnRefusal::Optional(part) if found.reason == Reason::JsonValue => Found {
225 part,
226 reason: Reason::OptionalJson,
227 path: Vec::new(),
228 },
229 OnRefusal::Optional(_) | OnRefusal::Through => found,
230 }
231 }
232}
233
234impl<'a> Walk<'a> {
235 fn new(decls: &'a [Decl], on_param: &'a mut dyn FnMut(u32, Settings)) -> Self {
236 Walk {
237 decls,
238 on_param,
239 nodes: Vec::new(),
240 ids: HashMap::new(),
241 walked: HashSet::new(),
242 #[cfg(test)]
243 steps: 0,
244 }
245 }
246
247 fn judge(&mut self, ty: &Type, settings: Settings) -> Option<Refusal> {
249 let root = self.intern(ty, &[]);
250 let mut open: Vec<Open> = Vec::new();
251 let mut entered = self.enter(root, settings);
252 loop {
253 match entered {
254 Entered::Refused(mut found) => {
255 while let Some(left) = open.pop() {
256 found = left.refused(found);
257 }
258 return Some(Refusal {
259 part: self.render(found.part),
260 reason: found.reason,
261 path: found.path,
262 });
263 }
264 Entered::Parts(parts, on_refusal) => open.push(Open {
265 parts: parts.into_iter(),
266 step: None,
267 on_refusal,
268 }),
269 }
270 entered = loop {
271 let top = open.last_mut()?;
272 if let Some((step, part, settings)) = top.parts.next() {
273 top.step = step;
274 break self.enter(part, settings);
275 }
276 open.pop();
277 };
278 }
279 }
280
281 fn intern(&mut self, ty: &Type, args: &[Id]) -> Id {
284 ty.fold(&mut Interning { walk: self, args })
285 }
286
287 fn render(&self, id: Id) -> Type {
289 let mut todo = vec![(id, false)];
290 let mut done: Vec<Type> = Vec::new();
291 while let Some((id, parts_done)) = todo.pop() {
292 let node = &self.nodes[id.0];
293 let parts = node.parts();
294 if parts_done || parts.is_empty() {
295 let built = done.split_off(done.len() - parts.len());
296 done.push(node.ty(built));
297 } else {
298 todo.push((id, true));
299 todo.extend(parts.into_iter().rev().map(|part| (part, false)));
300 }
301 }
302 done.pop().expect("rendering a type yields it")
303 }
304
305 fn enter(&mut self, id: Id, settings: Settings) -> Entered {
307 #[cfg(test)]
308 {
309 self.steps += 1;
310 }
311 let inner = inner(settings);
312 match self.nodes[id.0].clone() {
313 Node::Param(index) => {
314 (self.on_param)(index, settings);
315 through(Vec::new(), inner)
316 }
317 Node::Leaf(Type::NotData) if settings.data => refused(id, Reason::NotData),
318 Node::Task(_) if settings.data => refused(id, Reason::Task),
319 Node::Leaf(Type::Json) if settings.crossing == Crossing::HeldByOption => {
320 refused(id, Reason::JsonValue)
321 }
322 Node::Function(..) if settings.data => refused(id, Reason::Function),
323 Node::Function(..)
324 | Node::Task(_)
325 | Node::List(_)
326 | Node::Set(_)
327 | Node::Option(_)
328 | Node::Dict(..)
329 | Node::Tuple(_)
330 if !self.walked.insert((id, inner.crossing)) =>
331 {
332 through(Vec::new(), inner)
333 }
334 Node::Leaf(_) | Node::Function(..) | Node::Task(_) => through(Vec::new(), inner),
335 Node::List(item) | Node::Set(item) => through(vec![(Some(Step::Element), item)], inner),
336 Node::Dict(key, value) => through(
337 vec![(Some(Step::Element), key), (Some(Step::Element), value)],
338 inner,
339 ),
340 Node::Tuple(parts) => through(
341 parts
342 .into_iter()
343 .enumerate()
344 .map(|(position, part)| (Some(Step::Index(position)), part))
345 .collect(),
346 inner,
347 ),
348 Node::Option(held) if settings.crossing != Crossing::Stays => {
350 let held_by = Settings {
351 crossing: Crossing::HeldByOption,
352 ..settings
353 };
354 Entered::Parts(vec![(None, held, held_by)], OnRefusal::Optional(id))
355 }
356 Node::Option(held) => through(vec![(None, held)], inner),
357 Node::Named(decl, args) => self.declared(id, decl, &args, settings),
358 }
359 }
360
361 fn declared(&mut self, id: Id, decl: DeclId, args: &[Id], settings: Settings) -> Entered {
364 let inner = inner(settings);
365 let declared = &self.decls[crate::index(decl.0)];
366 match &declared.body {
367 Body::Host if !settings.host_ok => refused(id, Reason::Host),
368 Body::NonData if settings.data => refused(id, Reason::NotData),
369 Body::Record(..) | Body::Enum(..) | Body::Newtype(_)
370 if settings.no_opaque && declared.opaque =>
371 {
372 refused(id, Reason::Opaque)
373 }
374 Body::Record(..) | Body::Enum(..)
375 if settings.names == Spelling::Relaxed
376 && NameIndex::of(&declared.body, Spelling::Relaxed).is_err() =>
377 {
378 refused(id, Reason::SharedKey)
379 }
380 Body::Newtype(_) if !self.walked.insert((id, settings.crossing)) => {
381 through(Vec::new(), inner)
382 }
383 Body::Host | Body::NonData | Body::Record(..) | Body::Enum(..)
384 if !self.walked.insert((id, inner.crossing)) =>
385 {
386 through(Vec::new(), inner)
387 }
388 Body::Host => through(
389 args.iter().map(|arg| (Some(Step::Element), *arg)).collect(),
390 inner,
391 ),
392 Body::NonData => through(Vec::new(), inner),
393 Body::Newtype(base) => {
397 let base = self.intern(base, args);
398 Entered::Parts(
399 vec![(Some(Step::Base(decl)), base, settings)],
400 OnRefusal::Through,
401 )
402 }
403 Body::Record(_, fields) => {
404 let mut parts = Vec::with_capacity(fields.len());
405 for (index, field) in fields.iter().enumerate() {
406 parts.push((Some(Step::Field { decl, index }), self.intern(field, args)));
407 }
408 through(parts, inner)
409 }
410 Body::Enum(_, ctors) => {
411 let mut parts = Vec::new();
412 for (ctor, payload) in ctors.iter().enumerate() {
413 for (index, part) in payload.iter().enumerate() {
414 let step = Step::Payload { decl, ctor, index };
415 parts.push((Some(step), self.intern(part, args)));
416 }
417 }
418 through(parts, inner)
419 }
420 }
421 }
422}
423
424impl Node {
425 fn parts(&self) -> Vec<Id> {
427 match self {
428 Node::Leaf(_) | Node::Param(_) => Vec::new(),
429 Node::List(item) | Node::Set(item) | Node::Option(item) | Node::Task(item) => {
430 vec![*item]
431 }
432 Node::Dict(key, value) => vec![*key, *value],
433 Node::Tuple(parts) | Node::Named(_, parts) => parts.clone(),
434 Node::Function(params, result) => params
435 .iter()
436 .copied()
437 .chain(std::iter::once(*result))
438 .collect(),
439 }
440 }
441
442 fn ty(&self, mut parts: Vec<Type>) -> Type {
444 let mut part = || Box::new(parts.remove(0));
445 match self {
446 Node::Leaf(leaf) => leaf.clone(),
447 Node::Param(index) => Type::Param(*index),
448 Node::List(_) => Type::List(part()),
449 Node::Set(_) => Type::Set(part()),
450 Node::Option(_) => Type::Option(part()),
451 Node::Task(_) => Type::Task(part()),
452 Node::Dict(..) => Type::Dict(part(), part()),
453 Node::Tuple(_) => Type::Tuple(parts),
454 Node::Named(decl, _) => Type::Named(*decl, parts),
455 Node::Function(..) => {
456 let result = Box::new(parts.pop().expect("a function has a result"));
457 Type::Function {
458 params: parts,
459 result,
460 }
461 }
462 }
463 }
464}
465
466struct Interning<'w, 'a> {
469 walk: &'w mut Walk<'a>,
470 args: &'w [Id],
471}
472
473impl Fold<Type> for Interning<'_, '_> {
474 type Made = Id;
475
476 fn open(&mut self, ty: &Type) -> Option<Id> {
477 let Type::Param(index) = ty else {
478 return None;
479 };
480 self.args.get(crate::index(*index)).copied()
481 }
482
483 fn join(&mut self, ty: &Type, mut part: impl FnMut(&mut Self, &Type) -> Id) -> Id {
484 let parts = ty.parts().map(|ty| part(self, ty)).collect();
485 let walk = &mut *self.walk;
486 let next = Id(walk.nodes.len());
487 *walk.ids.entry(node(ty, parts)).or_insert_with_key(|node| {
488 walk.nodes.push(node.clone());
489 next
490 })
491 }
492}
493
494fn node(ty: &Type, mut parts: Vec<Id>) -> Node {
496 match ty {
497 Type::List(_) => Node::List(parts[0]),
498 Type::Set(_) => Node::Set(parts[0]),
499 Type::Option(_) => Node::Option(parts[0]),
500 Type::Task(_) => Node::Task(parts[0]),
501 Type::Dict(..) => Node::Dict(parts[0], parts[1]),
502 Type::Tuple(_) => Node::Tuple(parts),
503 Type::Named(decl, _) => Node::Named(*decl, parts),
504 Type::Function { .. } => {
505 let result = parts.pop().expect("a function has a result");
506 Node::Function(parts, result)
507 }
508 Type::Param(index) => Node::Param(*index),
509 Type::Int
510 | Type::Decimal
511 | Type::Bool
512 | Type::Text
513 | Type::Bytes
514 | Type::Duration
515 | Type::Instant
516 | Type::Unit
517 | Type::Never
518 | Type::Json
519 | Type::NotData => Node::Leaf(ty.clone()),
520 }
521}
522
523fn inner(settings: Settings) -> Settings {
526 Settings {
527 crossing: settings.crossing.min(Crossing::Crosses),
528 ..settings
529 }
530}
531
532fn refused(id: Id, reason: Reason) -> Entered {
534 Entered::Refused(Found {
535 part: id,
536 reason,
537 path: Vec::new(),
538 })
539}
540
541fn through(parts: Vec<(Option<Step>, Id)>, inner: Settings) -> Entered {
543 let parts = parts
544 .into_iter()
545 .map(|(step, part)| (step, part, inner))
546 .collect();
547 Entered::Parts(parts, OnRefusal::Through)
548}
549
550#[cfg(test)]
551#[cfg_attr(coverage, coverage(off))]
552mod tests {
553 use super::{Crossing, Settings, Spelling, Walk};
554 use crate::{Body, Decl, DeclId, Identity, ModulePath, RecordShape, Segments, Tree, Type};
555
556 fn doubling(n: u32) -> Vec<Decl> {
560 (0..n)
561 .map(|at| {
562 let field = if at + 1 == n {
563 Type::Param(0)
564 } else {
565 Type::Named(
566 DeclId(at + 1),
567 vec![Type::Tuple(vec![Type::Param(0), Type::Param(0)])],
568 )
569 };
570 Decl {
571 lexical_ordinal: 1,
572 identity: Identity {
573 origin: ModulePath::new(
574 Tree::Local,
575 None,
576 Segments::from_names(["main"]).expect("a test path is a path"),
577 ),
578 version: None,
579 name: format!("D{at}"),
580 },
581 doc: None,
582 params: vec!["T".into()],
583 members: Vec::new(),
584 opaque: false,
585 body: Body::Record(RecordShape::new(&format!("D{at}"), ["x"]), vec![field]),
586 }
587 })
588 .collect()
589 }
590
591 fn steps(n: u32) -> usize {
593 let decls = doubling(n);
594 let mut on_param = |_, _| {};
595 let mut walk = Walk::new(&decls, &mut on_param);
596 let settings = Settings {
597 data: true,
598 host_ok: true,
599 no_opaque: true,
600 crossing: Crossing::Crosses,
601 names: Spelling::Exact,
602 };
603 assert!(
604 walk.judge(&Type::Named(DeclId(0), vec![Type::Int]), settings)
605 .is_none()
606 );
607 walk.steps
608 }
609
610 #[test]
611 fn a_chain_doubling_its_argument_is_judged_in_steps_linear_in_its_length() {
612 for n in 1..=30 {
613 let steps = steps(n);
614 assert!(
615 steps <= 8 * crate::index(n),
616 "{n} declarations took {steps} steps"
617 );
618 }
619 }
620}