1use std::hash::{Hash, Hasher};
11
12use flow_types::Identity as Declared;
13use flow_types::{Fold, ModulePath, Nested, Segments, SegmentsError, Tree};
14
15use flow_value::Int;
16
17use crate::wire;
18
19wire! {
20 #[derive(Debug)]
23 pub enum Term {
24 Int,
26 Decimal,
28 Bool,
30 Text,
32 Bytes,
34 Duration,
36 Instant,
38 Unit,
40 Never,
42 JsonValue,
44 List(Box<Term>),
46 Set(Box<Term>),
48 Option(Box<Term>),
50 Task(Box<Term>),
52 Dict(Box<Term>, Box<Term>),
54 Tuple(Vec<Term>),
56 Function {
58 params: Vec<Term>,
60 result: Box<Term>,
62 },
63 Named {
65 declaration: Int,
67 args: Vec<Term>,
69 },
70 Param {
72 owner: Owner,
74 index: Int,
76 },
77 }
78}
79
80wire! {
81 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
83 pub enum Owner {
84 Tool,
86 Declaration(Int),
88 }
89}
90
91wire! {
92 #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
96 pub struct Identity {
97 pub library: Option<Library>,
100 pub module: String,
102 pub name: String,
104 }
105}
106
107wire! {
108 #[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
110 pub struct Library {
111 pub address: String,
114 pub version: Option<String>,
117 }
118}
119
120wire! {
121 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
123 pub struct Template {
124 pub name: String,
126 pub identity: Identity,
128 pub lexical_ordinal: Int,
130 pub generic: Vec<String>,
132 pub opaque: bool,
134 pub doc: Option<String>,
136 pub body: Body,
138 }
139}
140
141wire! {
142 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
144 pub enum Body {
145 Record(Vec<Field>),
147 Enum(Vec<Constructor>),
149 Newtype(Term),
151 Host,
153 Nondata,
155 }
156}
157
158wire! {
159 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
161 pub struct Field {
162 pub name: String,
164 pub ty: Term,
166 pub doc: Option<String>,
168 }
169}
170
171wire! {
172 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
174 pub struct Constructor {
175 pub name: String,
177 pub doc: Option<String>,
179 pub payload: Payload,
181 }
182}
183
184wire! {
185 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
187 pub enum Payload {
188 Empty,
190 Positional(Vec<Term>),
192 Named(Vec<Field>),
194 }
195}
196
197wire! {
198 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
200 pub struct TypeSpec {
201 pub generic: Vec<String>,
203 pub params: Vec<(String, Term)>,
205 pub result: Term,
207 pub declarations: Vec<Template>,
209 }
210}
211
212wire! {
213 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
215 pub struct CallTypes {
216 pub bindings: Vec<(String, Term)>,
218 pub params: Vec<(String, Term)>,
220 pub result: Term,
222 pub declarations: Vec<Template>,
224 }
225}
226
227wire! {
228 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
231 pub struct ResultType {
232 pub result: Term,
234 pub declarations: Vec<Template>,
236 }
237}
238
239wire! {
240 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
242 pub struct Program {
243 pub root: String,
245 pub tools: Vec<(Identity, TypeSpec)>,
248 pub types: Vec<Template>,
250 }
251}
252
253impl Identity {
254 pub fn of(identity: &Declared) -> Self {
256 let origin = &identity.origin;
257 let library = match (origin.tree(), origin.library()) {
258 (Tree::Local, None) => None,
259 (Tree::Std | Tree::Repository(_) | Tree::Local, _) => Some(Library {
260 address: origin.address(),
261 version: identity.version.clone(),
262 }),
263 };
264 Identity {
265 library,
266 module: origin.module().to_string(),
267 name: identity.name.clone(),
268 }
269 }
270
271 pub fn identity(&self) -> Result<Declared, SegmentsError> {
282 let module = self.module.parse()?;
283 let origin = match &self.library {
284 None => ModulePath::new(Tree::Local, None, module),
285 Some(Library {
286 address,
287 version: Some(_),
288 }) if address == Tree::STD => ModulePath::new(Tree::Std, None, module),
289 Some(Library {
290 address,
291 version: Some(_),
292 }) => ModulePath::new(Tree::Repository(address.clone()), None, module),
293 Some(Library {
294 address,
295 version: None,
296 }) if address == "." => ModulePath::new(Tree::Local, Some(Segments::root()), module),
297 Some(Library {
298 address,
299 version: None,
300 }) => ModulePath::new(Tree::Local, Some(address.parse()?), module),
301 };
302 Ok(Declared {
303 origin,
304 version: self
305 .library
306 .as_ref()
307 .and_then(|library| library.version.clone()),
308 name: self.name.clone(),
309 })
310 }
311}
312
313impl Nested for Term {
316 const LEAF: Term = Term::Int;
317
318 fn parts(&self) -> impl DoubleEndedIterator<Item = &Term> {
321 let (list, boxed): (&[Term], [Option<&Term>; 2]) = match self {
322 Term::List(item) | Term::Set(item) | Term::Option(item) | Term::Task(item) => {
323 (&[], [Some(item), None])
324 }
325 Term::Dict(key, value) => (&[], [Some(key), Some(value)]),
326 Term::Tuple(parts) | Term::Named { args: parts, .. } => (parts, [None, None]),
327 Term::Function { params, result } => (params, [Some(result), None]),
328 Term::Int
329 | Term::Decimal
330 | Term::Bool
331 | Term::Text
332 | Term::Bytes
333 | Term::Duration
334 | Term::Instant
335 | Term::Unit
336 | Term::Never
337 | Term::JsonValue
338 | Term::Param { .. } => (&[], [None, None]),
339 };
340 list.iter().chain(boxed.into_iter().flatten())
341 }
342
343 fn parts_mut(&mut self) -> impl Iterator<Item = &mut Term> {
344 let (list, boxed): (&mut [Term], [Option<&mut Box<Term>>; 2]) = match self {
345 Term::List(item) | Term::Set(item) | Term::Option(item) | Term::Task(item) => {
346 (&mut [], [Some(item), None])
347 }
348 Term::Dict(key, value) => (&mut [], [Some(key), Some(value)]),
349 Term::Tuple(parts) | Term::Named { args: parts, .. } => (parts, [None, None]),
350 Term::Function { params, result } => (params, [Some(result), None]),
351 Term::Int
352 | Term::Decimal
353 | Term::Bool
354 | Term::Text
355 | Term::Bytes
356 | Term::Duration
357 | Term::Instant
358 | Term::Unit
359 | Term::Never
360 | Term::JsonValue
361 | Term::Param { .. } => (&mut [], [None, None]),
362 };
363 list.iter_mut()
364 .chain(boxed.into_iter().flatten().map(|part| &mut **part))
365 }
366}
367
368impl Term {
369 fn map_parts(&self, mut part: impl FnMut(&Term) -> Term) -> Term {
372 match self {
373 Term::List(item) => Term::List(Box::new(part(item))),
374 Term::Set(item) => Term::Set(Box::new(part(item))),
375 Term::Option(item) => Term::Option(Box::new(part(item))),
376 Term::Task(item) => Term::Task(Box::new(part(item))),
377 Term::Dict(key, value) => {
378 let key = Box::new(part(key));
379 Term::Dict(key, Box::new(part(value)))
380 }
381 Term::Tuple(parts) => Term::Tuple(parts.iter().map(part).collect()),
382 Term::Named { declaration, args } => Term::Named {
383 declaration: declaration.clone(),
384 args: args.iter().map(part).collect(),
385 },
386 Term::Function { params, result } => {
387 let params = params.iter().map(&mut part).collect();
388 Term::Function {
389 params,
390 result: Box::new(part(result)),
391 }
392 }
393 Term::Int => Term::Int,
394 Term::Decimal => Term::Decimal,
395 Term::Bool => Term::Bool,
396 Term::Text => Term::Text,
397 Term::Bytes => Term::Bytes,
398 Term::Duration => Term::Duration,
399 Term::Instant => Term::Instant,
400 Term::Unit => Term::Unit,
401 Term::Never => Term::Never,
402 Term::JsonValue => Term::JsonValue,
403 Term::Param { owner, index } => Term::Param {
404 owner: owner.clone(),
405 index: index.clone(),
406 },
407 }
408 }
409
410 fn same_node(&self, other: &Term) -> bool {
413 match (self, other) {
414 (
415 Term::Named {
416 declaration: a,
417 args: xs,
418 },
419 Term::Named {
420 declaration: b,
421 args: ys,
422 },
423 ) => a == b && xs.len() == ys.len(),
424 (Term::Tuple(xs), Term::Tuple(ys))
425 | (Term::Function { params: xs, .. }, Term::Function { params: ys, .. }) => {
426 xs.len() == ys.len()
427 }
428 (Term::Param { owner: a, index: i }, Term::Param { owner: b, index: j }) => {
429 a == b && i == j
430 }
431 _ => std::mem::discriminant(self) == std::mem::discriminant(other),
432 }
433 }
434}
435
436struct Cloning;
438
439impl Fold<Term> for Cloning {
440 type Made = Term;
441
442 fn open(&mut self, _: &Term) -> Option<Term> {
443 None
444 }
445
446 fn join(&mut self, term: &Term, mut part: impl FnMut(&mut Self, &Term) -> Term) -> Term {
447 term.map_parts(|term| part(self, term))
448 }
449}
450
451impl Clone for Term {
452 fn clone(&self) -> Term {
453 self.fold(&mut Cloning)
454 }
455}
456
457impl PartialEq for Term {
460 fn eq(&self, other: &Term) -> bool {
461 self.same_tree(other, Term::same_node)
462 }
463}
464
465impl Eq for Term {}
466
467impl Hash for Term {
470 fn hash<H: Hasher>(&self, state: &mut H) {
471 self.fold(&mut Hashing(state));
472 }
473}
474
475struct Hashing<'h, H>(&'h mut H);
477
478impl<H: Hasher> Fold<Term> for Hashing<'_, H> {
479 type Made = ();
480
481 fn open(&mut self, term: &Term) -> Option<()> {
482 std::mem::discriminant(term).hash(self.0);
483 match term {
484 Term::Named { declaration, .. } => declaration.hash(self.0),
485 Term::Param { owner, index } => {
486 owner.hash(self.0);
487 index.hash(self.0);
488 }
489 Term::Int
490 | Term::Decimal
491 | Term::Bool
492 | Term::Text
493 | Term::Bytes
494 | Term::Duration
495 | Term::Instant
496 | Term::Unit
497 | Term::Never
498 | Term::JsonValue
499 | Term::List(_)
500 | Term::Set(_)
501 | Term::Option(_)
502 | Term::Task(_)
503 | Term::Dict(_, _)
504 | Term::Tuple(_)
505 | Term::Function { .. } => {}
506 }
507 term.parts().next().is_none().then_some(())
508 }
509
510 fn join(&mut self, term: &Term, mut part: impl FnMut(&mut Self, &Term)) {
511 for term in term.parts() {
512 part(self, term);
513 }
514 }
515}
516
517impl Drop for Term {
518 fn drop(&mut self) {
519 self.free_parts();
520 }
521}
522
523#[cfg(test)]
524#[cfg_attr(coverage, coverage(off))]
525mod tests;