puffin/algebra/
atoms.rs

1//! This module provides an enum for terms. A term can either be a Variable or a Function.
2//! This also implements the serializability of terms.
3use std::fmt::{self};
4use std::hash::{Hash, Hasher};
5
6use rand::random;
7use serde::{Deserialize, Serialize};
8
9use crate::algebra::atoms::fn_container::FnContainer;
10use crate::algebra::dynamic_function::{
11    DynamicFunction, DynamicFunctionShape, FunctionAttributes, TypeShape,
12};
13use crate::algebra::remove_prefix;
14use crate::protocol::ProtocolTypes;
15use crate::trace::Query;
16
17/// A variable symbol with fixed type.
18#[derive(Serialize, Deserialize, Debug)]
19#[serde(bound = "PT: ProtocolTypes")]
20pub struct Variable<PT: ProtocolTypes> {
21    /// Unique ID of this variable. Uniqueness is guaranteed across all
22    /// [`Term`](crate::algebra::Term)s ever created. Cloning change this ID.
23    pub unique_id: u32,
24    /// ID of this variable. This id stays the same during cloning.
25    pub resistant_id: u32,
26    pub typ: TypeShape<PT>,
27    /// The struct which holds information about how to query this variable from knowledge
28    pub query: Query<PT::Matcher>,
29}
30
31impl<PT: ProtocolTypes> Hash for Variable<PT> {
32    fn hash<H: Hasher>(&self, state: &mut H) {
33        self.typ.hash(state);
34        self.query.hash(state);
35    }
36}
37
38impl<PT: ProtocolTypes> Eq for Variable<PT> {}
39impl<PT: ProtocolTypes> PartialEq for Variable<PT> {
40    fn eq(&self, other: &Self) -> bool {
41        self.typ == other.typ && self.query == other.query
42    }
43}
44
45impl<PT: ProtocolTypes> Clone for Variable<PT> {
46    fn clone(&self) -> Self {
47        Variable {
48            unique_id: random(),
49            resistant_id: self.resistant_id,
50            typ: self.typ.clone(),
51            query: self.query.clone(),
52        }
53    }
54}
55
56impl<PT: ProtocolTypes> Variable<PT> {
57    pub fn new(typ: TypeShape<PT>, query: Query<PT::Matcher>) -> Self {
58        Self {
59            unique_id: random(),
60            resistant_id: random(),
61            typ,
62            query,
63        }
64    }
65}
66
67impl<PT: ProtocolTypes> fmt::Display for Variable<PT> {
68    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
69        write!(f, "{}/{}", self.query, remove_prefix(self.typ.name))
70    }
71}
72
73/// A function symbol with fixed arity and fixed types.
74#[derive(Serialize, Deserialize, Debug)]
75#[serde(bound = "PT: ProtocolTypes")]
76pub struct Function<PT: ProtocolTypes> {
77    /// Unique ID of this function. Uniqueness is guaranteed across all
78    /// [`Term`](crate::algebra::Term)s ever created. Cloning change this ID.
79    pub unique_id: u32,
80    /// ID of this function. This id stays the same during cloning.
81    pub resistant_id: u32,
82    // #[serde(flatten)] not working: https://github.com/jamesmunns/postcard/issues/29
83    fn_container: FnContainer<PT>,
84}
85
86impl<PT: ProtocolTypes> Eq for Function<PT> {}
87impl<PT: ProtocolTypes> Hash for Function<PT> {
88    fn hash<H: Hasher>(&self, state: &mut H) {
89        self.fn_container.hash(state)
90    }
91}
92
93impl<PT: ProtocolTypes> PartialEq for Function<PT> {
94    fn eq(&self, other: &Self) -> bool {
95        self.fn_container == other.fn_container
96    }
97}
98
99impl<PT: ProtocolTypes> Clone for Function<PT> {
100    fn clone(&self) -> Self {
101        Function {
102            unique_id: random(),
103            resistant_id: self.resistant_id,
104            fn_container: self.fn_container.clone(),
105        }
106    }
107}
108
109impl<PT: ProtocolTypes> Function<PT> {
110    pub fn attrs(&self) -> FunctionAttributes {
111        self.fn_container.attrs
112    }
113
114    pub fn is_opaque(&self) -> bool {
115        self.fn_container.attrs.is_opaque
116    }
117
118    pub fn is_list(&self) -> bool {
119        self.fn_container.attrs.is_list
120    }
121
122    pub fn is_get(&self) -> bool {
123        self.fn_container.attrs.is_get
124    }
125
126    pub fn no_gen(&self) -> bool {
127        self.fn_container.attrs.no_gen
128    }
129
130    pub fn no_bit(&self) -> bool {
131        self.fn_container.attrs.no_bit
132    }
133
134    pub fn no_det(&self) -> bool {
135        self.fn_container.attrs.no_det
136    }
137
138    #[must_use]
139    pub fn new(shape: DynamicFunctionShape<PT>, dynamic_fn: Box<dyn DynamicFunction<PT>>) -> Self {
140        let attrs = PT::signature()
141            .attrs_by_name
142            .get(shape.name)
143            .copied()
144            .unwrap_or_default(); // Default to empty attributes, use Signature::new to provide attributes
145        Self {
146            unique_id: random(),
147            resistant_id: random(),
148            fn_container: FnContainer {
149                shape,
150                dynamic_fn,
151                attrs,
152            },
153        }
154    }
155
156    #[must_use]
157    pub fn arity(&self) -> u16 {
158        self.fn_container.shape.arity()
159    }
160
161    #[must_use]
162    pub fn is_constant(&self) -> bool {
163        self.fn_container.shape.is_constant()
164    }
165
166    #[must_use]
167    pub const fn name(&self) -> &'static str {
168        self.fn_container.shape.name
169    }
170
171    #[must_use]
172    pub const fn shape(&self) -> &DynamicFunctionShape<PT> {
173        &self.fn_container.shape
174    }
175
176    #[must_use]
177    pub fn dynamic_fn(&self) -> &dyn DynamicFunction<PT> {
178        &self.fn_container.dynamic_fn
179    }
180
181    pub fn change_function(
182        &mut self,
183        shape: DynamicFunctionShape<PT>,
184        dynamic_fn: Box<dyn DynamicFunction<PT>>,
185    ) {
186        self.fn_container.shape = shape;
187        self.fn_container.dynamic_fn = dynamic_fn;
188    }
189}
190
191impl<PT: ProtocolTypes> fmt::Display for Function<PT> {
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        self.fn_container.shape.fmt(f)
194    }
195}
196
197mod fn_container {
198    use std::fmt;
199    use std::hash::{Hash, Hasher};
200
201    use serde::de::{MapAccess, SeqAccess, Visitor};
202    use serde::ser::SerializeStruct;
203    use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
204
205    use crate::algebra::dynamic_function::{
206        DynamicFunction, DynamicFunctionShape, FunctionAttributes, TypeShape,
207    };
208    use crate::algebra::signature::Signature;
209    use crate::protocol::ProtocolTypes;
210
211    const NAME: &str = "name";
212    const ARGUMENTS: &str = "arguments";
213    const RETURN: &str = "return";
214    const FIELDS: &[&str] = &[NAME, ARGUMENTS, RETURN];
215
216    #[derive(Clone, Debug)]
217    pub struct FnContainer<PT: ProtocolTypes> {
218        pub shape: DynamicFunctionShape<PT>,
219        pub dynamic_fn: Box<dyn DynamicFunction<PT>>,
220        pub attrs: FunctionAttributes,
221    }
222
223    impl<PT: ProtocolTypes> Hash for FnContainer<PT> {
224        fn hash<H: Hasher>(&self, state: &mut H) {
225            self.shape.hash(state);
226        }
227    }
228
229    impl<PT: ProtocolTypes> Eq for FnContainer<PT> {}
230    impl<PT: ProtocolTypes> PartialEq for FnContainer<PT> {
231        fn eq(&self, other: &Self) -> bool {
232            // shape already identifies the function container
233            self.shape == other.shape
234        }
235    }
236
237    impl<PT: ProtocolTypes> Serialize for FnContainer<PT> {
238        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
239        where
240            S: Serializer,
241        {
242            let mut state = serializer.serialize_struct("FnContainer", FIELDS.len())?;
243            state.serialize_field(NAME, &self.shape.name)?;
244            state.serialize_field(ARGUMENTS, &self.shape.argument_types)?;
245            state.serialize_field(RETURN, &self.shape.return_type)?;
246            state.end()
247        }
248    }
249
250    struct FnContainerVisitor<PT: ProtocolTypes> {
251        signature: &'static Signature<PT>,
252    }
253
254    impl<'de, PT: ProtocolTypes> Visitor<'de> for FnContainerVisitor<PT> {
255        type Value = FnContainer<PT>;
256
257        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
258            formatter.write_str("struct FnContainer")
259        }
260
261        fn visit_seq<V>(self, mut seq: V) -> Result<FnContainer<PT>, V::Error>
262        where
263            V: SeqAccess<'de>,
264        {
265            let name: &str = seq
266                .next_element()?
267                .ok_or_else(|| de::Error::invalid_length(0, &self))?;
268            let argument_types: Vec<TypeShape<PT>> = seq
269                .next_element()?
270                .ok_or_else(|| de::Error::invalid_length(1, &self))?;
271            let return_type: TypeShape<PT> = seq
272                .next_element()?
273                .ok_or_else(|| de::Error::invalid_length(2, &self))?;
274
275            let (shape, dynamic_fn) = self
276                .signature
277                .functions_by_name
278                .get(name)
279                .ok_or_else(|| de::Error::custom(format!("could not find function {name}")))?;
280
281            let attrs = self
282                .signature
283                .attrs_by_name
284                .get(name)
285                .copied()
286                .ok_or_else(|| de::Error::custom(format!("could not find function {name}")))?;
287
288            if name != shape.name {
289                return Err(de::Error::custom("Function<PT> name does not match!"));
290            }
291
292            if return_type != shape.return_type || argument_types != shape.argument_types {
293                return Err(de::Error::custom(
294                    "Return types or argument types do not match!",
295                ));
296            }
297
298            Ok(FnContainer {
299                shape: shape.clone(),
300                dynamic_fn: dynamic_fn.clone(),
301                attrs,
302            })
303        }
304
305        fn visit_map<V>(self, mut map: V) -> Result<FnContainer<PT>, V::Error>
306        where
307            V: MapAccess<'de>,
308        {
309            let mut name: Option<&'de str> = None;
310            let mut arguments: Option<Vec<TypeShape<PT>>> = None;
311            let mut ret: Option<TypeShape<PT>> = None;
312            while let Some(key) = map.next_key()? {
313                match key {
314                    NAME => {
315                        if name.is_some() {
316                            return Err(de::Error::duplicate_field(NAME));
317                        }
318                        name = Some(map.next_value()?);
319                    }
320                    ARGUMENTS => {
321                        if arguments.is_some() {
322                            return Err(de::Error::duplicate_field(ARGUMENTS));
323                        }
324                        arguments = Some(map.next_value()?);
325                    }
326                    RETURN => {
327                        if ret.is_some() {
328                            return Err(de::Error::duplicate_field(RETURN));
329                        }
330                        ret = Some(map.next_value()?);
331                    }
332                    _ => {
333                        return Err(de::Error::unknown_field(key, FIELDS));
334                    }
335                }
336            }
337
338            let name = name.ok_or_else(|| de::Error::missing_field(NAME))?;
339            let (shape, dynamic_fn) =
340                self.signature.functions_by_name.get(name).ok_or_else(|| {
341                    de::Error::custom(format!(
342                        "Failed to link function symbol: Could not find function {name}"
343                    ))
344                })?;
345            let attrs = self
346                .signature
347                .attrs_by_name
348                .get(name)
349                .copied()
350                .ok_or_else(|| {
351                    de::Error::custom(format!(
352                        "Failed to link function symbol: Could not find function {name}"
353                    ))
354                })?;
355
356            let argument_types = arguments.ok_or_else(|| de::Error::missing_field(ARGUMENTS))?;
357            let return_type = ret.ok_or_else(|| de::Error::missing_field(RETURN))?;
358
359            if name != shape.name {
360                return Err(de::Error::custom("Function<PT> name does not match!"));
361            }
362
363            if return_type != shape.return_type || argument_types != shape.argument_types {
364                return Err(de::Error::custom(
365                    "Return types or argument types do not match!",
366                ));
367            }
368
369            Ok(FnContainer {
370                shape: shape.clone(),
371                dynamic_fn: dynamic_fn.clone(),
372                attrs,
373            })
374        }
375    }
376
377    impl<'de, PT: ProtocolTypes> Deserialize<'de> for FnContainer<PT> {
378        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
379        where
380            D: Deserializer<'de>,
381        {
382            deserializer.deserialize_struct(
383                "FnContainer",
384                FIELDS,
385                FnContainerVisitor {
386                    signature: PT::signature(),
387                },
388            )
389        }
390    }
391}