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
use std::fmt::{Debug, Display};
use std::str::FromStr;
use std::ops::{Add, Sub, Mul, Div, Rem, Not};

use crate::error::*;
pub use bigdecimal::*;
use crate::table::Table;

pub type Contents = Vec<BigDecimal>;
pub const NOTHING : &[BigDecimal] = &[];


fn to_decimal(num: f64) -> BigDecimal {
    match BigDecimal::from_str(&num.to_string()) {
        Ok(v) => v,
        Err(_) => BigDecimal::from_str("0").unwrap()
    }
}


fn from_string(string: String) -> Contents {
    let mut result = vec![];
    for ch in string.chars() {
        result.push(
            match BigDecimal::from_str(&(ch as i32).to_string()) {
                Ok(s) => s,
                Err(_) => return NOTHING.to_vec()
            }
        );
    }
    return result;
}


fn from_number(number: BigDecimal) -> Contents {
    return vec![number];
}


#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Instruction {
    Print,
    Println,
    While,
    If,
    Append,
    Pop,
    Index,
    Equal,
    Greater,
    Less,
    Not,
    Add,
    Mul,
    Sub,
    Div,
    Mod,
    Call,
    Load,
    Store,
    GetAttr,
    SetAttr,
    Execute,
    Pass
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Problem {
    IncompatibleTypes,
    ValueError,
    OutOfRange,
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Type {
    Str,
    Num,
    List,
    Function,
    Instance,
    Problem(Problem),
    Nothing,
    Command(Instruction)
}


pub trait Object: Sized + Clone + Debug + Display + Add + Sub + Mul + Div + Rem + Not {
    // initializers
    fn new(value_type: Type, contents: Contents) -> Self;

    fn empty_instance() -> Self {
        return Self::new(Type::Instance, NOTHING.to_vec());
    }

    fn from_string(string: String) -> Self {
        return Self::new(Type::Str, from_string(string));
    }

    fn from_str(string: &str) -> Self {
        return Self::new(Type::Str, from_string(string.to_string()));
    }

    fn from_f64(decimal: f64) -> Self {
        return Self::new(Type::Num, from_number(to_decimal(decimal)));
    }

    fn from_number(decimal: BigDecimal) -> Self {
        return Self::new(Type::Num, from_number(decimal));
    }

    fn from_instruction(instruction: Instruction) -> Self {
        return Self::new(Type::Command(instruction), NOTHING.to_vec());
    }

    fn from_problem(problem: Problem) -> Self {
        return Self::new(Type::Problem(problem), NOTHING.to_vec());
    }

    fn from_vector(vector: Vec<Self>) -> Self {
        let mut instance = Self::new(Type::List, NOTHING.to_vec());
        instance.set_list(vector);
        return instance;
    }

    fn from_nothing() -> Self {
        Self::new(
            Type::Nothing,
            NOTHING.to_vec()
            )
    }

    fn from_function(vector: Vec<Self>) -> Self {
        let mut instance = Self::new(Type::Function, NOTHING.to_vec());
        instance.set_list(vector);
        return instance;
    }

    fn from_foreign_function(function: fn(Self) -> Self) -> Self {
        let mut instance = Self::new(
            Type::Function,
            NOTHING.to_vec()
            );
        instance.set_foreign_function(function);
        return instance;
    }

    // helper functions
    fn get_type(&self) -> Type;
    fn get_list(&self) -> Vec<Self>;
    fn get_contents(&self) -> Contents;
    fn get_attributes(&self) -> Table<Self>;
    fn get_foreign_function(&self) -> fn(Self) -> Self;

    fn set_type(&mut self, object_type: Type);
    fn set_list(&mut self, list: Vec<Self>);
    fn set_contents(&mut self, contents: Contents);
    fn set_attributes(&mut self, attributes: Table<Self>);
    fn set_foreign_function(&mut self, function: fn(Self) -> Self);

    // getters
    fn get_attr(&self, name: String) -> Self {
        let table = self.get_attributes();
        let raw_attr = table.get(name);
        let attr = match raw_attr {
            Some(s) => s,
            None => Self::new(Type::Nothing, NOTHING.to_vec())
        };
        return attr;
    }

    fn as_number(&self) -> BigDecimal {
        if self.get_contents().len() > 0 {
            self.get_contents()[0].clone()
        } else {
            BigDecimal::from_str("0").unwrap()
        }
    }

    fn as_usize(&self) -> usize {
        if self.get_contents().len() > 0 {
            match self.get_contents()[0].to_i32() {
                Some(i) => i as usize,
                None => 0 as usize
            }
        } else {
            0 as usize
        }
    }

    fn as_string(&self) -> String {
        let mut result = "".to_string();

        for ch in self.get_contents() {
            let character = match ch.to_i32() {
                Some(i) => i as u8 as char,
                None => ' '
            };
            result += &character.to_string();
        }
        return result.to_string();
    }
    
    fn as_list(&self) -> Vec<Self> {
        self.get_list()
    }

    fn as_instruction(&self) -> Instruction {
        match self.get_type() {
            Type::Command(i) => i,
            _ => Instruction::Pass
        }
    }
    
    fn as_instance(&self) -> Table<Self> {
        return self.get_attributes();
    }
    
    
    fn as_foreign_function(&self) -> fn(Self) -> Self {
        return self.get_foreign_function();
    }
    
    // setters
    fn set_attr(&mut self, name: String, object: Self) {
        let mut table = self.get_attributes();
        table.set(name, object);
        self.set_attributes(table);
    }

    fn get_attr_recursive(&mut self, names: Vec<String>) -> Self {
        if names.len() < 1 {
            throw_no_stack("Could not set attribute of object without the attribute name");
        }

        let name = &names[0];
        let table = self.get_attributes();
        if names.len() == 1 {

            match table.get(name.to_string()) {
                Some(o) => o,
                None => Self::from_nothing()
            }

        } else {

            match table.get(name.to_string()) {
                Some(o) => o,
                None => Self::empty_instance()
            }.get_attr_recursive(names[1..].to_vec())
        }
    }

    fn set_attr_recursive(&mut self, names: Vec<String>, object: Self) -> Self {
        if names.len() < 1 {
            throw_no_stack("Could not set attribute of object without the attribute name");
        }

        let name = &names[0];
        let mut table = self.get_attributes();

        if names.len() == 1 {

            table.set(name.to_string(), object);
            self.set_attributes(table);

        } else {

            table.set(
                name.to_string(),
                match table.get(name.to_string()) {
                    Some(o) => o,
                    None => Self::empty_instance()
                }
                    .set_attr_recursive(names[1..].to_vec(), object));
            self.set_attributes(table);

        }
        self.clone()
    }


    fn index(&mut self, index: Self) -> Self {
        let my_type = self.get_type();
        match my_type {
            Type::Str => match self.as_string().chars().nth(index.as_usize()) {
                Some(c) => {
                    let mut string = String::new();
                    string.push(c);
                    Self::from_string(string)
                },
                None => {
                    Self::from_problem(
                        Problem::OutOfRange
                    )
                }
            },
            Type::List => self.as_list()[index.as_usize()].clone(),
            Type::Function => self.as_list()[index.as_usize()].clone(),
            _ => Self::from_problem(Problem::ValueError)
        }
    }

    fn list_push(&mut self, object: Self) {
        self.set_type(Type::List);

        let mut list = self.get_list();
        list.push(object);
        self.set_list(list);
    }

    fn list_pop(&mut self) -> Self {
        match self.get_list().pop() {
            Some(e) => e,
            None => Self::new(Type::Nothing, NOTHING.to_vec())
        }
    }

    fn call_foreign_function(&mut self, parameter: Self) -> Self {
        self.get_foreign_function()(parameter)
    }

    fn format(&self) -> String {
        let object_type = self.get_type();
        match object_type {
            Type::Str => format!("{}", self.as_string()),
            Type::Num => format!("{}", self.as_number()),
            Type::List => {
                if self.as_list().len() == 0 {
                    return "[]".to_string();
                }
                let mut result = "[".to_string();
                for item in self.as_list() {
                    result += &item.format();
                    result += ", ";
                }
                result.pop();
                result.pop();
                result + "]"
                },
            Type::Instance => {

                if self.get_attributes().keys().len() < 1 {
                    "<>".to_string()
                } else {
                    let mut result = "<".to_string();
                    for key in self.get_attributes().keys() {
                        result += &key;
                        result += ":";
                        result += &self.get_attr(key).format();
                        result += ", ";
                    }
                    result.pop();
                    result.pop();
                    result + ">"
                }

            },
            Type::Function => format!("Function"),
            Type::Nothing => format!("None"),
            Type::Problem(p) => format!("{:?}", p),
            Type::Command(c) => format!("{:?}", c),
        }
    }

    fn print(&self) {
        print!("{}", self.format());
    }

    fn println(&self) {
        println!("{}", self.format());
    }
}