1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
use anyhow::{bail, Error, Result};

use dcbor::prelude::*;

use crate::{Envelope, EnvelopeEncodable, Function, Parameter};

#[derive(Debug, Clone, PartialEq)]
pub struct Expression {
    function: Function,
    envelope: Envelope,
}

impl Expression {
    pub fn new(function: impl Into<Function>) -> Self {
        let function = function.into();
        Self {
            function: function.clone(),
            envelope: Envelope::new(function),
        }
    }
}

impl std::fmt::Display for Expression {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.envelope.format())
    }
}

pub trait ExpressionBehavior {
    //
    // Composition
    //

    /// Adds a parameter to the expression.
    fn with_parameter(self, parameter: impl Into<Parameter>, value: impl EnvelopeEncodable) -> Self;

    /// Adds a parameter to the expression, if the value is not `None`.
    fn with_optional_parameter(self, parameter: impl Into<Parameter>, value: Option<impl EnvelopeEncodable>) -> Self;

    //
    // Parsing
    //

    /// Returns the function of the expression.
    fn function(&self) -> &Function;

    /// Returns the envelope of the expression.
    fn expression_envelope(&self) -> &Envelope;

    /// Returns the argument for the given parameter.
    fn object_for_parameter(&self, param: impl Into<Parameter>) -> Result<Envelope>;

    /// Returns the arguments for the given possibly repeated parameter.
    fn objects_for_parameter(&self, param: impl Into<Parameter>) -> Vec<Envelope>;

    /// Returns the argument for the given parameter, decoded as the given type.
    ///
    /// - Throws: Throws an exception if there is not exactly one matching `parameter`,
    /// or if the parameter value is not the correct type.
    fn extract_object_for_parameter<T>(&self, param: impl Into<Parameter>) -> Result<T>
    where
        T: TryFrom<CBOR, Error = Error> + 'static;

    /// Returns the argument for the given parameter, or `None` if there is no matching parameter.
    fn extract_optional_object_for_parameter<T: TryFrom<CBOR, Error = Error> + 'static>(
        &self,
        param: impl Into<Parameter>,
    ) -> Result<Option<T>>;

    /// Returns an array of arguments for the given parameter, decoded as the given type.
    ///
    /// - Throws: Throws an exception if any of the parameter values are not the correct type.
    fn extract_objects_for_parameter<T>(&self, param: impl Into<Parameter>) -> Result<Vec<T>>
    where
        T: TryFrom<CBOR, Error = Error> + 'static;
}

impl ExpressionBehavior for Expression {
    fn with_parameter(
        mut self,
        parameter: impl Into<Parameter>,
        value: impl EnvelopeEncodable,
    ) -> Self {
        let assertion = Envelope::new_assertion(parameter.into(), value.into_envelope());
        self.envelope = self.envelope.add_assertion_envelope(assertion).unwrap();
        self
    }

    fn with_optional_parameter(
        self,
        parameter: impl Into<Parameter>,
        value: Option<impl EnvelopeEncodable>,
    ) -> Self {
        if let Some(value) = value {
            return self.with_parameter(parameter, value);
        }
        self
    }

    fn function(&self) -> &Function {
        &self.function
    }

    fn expression_envelope(&self) -> &Envelope {
        &self.envelope
    }

    fn object_for_parameter(&self, param: impl Into<Parameter>) -> Result<Envelope> {
        self.envelope.object_for_predicate(param.into())
    }

    fn objects_for_parameter(&self, param: impl Into<Parameter>) -> Vec<Envelope> {
        self.envelope.objects_for_predicate(param.into())
    }

    fn extract_object_for_parameter<T>(&self, param: impl Into<Parameter>) -> Result<T>
    where
        T: TryFrom<CBOR, Error = Error> + 'static,
    {
        self.envelope.extract_object_for_predicate(param.into())
    }

    fn extract_optional_object_for_parameter<T: TryFrom<CBOR, Error = Error> + 'static>(
        &self,
        param: impl Into<Parameter>,
    ) -> Result<Option<T>> {
        self.envelope
            .extract_optional_object_for_predicate(param.into())
    }

    fn extract_objects_for_parameter<T>(&self, param: impl Into<Parameter>) -> Result<Vec<T>>
    where
        T: TryFrom<CBOR, Error = Error> + 'static,
    {
        self.envelope.extract_objects_for_predicate(param.into())
    }
}

/// Expression -> Envelope
impl From<Expression> for Envelope {
    fn from(expression: Expression) -> Self {
        expression.envelope
    }
}

/// Envelope -> Expression
impl TryFrom<Envelope> for Expression {
    type Error = Error;

    fn try_from(envelope: Envelope) -> Result<Self> {
        Ok(Self {
            function: envelope.extract_subject()?,
            envelope,
        })
    }
}

/// Envelope + optional expected function -> Expression
impl TryFrom<(Envelope, Option<&Function>)> for Expression {
    type Error = Error;

    fn try_from((envelope, expected_function): (Envelope, Option<&Function>)) -> Result<Self> {
        let expression = Expression::try_from(envelope)?;
        if let Some(expected_function) = expected_function {
            if expression.function() != expected_function {
                bail!(
                    "Expected function {:?}, but found {:?}",
                    expected_function,
                    expression.function()
                );
            }
        }
        Ok(expression)
    }
}

pub trait IntoExpression {
    fn into_expression(self) -> Expression;
    fn to_expression(&self) -> Expression;
}

impl<T: Into<Expression> + Clone + ?Sized> IntoExpression for T {
    fn into_expression(self) -> Expression {
        self.into()
    }

    fn to_expression(&self) -> Expression {
        self.clone().into()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{functions, parameters};
    use indoc::indoc;

    #[test]
    fn test_expression_1() -> Result<()> {
        let expression = Expression::new(functions::ADD)
            .with_parameter(parameters::LHS, 2)
            .with_parameter(parameters::RHS, 3);

        let envelope: Envelope = expression.clone().into();

        // println!("{}", envelope.format());
        assert_eq!(
            envelope.format(),
            indoc! {r#"
        «add» [
            ❰lhs❱: 2
            ❰rhs❱: 3
        ]
        "#}
            .trim()
        );

        let parsed_expression = Expression::try_from(envelope)?;

        assert_eq!(
            parsed_expression.extract_object_for_parameter::<i32>(parameters::LHS)?,
            2
        );
        assert_eq!(
            parsed_expression.extract_object_for_parameter::<i32>(parameters::RHS)?,
            3
        );

        assert_eq!(parsed_expression.function(), expression.function());
        assert_eq!(parsed_expression.expression_envelope(), expression.expression_envelope());
        assert_eq!(expression, parsed_expression);

        Ok(())
    }

    #[test]
    fn test_expression_2() -> Result<()> {
        let expression = Expression::new("foo")
            .with_parameter("bar", "baz")
            .with_optional_parameter("qux", None::<&str>);

        let envelope: Envelope = expression.clone().into();

        // println!("{}", envelope.format());
        assert_eq!(
            envelope.format(),
            indoc! {r#"
        «"foo"» [
            ❰"bar"❱: "baz"
        ]
        "#}
            .trim()
        );

        let parsed_expression = Expression::try_from(envelope)?;

        assert_eq!(
            parsed_expression.extract_object_for_parameter::<String>("bar")?,
            "baz"
        );
        assert_eq!(
            parsed_expression.extract_optional_object_for_parameter::<i32>("qux")?,
            None
        );

        assert_eq!(parsed_expression.function(), expression.function());
        assert_eq!(parsed_expression.expression_envelope(), expression.expression_envelope());
        assert_eq!(expression, parsed_expression);

        Ok(())
    }
}