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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use crate::core::Function;
use crate::lang::lir;
use crate::lang::lir::{Field, InnerType};
use crate::lang::mir::TypeHandle;
use crate::lang::parser::Located;
use crate::runtime::RuntimeError;
use indexmap::IndexMap;
use serde::Serialize;
use serde_json::{json, Map, Number};
use std::any::Any;
use std::borrow::Borrow;
use std::cell::{Ref, RefCell};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt::{Debug, Display, Formatter, Pointer};
use std::future::{ready, Future};
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::rc::Rc;
use std::sync::Arc;

mod json;

struct Printer {
    indent: u8,
    content: String,
}

impl Printer {
    fn new() -> Self {
        Self {
            indent: 0,
            content: String::new(),
        }
    }

    fn write(&mut self, value: &str) {
        self.content.push_str(value);
    }

    fn write_with_indent(&mut self, value: &str) {
        self.content.push('\n');
        self.content.push_str(self.indent().as_str());
        self.content.push_str(value);
    }

    fn indent(&self) -> String {
        let mut spacing = String::new();
        for _ in 0..(self.indent * 2) {
            spacing.push(' ');
        }
        spacing
    }
}

#[derive(Debug, Clone)]
pub enum RationaleResult {
    None,
    Same(Rc<RuntimeValue>),
    Transform(Rc<RuntimeValue>),
}

impl Display for RationaleResult {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            RationaleResult::None => {
                write!(f, "None")
            }
            RationaleResult::Same(_) => {
                write!(f, "Same")
            }
            RationaleResult::Transform(_) => {
                write!(f, "Transform")
            }
        }
    }
}

impl RationaleResult {
    pub fn is_some(&self) -> bool {
        !matches!(self, RationaleResult::None)
    }

    pub fn is_none(&self) -> bool {
        !self.is_some()
    }
}

impl PartialEq<Self> for RuntimeValue {
    fn eq(&self, other: &Self) -> bool {
        match (&self, &other) {
            (Self::Boolean(lhs), Self::Boolean(rhs)) => lhs == rhs,
            (Self::Integer(lhs), Self::Integer(rhs)) => lhs == rhs,
            (Self::Decimal(lhs), Self::Decimal(rhs)) => lhs == rhs,
            (Self::String(lhs), Self::String(rhs)) => lhs == rhs,
            _ => false,
        }
    }
}

impl PartialOrd for RuntimeValue {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (&self, &other) {
            (Self::Boolean(lhs), Self::Boolean(rhs)) => lhs.partial_cmp(rhs),
            (Self::Integer(lhs), Self::Integer(rhs)) => lhs.partial_cmp(rhs),
            (Self::Decimal(lhs), Self::Decimal(rhs)) => lhs.partial_cmp(rhs),
            (Self::Decimal(lhs), Self::Integer(rhs)) => lhs.partial_cmp(&(*rhs as f64)),
            (Self::Integer(lhs), Self::Decimal(rhs)) => (*lhs as f64).partial_cmp(rhs),
            (Self::String(lhs), Self::String(rhs)) => lhs.partial_cmp(rhs),
            _ => None,
        }
    }
}

impl From<&str> for RuntimeValue {
    fn from(inner: &str) -> Self {
        Self::String(inner.to_string())
    }
}

impl From<u8> for RuntimeValue {
    fn from(inner: u8) -> Self {
        Self::Integer(inner as _)
    }
}

impl From<u32> for RuntimeValue {
    fn from(inner: u32) -> Self {
        Self::Integer(inner as _)
    }
}

impl From<i64> for RuntimeValue {
    fn from(inner: i64) -> Self {
        Self::Integer(inner)
    }
}

impl From<usize> for RuntimeValue {
    fn from(inner: usize) -> Self {
        Self::Integer(inner as _)
    }
}

impl From<f64> for RuntimeValue {
    fn from(inner: f64) -> Self {
        Self::Decimal(inner)
    }
}

impl From<bool> for RuntimeValue {
    fn from(inner: bool) -> Self {
        Self::Boolean(inner)
    }
}

impl From<String> for RuntimeValue {
    fn from(inner: String) -> Self {
        Self::String(inner)
    }
}

impl From<Vec<u8>> for RuntimeValue {
    fn from(inner: Vec<u8>) -> Self {
        Self::Octets(inner)
    }
}

impl From<&[u8]> for RuntimeValue {
    fn from(inner: &[u8]) -> Self {
        inner.to_vec().into()
    }
}

impl From<Vec<RuntimeValue>> for RuntimeValue {
    fn from(inner: Vec<RuntimeValue>) -> Self {
        Self::List(inner.into_iter().map(Rc::new).collect())
    }
}

impl From<Vec<Rc<RuntimeValue>>> for RuntimeValue {
    fn from(value: Vec<Rc<RuntimeValue>>) -> Self {
        Self::List(value)
    }
}

impl From<&[RuntimeValue]> for RuntimeValue {
    fn from(inner: &[RuntimeValue]) -> Self {
        Self::List(inner.iter().map(|e| Rc::new(e.clone())).collect())
    }
}

impl From<Object> for RuntimeValue {
    fn from(inner: Object) -> Self {
        Self::Object(inner)
    }
}

#[derive(Serialize, Debug, Clone)]
pub enum RuntimeValue {
    Null,
    String(String),
    Integer(i64),
    Decimal(f64),
    Boolean(bool),
    Object(Object),
    List(#[serde(skip)] Vec<Rc<RuntimeValue>>),
    Octets(Vec<u8>),
}

impl Display for RuntimeValue {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Null => write!(f, "<null>"),
            Self::String(val) => write!(f, "{}", val),
            Self::Integer(val) => write!(f, "{}", val),
            Self::Decimal(val) => write!(f, "{}", val),
            Self::Boolean(val) => write!(f, "{}", val),
            Self::Object(val) => Display::fmt(val, f),
            Self::List(val) => write!(f, "[ <<things>> ]"),
            Self::Octets(val) => write!(f, "[ <<octets>> ]"),
        }
    }
}

impl RuntimeValue {
    pub fn type_name(&self) -> &'static str {
        match self {
            Self::Null => "null",
            Self::String(_) => "string",
            Self::Integer(_) => "integer",
            Self::Decimal(_) => "decimal",
            Self::Boolean(_) => "boolean",
            Self::Object(_) => "object",
            Self::List(_) => "list",
            Self::Octets(_) => "octets",
        }
    }

    pub fn as_json(&self) -> serde_json::Value {
        match self {
            Self::Null => serde_json::Value::Null,
            Self::String(val) => serde_json::Value::String(val.clone()),
            Self::Integer(val) => serde_json::Value::Number(Number::from(*val)),
            Self::Decimal(val) => json!(val),
            Self::Boolean(val) => serde_json::Value::Bool(*val),
            Self::Object(val) => val.as_json(),
            Self::List(val) => {
                let mut inner = Vec::new();
                for each in val {
                    inner.push((**each).borrow().as_json())
                }
                serde_json::Value::Array(inner)
            }
            Self::Octets(val) => {
                let mut octets = String::new();
                for chunk in val.chunks(16) {
                    for octet in chunk {
                        octets.push_str(format!("{:02x} ", octet).as_str());
                    }
                    //octets.push( '\n');
                }
                serde_json::Value::String(octets)
            }
        }
    }

    pub fn with_iter<I, T>(iter: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<RuntimeValue>,
    {
        RuntimeValue::List(iter.into_iter().map(|e| Rc::new(e.into())).collect())
    }
}

impl RuntimeValue {
    pub fn null() -> Self {
        Self::Null
    }

    pub fn is_string(&self) -> bool {
        matches!(self, Self::String(_))
    }

    pub fn try_get_string(&self) -> Option<String> {
        if let Self::String(inner) = self {
            Some(inner.clone())
        } else {
            None
        }
    }

    pub fn is_integer(&self) -> bool {
        matches!(self, Self::Integer(_))
    }

    pub fn try_get_integer(&self) -> Option<i64> {
        if let Self::Integer(inner) = self {
            Some(*inner)
        } else {
            None
        }
    }

    pub fn is_decimal(&self) -> bool {
        matches!(self, Self::Decimal(_))
    }

    pub fn try_get_decimal(&self) -> Option<f64> {
        if let Self::Decimal(inner) = self {
            Some(*inner)
        } else {
            None
        }
    }

    pub fn is_boolean(&self) -> bool {
        matches!(self, Self::Boolean(_))
    }

    pub fn try_get_boolean(&self) -> Option<bool> {
        if let Self::Boolean(inner) = self {
            Some(*inner)
        } else {
            None
        }
    }

    pub fn is_list(&self) -> bool {
        matches!(self, Self::List(_))
    }

    pub fn try_get_list(&self) -> Option<&Vec<Rc<RuntimeValue>>> {
        if let Self::List(inner) = self {
            Some(inner)
        } else {
            None
        }
    }

    pub fn is_object(&self) -> bool {
        matches!(self, Self::Object(_))
    }

    pub fn try_get_object(&self) -> Option<&Object> {
        if let Self::Object(inner) = self {
            Some(inner)
        } else {
            None
        }
    }

    pub fn is_octets(&self) -> bool {
        matches!(self, Self::Octets(_))
    }

    pub fn try_get_octets(&self) -> Option<&Vec<u8>> {
        if let Self::Octets(inner) = self {
            Some(inner)
        } else {
            None
        }
    }
}

#[derive(Serialize, Debug, Clone, Default)]
pub struct Object {
    #[serde(skip)]
    fields: IndexMap<String, Rc<RuntimeValue>>,
}

impl Display for Object {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        for (name, value) in &self.fields {
            writeln!(f, "{}: <<{}>>", name, value.type_name())?;
        }

        Ok(())
    }
}

impl Object {
    pub fn new() -> Self {
        Self {
            fields: Default::default(),
        }
    }

    fn as_json(&self) -> serde_json::Value {
        let mut inner = Map::new();
        for (name, value) in &self.fields {
            inner.insert(name.clone(), (**value).borrow().as_json());
        }

        serde_json::Value::Object(inner)
    }

    pub fn get<N>(&self, name: N) -> Option<Rc<RuntimeValue>>
    where
        N: AsRef<str>,
    {
        self.fields.get(name.as_ref()).cloned()
    }

    pub fn set<N, V>(&mut self, name: N, value: V)
    where
        N: Into<String>,
        V: Into<RuntimeValue>,
    {
        self.fields.insert(name.into(), Rc::new(value.into()));
    }

    pub fn iter(&self) -> impl Iterator<Item = (&String, &Rc<RuntimeValue>)> {
        self.fields.iter()
    }
}