tc_scalar/
lib.rs

1//! Immutable values which always reside entirely in memory
2
3use std::collections::HashSet;
4use std::convert::{TryFrom, TryInto};
5use std::fmt;
6use std::ops::{Bound, Deref, DerefMut};
7use std::str::FromStr;
8
9use async_hash::{Digest, Hash, Output};
10use async_trait::async_trait;
11use bytes::Bytes;
12use destream::{de, en};
13use futures::future::TryFutureExt;
14use futures::stream::{self, StreamExt, TryStreamExt};
15use get_size::GetSize;
16use log::{debug, warn};
17use safecast::{as_type, Match, TryCastFrom, TryCastInto};
18use smallvec::SmallVec;
19
20use tc_error::*;
21use tc_transact::public::{Public, StateInstance, ToState};
22use tc_value::{Float, Host, Link, Number, TCString, Value, ValueType};
23use tcgeneric::*;
24
25pub use op::*;
26pub use reference::*;
27pub use tc_value as value;
28
29pub mod op;
30pub mod public;
31pub mod reference;
32
33const ERR_NO_SELF: &str = "Op context has no $self--consider using a method instead";
34const PREFIX: PathLabel = path_label(&["state", "scalar"]);
35
36/// The label of an instance in its own method context
37pub const SELF: Label = label("self");
38
39/// The [`Class`] of a [`Scalar`].
40#[derive(Clone, Copy, Eq, PartialEq)]
41pub enum ScalarType {
42    Cluster,
43    Map,
44    Op(OpDefType),
45    Range,
46    Ref(RefType),
47    Tuple,
48    Value(ValueType),
49}
50
51impl Class for ScalarType {}
52
53impl NativeClass for ScalarType {
54    fn from_path(path: &[PathSegment]) -> Option<Self> {
55        debug!("ScalarType::from_path {}", TCPath::from(path));
56        if path.len() >= 2 && &path[..2] != &PREFIX[..] {
57            return None;
58        }
59
60        if path.len() == 3 {
61            match path[2].as_str() {
62                "cluster" => Some(Self::Cluster),
63                "map" => Some(Self::Map),
64                "range" => Some(Self::Range),
65                "tuple" => Some(Self::Tuple),
66                _ => None,
67            }
68        } else if path.len() > 2 {
69            match path[2].as_str() {
70                "op" => OpDefType::from_path(path).map(Self::Op),
71                "ref" => RefType::from_path(path).map(Self::Ref),
72                "value" => ValueType::from_path(path).map(Self::Value),
73                _ => None,
74            }
75        } else {
76            None
77        }
78    }
79
80    fn path(&self) -> TCPathBuf {
81        let prefix = TCPathBuf::from(PREFIX);
82
83        match self {
84            Self::Cluster => prefix.append(label("cluster")),
85            Self::Map => prefix.append(label("map")),
86            Self::Op(odt) => odt.path(),
87            Self::Range => prefix.append(label("range")),
88            Self::Ref(rt) => rt.path(),
89            Self::Value(vt) => vt.path(),
90            Self::Tuple => prefix.append(label("tuple")),
91        }
92    }
93}
94
95impl Default for ScalarType {
96    fn default() -> Self {
97        Self::Value(ValueType::default())
98    }
99}
100
101impl From<ValueType> for ScalarType {
102    fn from(vt: ValueType) -> Self {
103        Self::Value(vt)
104    }
105}
106
107impl fmt::Debug for ScalarType {
108    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109        match self {
110            Self::Cluster => f.write_str("Cluster reference"),
111            Self::Map => f.write_str("Map<Scalar>"),
112            Self::Op(odt) => fmt::Debug::fmt(odt, f),
113            Self::Range => f.write_str("Range"),
114            Self::Ref(rt) => fmt::Debug::fmt(rt, f),
115            Self::Value(vt) => fmt::Debug::fmt(vt, f),
116            Self::Tuple => f.write_str("Tuple<Scalar>"),
117        }
118    }
119}
120
121/// A reference to a `Cluster`
122#[derive(Clone, Eq, PartialEq)]
123pub struct ClusterRef(TCPathBuf);
124
125impl GetSize for ClusterRef {
126    fn get_size(&self) -> usize {
127        self.0.get_size()
128    }
129}
130
131impl ClusterRef {
132    /// Consume this reference and return its `TCPathBuf`
133    pub fn into_path(self) -> TCPathBuf {
134        self.0
135    }
136
137    /// Borrow this reference's `TCPathBuf`
138    pub fn path(&self) -> &TCPathBuf {
139        &self.0
140    }
141}
142
143impl<'a, D: Digest> Hash<D> for &'a ClusterRef {
144    fn hash(self) -> Output<D> {
145        Hash::<D>::hash(&self.0)
146    }
147}
148
149impl From<TCPathBuf> for ClusterRef {
150    fn from(path: TCPathBuf) -> Self {
151        Self(path)
152    }
153}
154
155impl fmt::Debug for ClusterRef {
156    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
157        write!(f, "reference to Cluster at {:?}", self.0)
158    }
159}
160
161impl fmt::Display for ClusterRef {
162    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
163        write!(f, "reference to Cluster at {}", self.0)
164    }
165}
166
167/// A scalar value, i.e. an immutable state always held in main memory and never split into blocks.
168#[derive(Clone, Eq, PartialEq)]
169pub enum Scalar {
170    Cluster(ClusterRef),
171    Map(Map<Self>),
172    Op(OpDef),
173    Range((Bound<Value>, Bound<Value>)),
174    Ref(Box<TCRef>),
175    Tuple(Tuple<Self>),
176    Value(Value),
177}
178
179as_type!(Scalar, Cluster, ClusterRef);
180as_type!(Scalar, Map, Map<Scalar>);
181as_type!(Scalar, Op, OpDef);
182as_type!(Scalar, Range, (Bound<Value>, Bound<Value>));
183as_type!(Scalar, Ref, Box<TCRef>);
184as_type!(Scalar, Tuple, Tuple<Scalar>);
185as_type!(Scalar, Value, Value);
186
187impl Scalar {
188    /// Return `true` if this `Scalar` variant is a [`Map`].
189    pub fn is_map(&self) -> bool {
190        match self {
191            Self::Map(_) => true,
192            _ => false,
193        }
194    }
195
196    /// Return `true` if self is an empty tuple, default link, or `Value::None`.
197    pub fn is_none(&self) -> bool {
198        match self {
199            Self::Map(map) => map.is_empty(),
200            Self::Tuple(tuple) => tuple.is_empty(),
201            Self::Value(value) => value.is_none(),
202            _ => false,
203        }
204    }
205
206    /// Return `true` if this `Scalar` variant is a [`Tuple`].
207    pub fn is_tuple(&self) -> bool {
208        match self {
209            Self::Tuple(_) => true,
210            Self::Value(value) => value.is_tuple(),
211            _ => false,
212        }
213    }
214
215    /// Cast this `Scalar` into the specified [`ScalarType`], if possible.
216    pub fn into_type(self, class: ScalarType) -> Option<Self> {
217        debug!("cast into {:?} from {:?}: {:?}", class, self.class(), self);
218
219        if self.class() == class {
220            return Some(self);
221        }
222
223        use OpDefType as ODT;
224        use OpRefType as ORT;
225        use RefType as RT;
226        use ScalarType as ST;
227
228        match class {
229            ST::Cluster => self.opt_cast_into().map(ClusterRef).map(Self::Cluster),
230            ST::Map => self.opt_cast_into().map(Self::Map),
231            ST::Op(odt) => match odt {
232                ODT::Get => self.opt_cast_into().map(OpDef::Get).map(Self::Op),
233
234                ODT::Put => self.opt_cast_into().map(OpDef::Put).map(Self::Op),
235
236                ODT::Post => self.opt_cast_into().map(OpDef::Post).map(Self::Op),
237
238                ODT::Delete => self.opt_cast_into().map(OpDef::Delete).map(Self::Op),
239            },
240            ST::Range => self.opt_cast_into().map(Self::Range),
241            ST::Ref(rt) => match rt {
242                RT::After => self
243                    .opt_cast_into()
244                    .map(Box::new)
245                    .map(TCRef::After)
246                    .map(Box::new)
247                    .map(Scalar::Ref),
248
249                RT::Case => self
250                    .opt_cast_into()
251                    .map(Box::new)
252                    .map(TCRef::Case)
253                    .map(Box::new)
254                    .map(Scalar::Ref),
255
256                RT::Id => self
257                    .opt_cast_into()
258                    .map(TCRef::Id)
259                    .map(Box::new)
260                    .map(Scalar::Ref),
261
262                RT::If => self
263                    .opt_cast_into()
264                    .map(Box::new)
265                    .map(TCRef::If)
266                    .map(Box::new)
267                    .map(Scalar::Ref),
268
269                RT::Op(ort) => {
270                    debug!("cast into op ref from {:?}", self);
271
272                    if ort == ORT::Delete && self.matches::<(Scalar, Scalar)>() {
273                        debug!("cast into DELETE ref from {:?}", self);
274
275                        let (subject, key): (Scalar, Scalar) = self.opt_cast_into().unwrap();
276                        let delete_ref: Option<(Subject, Scalar)> = match subject {
277                            Scalar::Ref(tc_ref) => match *tc_ref {
278                                TCRef::Id(id_ref) => Some((id_ref.into(), key)),
279                                TCRef::Op(OpRef::Get((subject, none))) if none.is_none() => {
280                                    Some((subject, key))
281                                }
282                                other => {
283                                    debug!("invalid DELETE subject: {:?}", other);
284                                    None
285                                }
286                            },
287                            other => {
288                                debug!("invalid DELETE subject: {:?}", other);
289                                None
290                            }
291                        };
292
293                        if let Some((subject, key)) = &delete_ref {
294                            debug!("DELETE ref is {}: {:?}", subject, key);
295                        } else {
296                            debug!("could not cast into DELETE ref");
297                        }
298
299                        delete_ref.map(OpRef::Delete).map(TCRef::Op).map(Self::from)
300                    } else if self.matches::<Tuple<Scalar>>() {
301                        let tuple: Tuple<Scalar> = self.opt_cast_into().unwrap();
302                        debug!("cast into {:?} from tuple {:?}", ort, tuple);
303
304                        let op_ref = match ort {
305                            ORT::Get => tuple.opt_cast_into().map(OpRef::Get),
306                            ORT::Put => tuple.opt_cast_into().map(OpRef::Put),
307                            ORT::Post => {
308                                debug!("subject is {:?} (a {:?})", &tuple[0], tuple[0].class());
309                                tuple.opt_cast_into().map(OpRef::Post)
310                            }
311                            ORT::Delete => tuple.opt_cast_into().map(OpRef::Delete),
312                        };
313
314                        op_ref.map(TCRef::Op).map(Self::from)
315                    } else {
316                        debug!("cannot cast into {:?} (not a tuple)", ort);
317                        None
318                    }
319                }
320
321                RT::While => self
322                    .opt_cast_into()
323                    .map(Box::new)
324                    .map(TCRef::While)
325                    .map(Box::new)
326                    .map(Scalar::Ref),
327
328                RT::With => self
329                    .opt_cast_into()
330                    .map(Box::new)
331                    .map(TCRef::With)
332                    .map(Box::new)
333                    .map(Scalar::Ref),
334            },
335
336            ST::Value(vt) => Value::opt_cast_from(self)
337                .and_then(|value| value.into_type(vt))
338                .map(Scalar::Value),
339
340            ST::Tuple => match self {
341                Self::Map(map) => Some(Self::Tuple(map.into_iter().map(|(_, v)| v).collect())),
342                Self::Tuple(tuple) => Some(Self::Tuple(tuple)),
343                _ => None,
344            },
345        }
346    }
347}
348
349impl Default for Scalar {
350    fn default() -> Self {
351        Self::Value(Value::default())
352    }
353}
354
355impl Instance for Scalar {
356    type Class = ScalarType;
357
358    fn class(&self) -> ScalarType {
359        use ScalarType as ST;
360        match self {
361            Self::Cluster(_) => ST::Cluster,
362            Self::Map(_) => ST::Map,
363            Self::Op(op) => ST::Op(op.class()),
364            Self::Range(_) => ST::Range,
365            Self::Ref(tc_ref) => ST::Ref(tc_ref.class()),
366            Self::Tuple(_) => ST::Tuple,
367            Self::Value(value) => ST::Value(value.class()),
368        }
369    }
370}
371
372impl GetSize for Scalar {
373    fn get_size(&self) -> usize {
374        match self {
375            Self::Cluster(cluster) => cluster.get_size(),
376            Self::Map(map) => map.get_size(),
377            Self::Op(op) => op.get_size(),
378            Self::Range((start, end)) => start.get_size() + end.get_size(),
379            Self::Ref(tc_ref) => tc_ref.get_size(),
380            Self::Tuple(tuple) => tuple.get_size(),
381            Self::Value(value) => value.get_size(),
382        }
383    }
384}
385
386#[async_trait]
387impl<State> Refer<State> for Scalar
388where
389    State: StateInstance + Refer<State> + From<Scalar>,
390    State::Closure: From<(Map<State>, OpDef)> + TryCastFrom<State>,
391    Map<State>: TryFrom<State, Error = TCError>,
392    Value: TryFrom<State, Error = TCError> + TryCastFrom<State>,
393    bool: TryCastFrom<State>,
394{
395    fn dereference_self(self, path: &TCPathBuf) -> Self {
396        match self {
397            Self::Map(map) => {
398                let map = map
399                    .into_iter()
400                    .map(|(id, scalar)| (id, scalar.dereference_self(path)))
401                    .collect();
402
403                Self::Map(map)
404            }
405            Self::Op(op_def) => Self::Op(op_def.dereference_self(path)),
406            Self::Ref(tc_ref) => {
407                let tc_ref = tc_ref.dereference_self(path);
408                Self::Ref(Box::new(tc_ref))
409            }
410            Self::Tuple(tuple) => {
411                let tuple = tuple
412                    .into_iter()
413                    .map(|scalar| scalar.dereference_self(path))
414                    .collect();
415
416                Self::Tuple(tuple)
417            }
418            other => other,
419        }
420    }
421
422    fn is_conditional(&self) -> bool {
423        match self {
424            Self::Map(map) => map.values().any(|scalar| scalar.is_conditional()),
425            Self::Ref(tc_ref) => tc_ref.is_conditional(),
426            Self::Tuple(tuple) => tuple.iter().any(|scalar| scalar.is_conditional()),
427            _ => false,
428        }
429    }
430
431    fn is_inter_service_write(&self, cluster_path: &[PathSegment]) -> bool {
432        match self {
433            Self::Map(map) => map
434                .values()
435                .any(|scalar| scalar.is_inter_service_write(cluster_path)),
436
437            Self::Op(op_def) => op_def.is_inter_service_write(cluster_path),
438
439            Self::Ref(tc_ref) => tc_ref.is_inter_service_write(cluster_path),
440
441            Self::Tuple(tuple) => tuple
442                .iter()
443                .any(|scalar| scalar.is_inter_service_write(cluster_path)),
444
445            _ => false,
446        }
447    }
448
449    fn is_ref(&self) -> bool {
450        match self {
451            Self::Map(map) => map.values().any(Self::is_ref),
452            Self::Ref(_) => true,
453            Self::Tuple(tuple) => tuple.iter().any(Self::is_ref),
454            _ => false,
455        }
456    }
457
458    fn reference_self(self, path: &TCPathBuf) -> Self {
459        match self {
460            Self::Map(map) => {
461                let map = map
462                    .into_iter()
463                    .map(|(id, scalar)| (id, scalar.reference_self(path)))
464                    .collect();
465
466                Self::Map(map)
467            }
468            Self::Op(op_def) => {
469                let before = op_def.clone();
470                let after = op_def.reference_self(path);
471                if before == after {
472                    Self::Op(after)
473                } else {
474                    Self::Ref(Box::new(TCRef::With(Box::new(With::new(
475                        vec![SELF.into()].into(),
476                        after,
477                    )))))
478                }
479            }
480            Self::Ref(tc_ref) => {
481                let tc_ref = tc_ref.reference_self(path);
482                Self::Ref(Box::new(tc_ref))
483            }
484            Self::Tuple(tuple) => {
485                let tuple = tuple
486                    .into_iter()
487                    .map(|scalar| scalar.reference_self(path))
488                    .collect();
489
490                Self::Tuple(tuple)
491            }
492            other => other,
493        }
494    }
495
496    fn requires(&self, deps: &mut HashSet<Id>) {
497        match self {
498            Self::Map(map) => {
499                for scalar in map.values() {
500                    scalar.requires(deps);
501                }
502            }
503            Self::Ref(tc_ref) => tc_ref.requires(deps),
504            Self::Tuple(tuple) => {
505                for scalar in tuple.iter() {
506                    scalar.requires(deps);
507                }
508            }
509            _ => {}
510        }
511    }
512
513    async fn resolve<'a, T: ToState<State> + Public<State> + Instance>(
514        self,
515        context: &'a Scope<'a, State, T>,
516        txn: &'a State::Txn,
517    ) -> TCResult<State> {
518        debug!("Scalar::resolve {:?}", self);
519
520        match self {
521            Self::Map(map) => {
522                let mut resolved = stream::iter(map)
523                    .map(|(id, scalar)| scalar.resolve(context, txn).map_ok(|state| (id, state)))
524                    .buffer_unordered(num_cpus::get());
525
526                let mut map = Map::new();
527                while let Some((id, state)) = resolved.try_next().await? {
528                    map.insert(id, state);
529                }
530
531                Ok(State::from(map))
532            }
533            Self::Ref(tc_ref) => tc_ref.resolve(context, txn).await,
534            Self::Tuple(tuple) => {
535                let len = tuple.len();
536                let mut resolved = stream::iter(tuple)
537                    .map(|scalar| scalar.resolve(context, txn))
538                    .buffered(num_cpus::get());
539
540                let mut tuple = Vec::with_capacity(len);
541                while let Some(state) = resolved.try_next().await? {
542                    tuple.push(state);
543                }
544
545                Ok(State::from(Tuple::from(tuple)))
546            }
547            other => Ok(State::from(other)),
548        }
549    }
550}
551
552impl<D: Digest> Hash<D> for Scalar {
553    fn hash(self) -> Output<D> {
554        Hash::<D>::hash(&self)
555    }
556}
557
558impl<'a, D: Digest> Hash<D> for &'a Scalar {
559    fn hash(self) -> Output<D> {
560        match self {
561            Scalar::Cluster(cluster_ref) => Hash::<D>::hash(cluster_ref),
562            Scalar::Map(map) => Hash::<D>::hash(map.deref()),
563            Scalar::Op(op) => Hash::<D>::hash(op),
564            Scalar::Range(_range) => todo!("hash a range"),
565            Scalar::Ref(tc_ref) => Hash::<D>::hash(tc_ref.deref()),
566            Scalar::Tuple(tuple) => Hash::<D>::hash(tuple.deref()),
567            Scalar::Value(value) => Hash::<D>::hash(value),
568        }
569    }
570}
571
572impl From<Id> for Scalar {
573    fn from(id: Id) -> Self {
574        Self::Value(id.into())
575    }
576}
577
578impl From<IdRef> for Scalar {
579    fn from(id_ref: IdRef) -> Self {
580        Self::Ref(Box::new(TCRef::Id(id_ref)))
581    }
582}
583
584impl From<Host> for Scalar {
585    fn from(host: Host) -> Self {
586        Value::from(host).into()
587    }
588}
589
590impl From<Link> for Scalar {
591    fn from(link: Link) -> Self {
592        Value::from(link).into()
593    }
594}
595
596impl From<Number> for Scalar {
597    fn from(n: Number) -> Self {
598        Self::Value(n.into())
599    }
600}
601
602impl From<OpRef> for Scalar {
603    fn from(op_ref: OpRef) -> Self {
604        Self::Ref(Box::new(TCRef::Op(op_ref)))
605    }
606}
607
608impl From<TCPathBuf> for Scalar {
609    fn from(path: TCPathBuf) -> Self {
610        Self::Value(path.into())
611    }
612}
613
614impl From<TCRef> for Scalar {
615    fn from(tc_ref: TCRef) -> Self {
616        Self::Ref(Box::new(tc_ref))
617    }
618}
619
620impl From<Tuple<Value>> for Scalar {
621    fn from(tuple: Tuple<Value>) -> Self {
622        Self::Value(tuple.into())
623    }
624}
625
626impl From<bool> for Scalar {
627    fn from(b: bool) -> Self {
628        Self::Value(b.into())
629    }
630}
631
632impl From<i64> for Scalar {
633    fn from(n: i64) -> Self {
634        Self::Value(n.into())
635    }
636}
637
638impl From<usize> for Scalar {
639    fn from(n: usize) -> Self {
640        Self::Value(n.into())
641    }
642}
643
644impl From<u64> for Scalar {
645    fn from(n: u64) -> Self {
646        Self::Value(n.into())
647    }
648}
649
650impl TryFrom<Scalar> for bool {
651    type Error = TCError;
652
653    fn try_from(scalar: Scalar) -> TCResult<Self> {
654        match scalar {
655            Scalar::Value(value) => value.try_into(),
656            other => Err(TCError::unexpected(other, "a boolean")),
657        }
658    }
659}
660
661impl TryFrom<Scalar> for Id {
662    type Error = TCError;
663
664    fn try_from(scalar: Scalar) -> TCResult<Self> {
665        match scalar {
666            Scalar::Value(value) => value.try_into(),
667            other => Err(TCError::unexpected(other, "a boolean")),
668        }
669    }
670}
671
672impl TryFrom<Scalar> for Map<Scalar> {
673    type Error = TCError;
674
675    fn try_from(scalar: Scalar) -> TCResult<Map<Scalar>> {
676        match scalar {
677            Scalar::Map(map) => Ok(map),
678
679            Scalar::Tuple(tuple) => tuple
680                .into_iter()
681                .map(|item| -> TCResult<(Id, Scalar)> { item.try_into() })
682                .collect(),
683
684            other => Err(TCError::unexpected(other, "a Map")),
685        }
686    }
687}
688
689impl TryFrom<Scalar> for Map<Value> {
690    type Error = TCError;
691
692    fn try_from(scalar: Scalar) -> TCResult<Map<Value>> {
693        debug!("try to construct a Map<Value> from {scalar:?}");
694
695        match scalar {
696            Scalar::Map(map) => map
697                .into_iter()
698                .map(|(id, scalar)| Value::try_from(scalar).map(|value| (id, value)))
699                .collect(),
700
701            Scalar::Tuple(tuple) => tuple
702                .into_iter()
703                .map(|item| -> TCResult<(Id, Value)> { item.try_into() })
704                .collect(),
705
706            Scalar::Value(value) => value.try_into(),
707
708            other => Err(TCError::unexpected(other, "a Map")),
709        }
710    }
711}
712
713impl TryFrom<Scalar> for Tuple<Scalar> {
714    type Error = TCError;
715
716    fn try_from(scalar: Scalar) -> Result<Self, Self::Error> {
717        match scalar {
718            Scalar::Map(map) => Ok(map
719                .into_iter()
720                .map(|(id, scalar)| Scalar::Tuple(vec![Scalar::from(id), scalar].into()))
721                .collect()),
722
723            Scalar::Tuple(tuple) => Ok(tuple),
724
725            Scalar::Value(value) => {
726                let tuple = Tuple::<Value>::try_from(value)?;
727                Ok(tuple.into_iter().map(Scalar::Value).collect())
728            }
729
730            other => Err(TCError::unexpected(other, "a Tuple")),
731        }
732    }
733}
734
735impl<T: TryFrom<Scalar>> TryFrom<Scalar> for (Id, T)
736where
737    TCError: From<T::Error>,
738{
739    type Error = TCError;
740
741    fn try_from(scalar: Scalar) -> Result<Self, Self::Error> {
742        match scalar {
743            Scalar::Tuple(mut tuple) if tuple.len() == 2 => {
744                let value = tuple.pop().expect("value");
745                let key = tuple.pop().expect("key");
746                Ok((Id::try_from(key)?, value.try_into()?))
747            }
748            other => Err(TCError::unexpected(other, "a map item")),
749        }
750    }
751}
752
753impl TryFrom<Scalar> for TCRef {
754    type Error = TCError;
755
756    fn try_from(scalar: Scalar) -> Result<Self, Self::Error> {
757        match scalar {
758            Scalar::Ref(tc_ref) => Ok(*tc_ref),
759            other => Err(TCError::unexpected(other, "a reference")),
760        }
761    }
762}
763
764impl TryFrom<Scalar> for Value {
765    type Error = TCError;
766
767    fn try_from(scalar: Scalar) -> TCResult<Value> {
768        match scalar {
769            Scalar::Value(value) => Ok(value),
770            Scalar::Tuple(tuple) => tuple.into_iter().map(Value::try_from).collect(),
771            other => Err(TCError::unexpected(other, "a Value")),
772        }
773    }
774}
775
776impl TryCastFrom<Scalar> for (Bound<Value>, Bound<Value>) {
777    fn can_cast_from(scalar: &Scalar) -> bool {
778        match scalar {
779            Scalar::Range(_) => true,
780            Scalar::Value(value) => Self::can_cast_from(value),
781            Scalar::Tuple(tuple) if tuple.len() == 2 => tuple.iter().all(|scalar| match scalar {
782                Scalar::Value(value) => Bound::<Value>::can_cast_from(value),
783                Scalar::Tuple(tuple) if tuple.len() == 2 => match &tuple[0] {
784                    Scalar::Value(Value::String(bound)) if bound == "in" || bound == "ex" => {
785                        Value::can_cast_from(&tuple[1])
786                    }
787                    _ => false,
788                },
789                _ => false,
790            }),
791            Scalar::Tuple(_) => false,
792            _ => false,
793        }
794    }
795
796    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
797        match scalar {
798            Scalar::Range(range) => Some(range),
799            Scalar::Value(value) => Self::opt_cast_from(value),
800            Scalar::Tuple(mut tuple) if tuple.len() == 2 => {
801                let hi: Value = tuple.pop().expect("hi").opt_cast_into()?;
802                let lo: Value = tuple.pop().expect("lo").opt_cast_into()?;
803                Some((lo.opt_cast_into()?, hi.opt_cast_into()?))
804            }
805            _ => None,
806        }
807    }
808}
809
810impl TryCastFrom<Scalar> for OpDef {
811    fn can_cast_from(scalar: &Scalar) -> bool {
812        match scalar {
813            Scalar::Op(_) => true,
814            Scalar::Tuple(tuple) => {
815                GetOp::can_cast_from(tuple)
816                    || PutOp::can_cast_from(tuple)
817                    || PostOp::can_cast_from(tuple)
818                    || DeleteOp::can_cast_from(tuple)
819            }
820            Scalar::Value(Value::Tuple(tuple)) => {
821                GetOp::can_cast_from(tuple)
822                    || PutOp::can_cast_from(tuple)
823                    || PostOp::can_cast_from(tuple)
824                    || DeleteOp::can_cast_from(tuple)
825            }
826            _ => false,
827        }
828    }
829
830    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
831        match scalar {
832            Scalar::Op(op_def) => Some(op_def),
833            Scalar::Tuple(tuple) => {
834                if PutOp::can_cast_from(&tuple) {
835                    tuple.opt_cast_into().map(Self::Put)
836                } else if GetOp::can_cast_from(&tuple) {
837                    tuple.opt_cast_into().map(Self::Get)
838                } else if PostOp::can_cast_from(&tuple) {
839                    tuple.opt_cast_into().map(Self::Post)
840                } else if DeleteOp::can_cast_from(&tuple) {
841                    tuple.opt_cast_into().map(Self::Delete)
842                } else {
843                    None
844                }
845            }
846            Scalar::Value(Value::Tuple(tuple)) => {
847                Scalar::Tuple(tuple.into_iter().collect()).opt_cast_into()
848            }
849            _ => None,
850        }
851    }
852}
853
854impl TryCastFrom<Scalar> for TCRef {
855    fn can_cast_from(scalar: &Scalar) -> bool {
856        match scalar {
857            Scalar::Ref(_) => true,
858            _ => false,
859        }
860    }
861
862    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
863        match scalar {
864            Scalar::Ref(tc_ref) => Some(*tc_ref),
865            _ => None,
866        }
867    }
868}
869
870impl TryCastFrom<Scalar> for IdRef {
871    fn can_cast_from(scalar: &Scalar) -> bool {
872        match scalar {
873            Scalar::Ref(tc_ref) => match &**tc_ref {
874                TCRef::Id(_) => true,
875                _ => false,
876            },
877            _ => false,
878        }
879    }
880
881    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
882        match scalar {
883            Scalar::Ref(tc_ref) => match *tc_ref {
884                TCRef::Id(id_ref) => Some(id_ref),
885                _ => None,
886            },
887            _ => None,
888        }
889    }
890}
891
892impl<T: Clone + TryCastFrom<Scalar>> TryCastFrom<Scalar> for Map<T> {
893    fn can_cast_from(scalar: &Scalar) -> bool {
894        match scalar {
895            Scalar::Map(map) => map.values().all(T::can_cast_from),
896            Scalar::Tuple(tuple) => Vec::<(Id, T)>::can_cast_from(tuple),
897            _ => false,
898        }
899    }
900
901    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
902        match scalar {
903            Scalar::Map(map) => {
904                let mut dest = Map::new();
905                for (key, value) in map.into_iter() {
906                    let value = T::opt_cast_from(value)?;
907                    dest.insert(key, value);
908                }
909                Some(dest)
910            }
911            Scalar::Tuple(tuple) => {
912                if let Some(entries) = Vec::<(Id, T)>::opt_cast_from(tuple) {
913                    Some(entries.into_iter().collect())
914                } else {
915                    None
916                }
917            }
918            _ => None,
919        }
920    }
921}
922
923impl TryCastFrom<Scalar> for Tuple<Scalar> {
924    fn can_cast_from(scalar: &Scalar) -> bool {
925        match scalar {
926            Scalar::Tuple(_) => true,
927            Scalar::Value(Value::Tuple(_)) => true,
928            _ => false,
929        }
930    }
931
932    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
933        match scalar {
934            Scalar::Tuple(tuple) => Some(tuple),
935            Scalar::Value(Value::Tuple(tuple)) => Some(tuple.into_iter().collect()),
936            _ => None,
937        }
938    }
939}
940
941impl<const N: usize, T> TryCastFrom<Scalar> for SmallVec<[T; N]>
942where
943    T: TryCastFrom<Scalar>,
944    [T; N]: smallvec::Array<Item = T>,
945{
946    fn can_cast_from(scalar: &Scalar) -> bool {
947        match scalar {
948            Scalar::Tuple(tuple) => Self::can_cast_from(tuple),
949            _ => false,
950        }
951    }
952
953    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
954        match scalar {
955            Scalar::Tuple(tuple) => Self::opt_cast_from(tuple),
956            _ => None,
957        }
958    }
959}
960
961impl<T: TryCastFrom<Scalar>> TryCastFrom<Scalar> for Vec<T> {
962    fn can_cast_from(scalar: &Scalar) -> bool {
963        match scalar {
964            Scalar::Tuple(tuple) => Self::can_cast_from(tuple),
965            _ => false,
966        }
967    }
968
969    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
970        match scalar {
971            Scalar::Tuple(tuple) => Self::opt_cast_from(tuple),
972            _ => None,
973        }
974    }
975}
976
977impl TryCastFrom<Scalar> for Tuple<Value> {
978    fn can_cast_from(scalar: &Scalar) -> bool {
979        match scalar {
980            Scalar::Tuple(tuple) => tuple.iter().all(Value::can_cast_from),
981            Scalar::Value(Value::Tuple(_)) => true,
982            _ => false,
983        }
984    }
985
986    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
987        match scalar {
988            Scalar::Tuple(tuple) => tuple.into_iter().map(Value::opt_cast_from).collect(),
989            Scalar::Value(Value::Tuple(tuple)) => Some(tuple),
990            _ => None,
991        }
992    }
993}
994
995macro_rules! from_value {
996    ($t:ty) => {
997        impl TryCastFrom<Scalar> for $t {
998            fn can_cast_from(scalar: &Scalar) -> bool {
999                match scalar {
1000                    Scalar::Value(value) => Self::can_cast_from(value),
1001                    _ => false,
1002                }
1003            }
1004
1005            fn opt_cast_from(scalar: Scalar) -> Option<Self> {
1006                match scalar {
1007                    Scalar::Value(value) => Self::opt_cast_from(value),
1008                    _ => None,
1009                }
1010            }
1011        }
1012    };
1013}
1014
1015from_value!(Bytes);
1016from_value!(Float);
1017from_value!(Link);
1018from_value!(Host);
1019from_value!(Number);
1020from_value!(TCPathBuf);
1021from_value!(TCString);
1022from_value!(bool);
1023from_value!(usize);
1024from_value!(u64);
1025
1026impl TryCastFrom<Scalar> for Value {
1027    fn can_cast_from(scalar: &Scalar) -> bool {
1028        match scalar {
1029            Scalar::Tuple(tuple) => tuple.iter().all(Self::can_cast_from),
1030            Scalar::Value(_) => true,
1031            _ => false,
1032        }
1033    }
1034
1035    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
1036        match scalar {
1037            Scalar::Tuple(tuple) => {
1038                let mut value = Vec::with_capacity(tuple.len());
1039                for item in tuple.into_iter() {
1040                    if let Some(item) = Self::opt_cast_from(item) {
1041                        value.push(item);
1042                    } else {
1043                        return None;
1044                    }
1045                }
1046
1047                Some(Value::Tuple(value.into()))
1048            }
1049            Scalar::Value(value) => Some(value),
1050            _ => None,
1051        }
1052    }
1053}
1054
1055impl TryCastFrom<Scalar> for Id {
1056    fn can_cast_from(scalar: &Scalar) -> bool {
1057        match scalar {
1058            Scalar::Value(value) => Self::can_cast_from(value),
1059            Scalar::Ref(tc_ref) => Self::can_cast_from(&**tc_ref),
1060            _ => false,
1061        }
1062    }
1063
1064    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
1065        match scalar {
1066            Scalar::Value(value) => Self::opt_cast_from(value),
1067            Scalar::Ref(tc_ref) => Self::opt_cast_from(*tc_ref),
1068            _ => None,
1069        }
1070    }
1071}
1072
1073impl TryCastFrom<Scalar> for OpRef {
1074    fn can_cast_from(scalar: &Scalar) -> bool {
1075        match scalar {
1076            Scalar::Ref(tc_ref) => Self::can_cast_from(&**tc_ref),
1077            get_ref if GetRef::can_cast_from(get_ref) => true,
1078            put_ref if PutRef::can_cast_from(put_ref) => true,
1079            post_ref if PostRef::can_cast_from(post_ref) => true,
1080            _ => false,
1081        }
1082    }
1083
1084    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
1085        match scalar {
1086            Scalar::Ref(tc_ref) => Self::opt_cast_from(*tc_ref),
1087            get_ref if GetRef::can_cast_from(&get_ref) => get_ref.opt_cast_into().map(Self::Get),
1088            put_ref if PutRef::can_cast_from(&put_ref) => put_ref.opt_cast_into().map(Self::Put),
1089            post_ref if PostRef::can_cast_from(&post_ref) => {
1090                post_ref.opt_cast_into().map(Self::Post)
1091            }
1092            _ => None,
1093        }
1094    }
1095}
1096
1097impl<T: TryCastFrom<Scalar>> TryCastFrom<Scalar> for (T,) {
1098    fn can_cast_from(scalar: &Scalar) -> bool {
1099        match scalar {
1100            Scalar::Tuple(tuple) => Self::can_cast_from(tuple),
1101            _ => false,
1102        }
1103    }
1104
1105    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
1106        match scalar {
1107            Scalar::Tuple(tuple) => Self::opt_cast_from(tuple),
1108            _ => None,
1109        }
1110    }
1111}
1112
1113impl<T1: TryCastFrom<Scalar>, T2: TryCastFrom<Scalar>> TryCastFrom<Scalar> for (T1, T2) {
1114    fn can_cast_from(scalar: &Scalar) -> bool {
1115        match scalar {
1116            Scalar::Tuple(tuple) => Self::can_cast_from(tuple),
1117            _ => false,
1118        }
1119    }
1120
1121    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
1122        debug!(
1123            "cast from {:?} into {}?",
1124            scalar,
1125            std::any::type_name::<Self>()
1126        );
1127
1128        match scalar {
1129            Scalar::Tuple(tuple) => Self::opt_cast_from(tuple),
1130            _ => None,
1131        }
1132    }
1133}
1134
1135impl<T1: TryCastFrom<Scalar>, T2: TryCastFrom<Scalar>, T3: TryCastFrom<Scalar>> TryCastFrom<Scalar>
1136    for (T1, T2, T3)
1137{
1138    fn can_cast_from(scalar: &Scalar) -> bool {
1139        match scalar {
1140            Scalar::Tuple(tuple) => Self::can_cast_from(tuple),
1141            _ => false,
1142        }
1143    }
1144
1145    fn opt_cast_from(scalar: Scalar) -> Option<Self> {
1146        match scalar {
1147            Scalar::Tuple(tuple) => Self::opt_cast_from(tuple),
1148            _ => None,
1149        }
1150    }
1151}
1152
1153/// A [`de::Visitor`] used to deserialize a [`Scalar`].
1154#[derive(Default)]
1155pub struct ScalarVisitor {
1156    value: tc_value::ValueVisitor,
1157}
1158
1159impl ScalarVisitor {
1160    pub async fn visit_map_value<A: de::MapAccess>(
1161        class: ScalarType,
1162        access: &mut A,
1163    ) -> Result<Scalar, A::Error> {
1164        let scalar = access.next_value::<Scalar>(()).await?;
1165
1166        if scalar.is_none() {
1167            // this is a classpath, no need to cast
1168        } else if let Some(scalar) = scalar.clone().into_type(class) {
1169            return Ok(scalar);
1170        } else {
1171            debug!("cannot cast into {:?} from {:?}", class, scalar);
1172        }
1173
1174        let subject = Link::from(class.path()).into();
1175        Self::visit_subject(subject, scalar)
1176    }
1177
1178    pub fn visit_subject<E: de::Error>(subject: Subject, params: Scalar) -> Result<Scalar, E> {
1179        if params.is_none() {
1180            let scalar = match subject {
1181                Subject::Ref(id, path) if path.is_empty() => Scalar::Ref(Box::new(TCRef::Id(id))),
1182                Subject::Ref(id, path) => Scalar::Ref(Box::new(TCRef::Op(OpRef::Get((
1183                    Subject::Ref(id, path),
1184                    Value::default().into(),
1185                ))))),
1186                Subject::Link(link) => Scalar::Value(Value::Link(link)),
1187            };
1188
1189            Ok(scalar)
1190        } else {
1191            OpRefVisitor::visit_ref_value(subject, params)
1192                .map(TCRef::Op)
1193                .map(Box::new)
1194                .map(Scalar::Ref)
1195        }
1196    }
1197}
1198
1199#[async_trait]
1200impl de::Visitor for ScalarVisitor {
1201    type Value = Scalar;
1202
1203    fn expecting() -> &'static str {
1204        "a Scalar, e.g. \"foo\" or 123 or {\"$ref: [\"id\", \"$state\"]\"}"
1205    }
1206
1207    async fn visit_array_u8<A: de::ArrayAccess<u8>>(
1208        self,
1209        array: A,
1210    ) -> Result<Self::Value, A::Error> {
1211        self.value.visit_array_u8(array).map_ok(Scalar::Value).await
1212    }
1213
1214    fn visit_bool<E: de::Error>(self, value: bool) -> Result<Self::Value, E> {
1215        self.value.visit_bool(value).map(Scalar::Value)
1216    }
1217
1218    fn visit_i8<E: de::Error>(self, value: i8) -> Result<Self::Value, E> {
1219        self.value.visit_i8(value).map(Scalar::Value)
1220    }
1221
1222    fn visit_i16<E: de::Error>(self, value: i16) -> Result<Self::Value, E> {
1223        self.value.visit_i16(value).map(Scalar::Value)
1224    }
1225
1226    fn visit_i32<E: de::Error>(self, value: i32) -> Result<Self::Value, E> {
1227        self.value.visit_i32(value).map(Scalar::Value)
1228    }
1229
1230    fn visit_i64<E: de::Error>(self, value: i64) -> Result<Self::Value, E> {
1231        self.value.visit_i64(value).map(Scalar::Value)
1232    }
1233
1234    fn visit_u8<E: de::Error>(self, value: u8) -> Result<Self::Value, E> {
1235        self.value.visit_u8(value).map(Scalar::Value)
1236    }
1237
1238    fn visit_u16<E: de::Error>(self, value: u16) -> Result<Self::Value, E> {
1239        self.value.visit_u16(value).map(Scalar::Value)
1240    }
1241
1242    fn visit_u32<E: de::Error>(self, value: u32) -> Result<Self::Value, E> {
1243        self.value.visit_u32(value).map(Scalar::Value)
1244    }
1245
1246    fn visit_u64<E: de::Error>(self, value: u64) -> Result<Self::Value, E> {
1247        self.value.visit_u64(value).map(Scalar::Value)
1248    }
1249
1250    fn visit_f32<E: de::Error>(self, value: f32) -> Result<Self::Value, E> {
1251        self.value.visit_f32(value).map(Scalar::Value)
1252    }
1253
1254    fn visit_f64<E: de::Error>(self, value: f64) -> Result<Self::Value, E> {
1255        self.value.visit_f64(value).map(Scalar::Value)
1256    }
1257
1258    fn visit_string<E: de::Error>(self, value: String) -> Result<Self::Value, E> {
1259        self.value.visit_string(value).map(Scalar::Value)
1260    }
1261
1262    fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
1263        self.value.visit_unit().map(Scalar::Value)
1264    }
1265
1266    fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
1267        self.value.visit_none().map(Scalar::Value)
1268    }
1269
1270    async fn visit_map<A: de::MapAccess>(self, mut access: A) -> Result<Self::Value, A::Error> {
1271        let key = if let Some(key) = access.next_key::<String>(()).await? {
1272            key
1273        } else {
1274            return Ok(Scalar::Map(Map::default()));
1275        };
1276
1277        if key.starts_with('/') {
1278            if let Ok(path) = TCPathBuf::from_str(&key) {
1279                if let Some(class) = ScalarType::from_path(&path) {
1280                    debug!("decode instance of {:?}", class);
1281                    return Self::visit_map_value(class, &mut access).await;
1282                } else {
1283                    debug!("not a scalar classpath: {}", path);
1284                }
1285            }
1286        }
1287
1288        if let Ok(subject) = Subject::from_str(&key) {
1289            let params = access.next_value(()).await?;
1290            return Self::visit_subject(subject, params);
1291        }
1292
1293        let mut map = Map::new();
1294        let key = Id::from_str(&key).map_err(de::Error::custom)?;
1295        let value = access.next_value(()).await?;
1296        map.insert(key, value);
1297
1298        while let Some(key) = access.next_key(()).await? {
1299            let value = access.next_value(()).await?;
1300            map.insert(key, value);
1301        }
1302
1303        Ok(Scalar::Map(map.into()))
1304    }
1305
1306    async fn visit_seq<A: de::SeqAccess>(self, mut access: A) -> Result<Self::Value, A::Error> {
1307        let mut items: Vec<Scalar> = if let Some(size) = access.size_hint() {
1308            Vec::with_capacity(size)
1309        } else {
1310            Vec::new()
1311        };
1312
1313        while let Some(value) = access.next_element(()).await? {
1314            items.push(value)
1315        }
1316
1317        Ok(Scalar::Tuple(items.into()))
1318    }
1319}
1320
1321#[async_trait]
1322impl de::FromStream for Scalar {
1323    type Context = ();
1324
1325    async fn from_stream<D: de::Decoder>(_: (), d: &mut D) -> Result<Self, D::Error> {
1326        d.decode_any(ScalarVisitor::default()).await
1327    }
1328}
1329
1330impl<'en> en::ToStream<'en> for Scalar {
1331    fn to_stream<E: en::Encoder<'en>>(&'en self, e: E) -> Result<E::Ok, E::Error> {
1332        match self {
1333            Scalar::Cluster(ClusterRef(path)) => single_entry(self.class().path(), path, e),
1334            Scalar::Map(map) => map.to_stream(e),
1335            Scalar::Op(op_def) => op_def.to_stream(e),
1336            Scalar::Range(_range) => todo!("Scalar::Range::to_stream"),
1337            Scalar::Ref(tc_ref) => tc_ref.to_stream(e),
1338            Scalar::Tuple(tuple) => tuple.to_stream(e),
1339            Scalar::Value(value) => value.to_stream(e),
1340        }
1341    }
1342}
1343
1344impl<'en> en::IntoStream<'en> for Scalar {
1345    fn into_stream<E: en::Encoder<'en>>(self, e: E) -> Result<E::Ok, E::Error> {
1346        let classpath = self.class().path();
1347
1348        match self {
1349            Scalar::Cluster(ClusterRef(path)) => single_entry(classpath, path, e),
1350            Scalar::Map(map) => map.into_inner().into_stream(e),
1351            Scalar::Op(op_def) => op_def.into_stream(e),
1352            Scalar::Range(_range) => todo!("Scalar::Range::into_stream"),
1353            Scalar::Ref(tc_ref) => tc_ref.into_stream(e),
1354            Scalar::Tuple(tuple) => tuple.into_inner().into_stream(e),
1355            Scalar::Value(value) => value.into_stream(e),
1356        }
1357    }
1358}
1359
1360impl fmt::Debug for Scalar {
1361    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1362        match self {
1363            Scalar::Cluster(cluster) => fmt::Debug::fmt(cluster, f),
1364            Scalar::Map(map) => fmt::Debug::fmt(map, f),
1365            Scalar::Op(op) => fmt::Debug::fmt(op, f),
1366            Scalar::Range(range) => fmt::Debug::fmt(range, f),
1367            Scalar::Ref(tc_ref) => fmt::Debug::fmt(tc_ref, f),
1368            Scalar::Tuple(tuple) => fmt::Debug::fmt(tuple, f),
1369            Scalar::Value(value) => fmt::Debug::fmt(value, f),
1370        }
1371    }
1372}
1373
1374/// The execution scope of a [`Scalar`], such as an [`OpDef`] or [`TCRef`]
1375pub struct Scope<'a, State, T> {
1376    subject: Option<&'a T>,
1377    data: Map<State>,
1378}
1379
1380impl<'a, State, T> Scope<'a, State, T>
1381where
1382    State: StateInstance + Refer<State>,
1383    T: ToState<State> + Instance + Public<State>,
1384{
1385    pub fn new<S: Into<State>, I: IntoIterator<Item = (Id, S)>>(
1386        subject: Option<&'a T>,
1387        data: I,
1388    ) -> Self {
1389        let data = data.into_iter().map(|(id, s)| (id, s.into())).collect();
1390
1391        debug!("new execution scope: {:?}", data);
1392        Self { subject, data }
1393    }
1394
1395    pub fn with_context<S: Into<State>, I: IntoIterator<Item = (Id, S)>>(
1396        subject: Option<&'a T>,
1397        context: Map<State>,
1398        data: I,
1399    ) -> Self {
1400        let data = context
1401            .into_inner()
1402            .into_iter()
1403            .chain(data.into_iter().map(|(id, s)| (id, s.into())))
1404            .collect();
1405
1406        debug!("new execution scope: {:?}", data);
1407        Self { subject, data }
1408    }
1409
1410    pub fn into_inner(self) -> Map<State> {
1411        self.data
1412    }
1413
1414    pub fn resolve_id(&self, id: &Id) -> TCResult<State> {
1415        debug!("resolve ID {}", id);
1416
1417        let result = if id == &SELF {
1418            self.subject().map(|subject| subject.to_state())
1419        } else {
1420            self.data
1421                .deref()
1422                .get(id)
1423                .cloned()
1424                .ok_or_else(|| TCError::not_found(format!("state with ID {}", id)))
1425        };
1426
1427        match result {
1428            Ok(state) => {
1429                debug!("{} resolved to {:?}", id, state);
1430                Ok(state)
1431            }
1432            Err(cause) => {
1433                warn!(
1434                    "error resolving {} in context {}: {}",
1435                    id,
1436                    self.data.keys().collect::<Tuple<&Id>>(),
1437                    cause
1438                );
1439                Err(cause)
1440            }
1441        }
1442    }
1443
1444    pub async fn resolve_get(
1445        &self,
1446        txn: &State::Txn,
1447        subject: &Id,
1448        path: &[PathSegment],
1449        key: Value,
1450    ) -> TCResult<State> {
1451        if subject == &SELF {
1452            let subject = self.subject()?;
1453            subject.get(txn, path, key).await
1454        } else if let Some(subject) = self.data.deref().get(subject).cloned() {
1455            let subject = subject.resolve(self, txn).await?;
1456            subject.get(txn, path, key).await
1457        } else {
1458            Err(TCError::not_found(format!(
1459                "GET method subject {}",
1460                subject
1461            )))
1462        }
1463    }
1464
1465    pub async fn resolve_put(
1466        &self,
1467        txn: &State::Txn,
1468        subject: &Id,
1469        path: &[PathSegment],
1470        key: Value,
1471        value: State,
1472    ) -> TCResult<()> {
1473        if subject == &SELF {
1474            let subject = self.subject()?;
1475            subject.put(txn, path, key, value).await
1476        } else if let Some(subject) = self.data.deref().get(subject).cloned() {
1477            let subject = subject.resolve(self, txn).await?;
1478            subject.put(txn, path, key, value).await
1479        } else {
1480            Err(TCError::not_found(format!(
1481                "PUT method subject {}",
1482                subject
1483            )))
1484        }
1485    }
1486
1487    pub async fn resolve_post(
1488        &self,
1489        txn: &State::Txn,
1490        subject: &Id,
1491        path: &[PathSegment],
1492        params: Map<State>,
1493    ) -> TCResult<State> {
1494        if subject == &SELF {
1495            let subject = self.subject()?;
1496            subject.post(txn, path, params).await
1497        } else if let Some(subject) = self.data.deref().get(subject).cloned() {
1498            let subject = subject.resolve(self, txn).await?;
1499            subject.post(txn, path, params).await
1500        } else {
1501            Err(TCError::not_found(format!(
1502                "POST method subject {}",
1503                subject
1504            )))
1505        }
1506    }
1507
1508    pub async fn resolve_delete(
1509        &self,
1510        txn: &State::Txn,
1511        subject: &Id,
1512        path: &[PathSegment],
1513        key: Value,
1514    ) -> TCResult<()> {
1515        if subject == &SELF {
1516            let subject = self.subject()?;
1517            subject.delete(txn, path, key).await
1518        } else if let Some(subject) = self.data.deref().get(subject).cloned() {
1519            let subject = subject.resolve(self, txn).await?;
1520            subject.delete(txn, path, key).await
1521        } else {
1522            Err(TCError::not_found(format!(
1523                "DELETE method subject {}",
1524                subject
1525            )))
1526        }
1527    }
1528
1529    fn subject(&self) -> TCResult<&T> {
1530        if let Some(subject) = self.subject {
1531            Ok(subject)
1532        } else {
1533            Err(bad_request!("{}", ERR_NO_SELF))
1534        }
1535    }
1536}
1537
1538impl<'a, State, T> Deref for Scope<'a, State, T> {
1539    type Target = Map<State>;
1540
1541    fn deref(&self) -> &Self::Target {
1542        &self.data
1543    }
1544}
1545
1546impl<'a, State, T> DerefMut for Scope<'a, State, T> {
1547    fn deref_mut(&mut self) -> &mut Self::Target {
1548        &mut self.data
1549    }
1550}
1551
1552impl<'a, State, T> fmt::Debug for Scope<'a, State, T> {
1553    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1554        let ids = self.keys().collect::<Tuple<&Id>>();
1555        write!(f, "execution scope with IDs {}", ids)
1556    }
1557}
1558
1559fn single_entry<
1560    'en,
1561    K: en::IntoStream<'en> + 'en,
1562    V: en::IntoStream<'en> + 'en,
1563    E: en::Encoder<'en>,
1564>(
1565    key: K,
1566    value: V,
1567    encoder: E,
1568) -> Result<E::Ok, E::Error> {
1569    use en::EncodeMap;
1570
1571    let mut map = encoder.encode_map(Some(1))?;
1572    map.encode_entry(key, value)?;
1573    map.end()
1574}