1use std::borrow::Cow;
13use std::collections::HashMap;
14use std::fmt::Write as _;
15use std::sync::{Arc, Mutex, PoisonError};
16
17use flow_span::{RunId, TaskPath};
18use flow_types::{
19 Body, Decl, DeclId, EnumShape, JsonValueCtor, Members, Mismatch, NameIndex, Nested, OptionCtor,
20 Reason, Role, Settings, Shape, Spelling, StdEnum, Tree, Type, Versions, judge,
21};
22use flow_value::{Value, Variant};
23
24use crate::DecodeError;
25use crate::decode::{CROSSING, Mode};
26use crate::form::{Form, form};
27use crate::json::quote;
28
29#[derive(Clone, Copy, PartialEq, Eq, Debug)]
31pub enum StdForm {
32 Path,
34 Url,
36 MediaType,
38 RunId,
41 TaskPath,
44}
45
46impl StdForm {
47 pub fn of(decl: &Decl) -> Option<StdForm> {
53 let identity = &decl.identity;
54 if *identity.origin.tree() != Tree::Std || identity.version.as_deref() != Some("v1") {
55 return None;
56 }
57 let role = Role::of(identity.origin.module().as_str(), identity.name.as_str())?;
58 [
59 StdForm::Path,
60 StdForm::Url,
61 StdForm::MediaType,
62 StdForm::RunId,
63 StdForm::TaskPath,
64 ]
65 .into_iter()
66 .find(|form| form.role() == role)
67 }
68
69 pub fn role(self) -> Role {
71 match self {
72 StdForm::Path => Role::Path,
73 StdForm::Url => Role::Url,
74 StdForm::MediaType => Role::MediaType,
75 StdForm::RunId => Role::RunId,
76 StdForm::TaskPath => Role::TaskPath,
77 }
78 }
79
80 pub fn normal(self, text: &str) -> Option<String> {
83 match self {
84 StdForm::Path => Some(flow_types::normal_path(text)),
85 StdForm::Url => crate::url::normal_url(text),
86 StdForm::MediaType => crate::media::normal_media_type(text),
87 StdForm::RunId => RunId::parse(text).ok().map(|run| run.to_string()),
88 StdForm::TaskPath => TaskPath::parse(text).ok().map(|task| task.to_string()),
89 }
90 }
91
92 pub fn make(self, text: &str) -> Option<Value> {
97 self.normal(text).map(|normal| Value::Text(normal.into()))
98 }
99
100 pub fn refusal(self, text: &str) -> Option<String> {
104 match self.normal(text) {
105 Some(normal) if normal == text => None,
106 Some(normal) => Some(format!(
107 "is {} written {}, which is not its normal form {}",
108 self.noun(),
109 quote(text),
110 quote(&normal)
111 )),
112 None => Some(format!("is {}, which is not {}", quote(text), self.noun())),
113 }
114 }
115
116 pub fn out_of(form: Option<StdForm>, value: &Value) -> Option<String> {
121 match (form, value) {
122 (Some(form), Value::Text(text)) => form.refusal(text.as_str()),
123 _ => None,
124 }
125 }
126
127 pub fn first_out_of(catalog: &Catalog, ty: &Type, value: &Value) -> Option<String> {
133 let mut pending: Vec<(Type, &Value)> = vec![(ty.clone(), value)];
134 while let Some((ty, value)) = pending.pop() {
135 match (form(catalog, &ty), value) {
136 (Form::Newtype(base, held), _) => {
137 if let Some(problem) = StdForm::out_of(held, value) {
138 return Some(problem);
139 }
140 pending.push((base, value));
141 }
142 (Form::List(item), Value::List(items)) => {
143 pending.extend(items.iter().map(|part| (item.clone(), part)));
144 }
145 (Form::Set(item), Value::Set(items)) => {
146 pending.extend(items.iter().map(|part| (item.clone(), part)));
147 }
148 (Form::Dict(key, item), Value::Dict(entries)) => {
149 for (k, v) in entries.iter() {
150 pending.push((key.clone(), k));
151 pending.push((item.clone(), v));
152 }
153 }
154 (Form::Tuple(parts), Value::Tuple(tuple)) => {
155 pending.extend(parts.iter().cloned().zip(tuple.parts()));
156 }
157 (Form::Record(record), Value::Record(fields)) => {
158 pending.extend(record.fields.into_iter().zip(fields.fields()));
159 }
160 (Form::Enum(shape), Value::Variant(variant)) => {
161 let parts = shape.parts(variant.index()).unwrap_or_default();
162 pending.extend(
163 parts
164 .into_iter()
165 .map(Cow::into_owned)
166 .zip(variant.payload()),
167 );
168 }
169 _ => {}
170 }
171 }
172 None
173 }
174
175 pub(crate) fn noun(self) -> &'static str {
177 match self {
178 StdForm::Path => "a path",
179 StdForm::Url => "a URL",
180 StdForm::MediaType => "a media type",
181 StdForm::RunId => "a run's id",
182 StdForm::TaskPath => "a task's id",
183 }
184 }
185}
186
187#[derive(Clone, Debug)]
190pub struct Catalog {
191 decls: Vec<Decl>,
192 judged: Judged,
193 names: Vec<Names>,
194 option: Bound<OptionCtor>,
195 json: Option<Bound<JsonValueCtor>>,
196}
197
198#[derive(Debug, Default)]
204struct Judged(Mutex<HashMap<(Type, Settings), Option<String>>>);
205
206impl Clone for Judged {
207 fn clone(&self) -> Self {
208 Judged(Mutex::new(self.entries().clone()))
209 }
210}
211
212impl Judged {
213 fn entries(&self) -> std::sync::MutexGuard<'_, HashMap<(Type, Settings), Option<String>>> {
214 self.0.lock().unwrap_or_else(PoisonError::into_inner)
215 }
216}
217
218#[derive(Clone, Debug)]
221struct Names {
222 exact: NameIndex,
223 relaxed: Option<NameIndex>,
226}
227
228impl Names {
229 fn of(decls: &[Decl]) -> Vec<Names> {
230 decls
231 .iter()
232 .map(|decl| Names {
233 exact: NameIndex::of(&decl.body, Spelling::Exact)
234 .expect("a declaration's names are distinct"),
235 relaxed: NameIndex::of(&decl.body, Spelling::Relaxed).ok(),
236 })
237 .collect()
238 }
239}
240
241#[derive(Clone, Debug)]
244pub(crate) struct Bound<C> {
245 pub(crate) shape: Arc<EnumShape>,
246 pub(crate) ctors: StdEnum<C>,
247}
248
249impl<C: Members> Bound<C> {
250 fn of(shape: Arc<EnumShape>) -> Result<Self, Mismatch> {
251 Ok(Bound {
252 ctors: StdEnum::of(&shape)?,
253 shape,
254 })
255 }
256}
257
258pub fn std_enum(role: Role) -> Arc<EnumShape> {
265 match role.shape() {
266 Some(Shape::Enum(shape)) => shape,
267 _ => panic!("std declares no enum for {role:?}"),
268 }
269}
270
271pub trait Params {
274 fn matches(&mut self, index: u32, other: &Catalog, other_ty: &Type) -> bool;
277}
278
279#[derive(Clone, Copy, Debug)]
282pub struct Exact;
283
284impl Params for Exact {
285 fn matches(&mut self, index: u32, _: &Catalog, other_ty: &Type) -> bool {
286 matches!(other_ty, Type::Param(other_index) if *other_index == index)
287 }
288}
289
290#[derive(Clone, Debug, Default)]
294pub struct Fixing {
295 fixed: std::collections::BTreeMap<u32, Type>,
296}
297
298impl Params for Fixing {
299 fn matches(&mut self, index: u32, other: &Catalog, other_ty: &Type) -> bool {
300 match self.fixed.entry(index) {
301 std::collections::btree_map::Entry::Occupied(fixed) => {
302 other.same(fixed.get(), other, other_ty)
303 }
304 std::collections::btree_map::Entry::Vacant(free) => {
305 free.insert(other_ty.clone());
306 true
307 }
308 }
309 }
310}
311
312impl Catalog {
313 pub fn new(
323 decls: Vec<Decl>,
324 option: Arc<EnumShape>,
325 json: Option<Arc<EnumShape>>,
326 ) -> Result<Self, DecodeError> {
327 let lacking = |mismatch: Mismatch| crate::metadata::fail(mismatch.to_string());
328 let option = Bound::of(option).map_err(lacking)?;
329 let json = json.map(Bound::of).transpose().map_err(lacking)?;
330 crate::metadata::regular(&decls)?;
331 Ok(Catalog {
332 names: Names::of(&decls),
333 decls,
334 judged: Judged::default(),
335 option,
336 json,
337 })
338 }
339
340 pub fn std(decls: Vec<Decl>) -> Result<Catalog, DecodeError> {
348 Catalog::new(
349 decls,
350 std_enum(Role::Option),
351 Some(std_enum(Role::JsonValue)),
352 )
353 }
354
355 pub(crate) fn extended(&self, more: Vec<Decl>) -> Catalog {
358 let mut decls = self.decls.clone();
359 decls.extend(more);
360 Catalog {
361 names: Names::of(&decls),
362 decls,
363 judged: Judged::default(),
364 option: self.option.clone(),
365 json: self.json.clone(),
366 }
367 }
368
369 pub fn decl(&self, id: DeclId) -> &Decl {
375 &self.decls[crate::bytes::index(id.0)]
376 }
377
378 pub fn decls(&self) -> impl ExactSizeIterator<Item = (DeclId, &Decl)> {
384 self.decls.iter().enumerate().map(|(index, decl)| {
385 (
386 DeclId(u32::try_from(index).expect("a catalog fits 32-bit ids")),
387 decl,
388 )
389 })
390 }
391
392 pub fn same(&self, ty: &Type, other: &Catalog, other_ty: &Type) -> bool {
397 self.matches(ty, other, other_ty, &mut Exact)
398 }
399
400 pub fn matches(
404 &self,
405 ty: &Type,
406 other: &Catalog,
407 other_ty: &Type,
408 params: &mut impl Params,
409 ) -> bool {
410 let mut todo = vec![(ty, other_ty)];
411 while let Some((ty, other_ty)) = todo.pop() {
412 if let Type::Param(index) = ty {
413 if !params.matches(*index, other, other_ty) {
414 return false;
415 }
416 continue;
417 }
418 let named_alike = match (ty, other_ty) {
419 (Type::Named(decl, _), Type::Named(other_decl, _)) => {
420 let (declared, other_declared) = (self.decl(*decl), other.decl(*other_decl));
421 declared.identity == other_declared.identity
422 && declared.lexical_ordinal == other_declared.lexical_ordinal
423 }
424 (Type::NotData, _) => false,
425 _ => true,
426 };
427 let alike = named_alike
428 && std::mem::discriminant(ty) == std::mem::discriminant(other_ty)
429 && ty.parts().count() == other_ty.parts().count();
430 if !alike {
431 return false;
432 }
433 todo.extend(ty.parts().rev().zip(other_ty.parts().rev()));
434 }
435 true
436 }
437
438 pub fn erase<'t>(&self, ty: &'t Type) -> Cow<'t, Type> {
445 let mut current = Cow::Borrowed(ty);
446 for _ in 0..=self.decls.len() {
447 let Type::Named(decl, args) = &*current else {
448 return current;
449 };
450 let Body::Newtype(base) = &self.decl(*decl).body else {
451 return current;
452 };
453 current = Cow::Owned(base.subst(args));
454 }
455 Cow::Owned(Type::NotData)
456 }
457
458 pub fn std_form(&self, ty: &Type) -> Option<StdForm> {
462 let mut current = Cow::Borrowed(ty);
463 for _ in 0..=self.decls.len() {
464 let Type::Named(decl, args) = &*current else {
465 break;
466 };
467 let decl = self.decl(*decl);
468 if let Some(form) = StdForm::of(decl) {
469 return Some(form);
470 }
471 let Body::Newtype(base) = &decl.body else {
472 break;
473 };
474 current = Cow::Owned(base.subst(args));
475 }
476 None
477 }
478
479 pub(crate) fn problem(&self, ty: &Type, settings: Settings) -> Option<String> {
483 let key = (ty.clone(), settings);
484 if let Some(problem) = self.judged.entries().get(&key) {
485 return problem.clone();
486 }
487 let mut unbound = false;
488 let problem = match judge(&self.decls, ty, settings, &mut |_, _| unbound = true) {
489 Some(refusal) => Some(match refusal.reason {
490 Reason::Opaque => format!(
491 "has the type {}, which is opaque, so it can't be decoded",
492 self.declared(&refusal.part)
493 ),
494 Reason::Host => format!(
495 "has the host type {}, which a run's input can't carry",
496 self.declared(&refusal.part)
497 ),
498 Reason::SharedKey => {
499 let decl = self.decl_of(&refusal.part);
500 let shared = NameIndex::of(&decl.body, Spelling::Relaxed).expect_err(
501 "the judge refuses only a declaration whose relaxed keys collide",
502 );
503 format!(
504 "has the type {}, whose names `{}` and `{}` share the relaxed key `{}`",
505 decl.identity, shared.first, shared.second, shared.key
506 )
507 }
508 Reason::JsonValue | Reason::OptionalJson => {
509 "has an Option<json.Value> part, which cannot cross a boundary".into()
510 }
511 Reason::Function | Reason::Task | Reason::NotData => no_encoding(),
512 }),
513 None => unbound.then(no_encoding),
514 };
515 self.judged.entries().insert(key, problem.clone());
516 problem
517 }
518
519 pub(crate) fn names(&self, decl: DeclId, mode: Mode) -> &NameIndex {
526 let names = &self.names[crate::bytes::index(decl.0)];
527 match mode.spelling() {
528 Spelling::Exact => &names.exact,
529 Spelling::Relaxed => names
530 .relaxed
531 .as_ref()
532 .expect("judging refuses a declaration whose relaxed keys collide"),
533 }
534 }
535
536 fn declared(&self, part: &Type) -> &flow_types::Identity {
538 &self.decl_of(part).identity
539 }
540
541 fn decl_of(&self, part: &Type) -> &Decl {
543 let Type::Named(decl, _) = part else {
544 unreachable!("only a declared type is refused for what it declares")
545 };
546 self.decl(*decl)
547 }
548
549 pub(crate) fn option(&self) -> &Bound<OptionCtor> {
550 &self.option
551 }
552
553 pub fn none(&self) -> Value {
560 Value::Variant(
561 Variant::new(
562 Arc::clone(&self.option.shape),
563 self.option.ctors.index(OptionCtor::None),
564 Vec::new(),
565 )
566 .expect("None carries nothing"),
567 )
568 }
569
570 pub fn some(&self, value: Value) -> Value {
576 Value::Variant(
577 Variant::new(
578 Arc::clone(&self.option.shape),
579 self.option.ctors.index(OptionCtor::Some),
580 vec![value],
581 )
582 .expect("Some carries one value"),
583 )
584 }
585
586 pub(crate) fn json(&self) -> &Bound<JsonValueCtor> {
587 self.json
588 .as_ref()
589 .expect("a program that names json.Value has std's json module")
590 }
591
592 pub fn name(&self, ty: &Type) -> String {
595 self.written(ty, Versions::Shown)
596 }
597
598 pub(crate) fn written(&self, ty: &Type, versions: Versions) -> String {
604 enum Next<'t> {
605 Type(&'t Type),
606 Text(&'static str),
607 }
608 let mut out = String::new();
609 let mut todo = vec![Next::Type(ty)];
610 while let Some(next) = todo.pop() {
611 let ty = match next {
612 Next::Text(text) => {
613 out.push_str(text);
614 continue;
615 }
616 Next::Type(ty) => ty,
617 };
618 let (open, close) = match ty {
619 Type::Int => ("Int", ""),
620 Type::Decimal => ("Decimal", ""),
621 Type::Bool => ("Bool", ""),
622 Type::Text => ("Text", ""),
623 Type::Bytes => ("Bytes", ""),
624 Type::Duration => ("Duration", ""),
625 Type::Instant => ("Instant", ""),
626 Type::Unit => ("Unit", ""),
627 Type::Never => ("Never", ""),
628 Type::Json => ("json.Value", ""),
629 Type::List(_) => ("List<", ">"),
630 Type::Set(_) => ("Set<", ">"),
631 Type::Option(_) => ("Option<", ">"),
632 Type::Task(_) => ("task.Task<", ">"),
633 Type::Dict(..) => ("Dict<", ">"),
634 Type::Tuple(_) | Type::Function { .. } => ("(", ""),
635 Type::Named(decl, args) => {
636 let declared = self.decl(*decl);
637 out.push_str(&declared.identity.written(versions));
638 if declared.lexical_ordinal > 1 {
639 write!(out, "#{}", declared.lexical_ordinal).expect("writing to a string");
640 }
641 if args.is_empty() {
642 ("", "")
643 } else {
644 ("<", ">")
645 }
646 }
647 Type::Param(index) => {
648 write!(out, "${index}").expect("writing to a string");
649 ("", "")
650 }
651 Type::NotData => ("a type that is not data", ""),
652 };
653 out.push_str(open);
654 todo.push(Next::Text(close));
655 let mut parts: Vec<&Type> = ty.parts().collect();
656 if let Type::Function { .. } = ty {
657 let result = parts.pop().expect("a function type has a result");
658 todo.push(Next::Type(result));
659 todo.push(Next::Text(") -> "));
660 } else if let Type::Tuple(_) = ty {
661 todo.push(Next::Text(")"));
662 }
663 for (at, part) in parts.into_iter().enumerate().rev() {
664 todo.push(Next::Type(part));
665 if at > 0 {
666 todo.push(Next::Text(", "));
667 }
668 }
669 }
670 out
671 }
672}
673
674fn no_encoding() -> String {
675 "has a type with no encoding".into()
676}
677
678pub fn crossable(catalog: &Catalog, ty: &Type) -> Result<(), DecodeError> {
687 crate::decodable(catalog, ty, CROSSING)
688}