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
use super::Address;
use crate::error;
use crate::lang::{Error, LineNumber, MaxValue};
use std::convert::TryFrom;
use std::rc::Rc;

/// ## Runtime values for stack and variables

#[derive(Debug, Clone, PartialEq)]
pub enum Val {
    String(Rc<str>),
    Single(f32),
    Double(f64),
    Integer(i16),
    Return(Address),
    Next(Address),
}

impl std::fmt::Display for Val {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use Val::*;
        let mut s = match self {
            String(s) => return write!(f, "{}", s),
            Integer(num) => format!("{}", num),
            Single(num) => {
                let s = format!("{}", num);
                if s.chars().filter(char::is_ascii_digit).count() > 9 {
                    format!("{:E}", num)
                } else {
                    format!("{}", num)
                }
            }
            Double(num) => {
                let s = format!("{}", num);
                if s.chars().filter(char::is_ascii_digit).count() > 17 {
                    format!("{:E}", num)
                } else {
                    format!("{}", num)
                }
            }
            Return(..) | Next(..) => {
                debug_assert!(false);
                return write!(f, "");
            }
        };
        if !s.starts_with('-') {
            s.insert(0, ' ');
        }
        write!(f, "{}", s)
    }
}

impl TryFrom<LineNumber> for Val {
    type Error = Error;
    fn try_from(line_number: LineNumber) -> std::result::Result<Self, Self::Error> {
        match line_number {
            Some(num) => Ok(Val::Single(num as f32)),
            None => Err(error!(UndefinedLine)),
        }
    }
}

impl TryFrom<Val> for LineNumber {
    type Error = Error;
    fn try_from(val: Val) -> std::result::Result<Self, Self::Error> {
        let num = u16::try_from(val)?;
        if num <= LineNumber::max_value() {
            Ok(Some(num))
        } else {
            Err(error!(UndefinedLine))
        }
    }
}

impl TryFrom<Val> for u16 {
    type Error = Error;
    fn try_from(val: Val) -> std::result::Result<Self, Self::Error> {
        match val {
            Val::Integer(num) => {
                if num >= 0 {
                    Ok(num as u16)
                } else {
                    Err(error!(Overflow))
                }
            }
            Val::Single(num) => {
                let num = num.floor();
                if num >= 0.0 && num <= u16::max_value() as f32 {
                    Ok(num as u16)
                } else {
                    Err(error!(Overflow))
                }
            }
            Val::Double(num) => {
                let num = num.floor();
                if num >= 0.0 && num <= u16::max_value() as f64 {
                    Ok(num as u16)
                } else {
                    Err(error!(Overflow))
                }
            }
            Val::String(_) | Val::Return(_) | Val::Next(..) => Err(error!(TypeMismatch)),
        }
    }
}

impl TryFrom<Val> for i16 {
    type Error = Error;
    fn try_from(val: Val) -> std::result::Result<Self, Self::Error> {
        match val {
            Val::Integer(num) => Ok(num),
            Val::Single(num) => {
                let num = num.floor();
                if num >= i16::min_value() as f32 && num <= i16::max_value() as f32 {
                    Ok(num as i16)
                } else {
                    Err(error!(Overflow))
                }
            }
            Val::Double(num) => {
                let num = num.floor();
                if num >= i16::min_value() as f64 && num <= i16::max_value() as f64 {
                    Ok(num as i16)
                } else {
                    Err(error!(Overflow))
                }
            }
            Val::String(_) | Val::Return(_) | Val::Next(..) => Err(error!(TypeMismatch)),
        }
    }
}

impl TryFrom<Val> for u32 {
    type Error = Error;
    fn try_from(val: Val) -> std::result::Result<Self, Self::Error> {
        match val {
            Val::Integer(num) => {
                if num >= 0 {
                    Ok(num as u32)
                } else {
                    Err(error!(Overflow))
                }
            }
            Val::Single(num) => {
                let num = num.floor();
                if num >= 0.0 && num <= u32::max_value() as f32 {
                    Ok(num as u32)
                } else {
                    Err(error!(Overflow))
                }
            }
            Val::Double(num) => {
                let num = num.floor();
                if num >= 0.0 && num <= u32::max_value() as f64 {
                    Ok(num as u32)
                } else {
                    Err(error!(Overflow))
                }
            }
            Val::String(_) | Val::Return(_) | Val::Next(..) => Err(error!(TypeMismatch)),
        }
    }
}

impl TryFrom<Val> for usize {
    type Error = Error;
    fn try_from(val: Val) -> std::result::Result<Self, Self::Error> {
        match val {
            Val::Integer(num) => {
                if num >= 0 {
                    Ok(num as usize)
                } else {
                    Err(error!(Overflow))
                }
            }
            Val::Single(num) => {
                let num = num.floor();
                if num >= 0.0 && num <= usize::max_value() as f32 {
                    Ok(num as usize)
                } else {
                    Err(error!(Overflow))
                }
            }
            Val::Double(num) => {
                let num = num.floor();
                if num >= 0.0 && num <= usize::max_value() as f64 {
                    Ok(num as usize)
                } else {
                    Err(error!(Overflow))
                }
            }
            Val::String(_) | Val::Return(_) | Val::Next(..) => Err(error!(TypeMismatch)),
        }
    }
}

impl TryFrom<Val> for f32 {
    type Error = Error;
    fn try_from(val: Val) -> std::result::Result<Self, Self::Error> {
        match val {
            Val::Integer(num) => Ok(num as f32),
            Val::Single(num) => Ok(num),
            Val::Double(num) => Ok(num as f32),
            Val::String(_) | Val::Return(_) | Val::Next(..) => Err(error!(TypeMismatch)),
        }
    }
}

impl TryFrom<Val> for f64 {
    type Error = Error;
    fn try_from(val: Val) -> std::result::Result<Self, Self::Error> {
        match val {
            Val::Integer(num) => Ok(num as f64),
            Val::Single(num) => Ok(num as f64),
            Val::Double(num) => Ok(num),
            Val::String(_) | Val::Return(_) | Val::Next(..) => Err(error!(TypeMismatch)),
        }
    }
}

impl TryFrom<Val> for Rc<str> {
    type Error = Error;
    fn try_from(val: Val) -> std::result::Result<Self, Self::Error> {
        match val {
            Val::String(s) => Ok(s),
            _ => Err(error!(TypeMismatch)),
        }
    }
}

impl From<&str> for Val {
    fn from(string: &str) -> Self {
        if string.starts_with('&') {
            let string = &string[1..];
            if string.starts_with('H') || string.starts_with('h') {
                if let Ok(num) = i16::from_str_radix(&string[1..], 16) {
                    return Val::Integer(num);
                }
            } else if let Ok(num) = i16::from_str_radix(&string, 8) {
                return Val::Integer(num);
            }
        }
        let mut s = String::from(string).replace("D", "E").replace("d", "e");
        match s.chars().last() {
            Some('!') | Some('#') | Some('%') => {
                s.pop();
            }
            _ => {}
        };
        if let Ok(num) = s.parse::<f64>() {
            Val::Double(num)
        } else {
            Val::String(string.into())
        }
    }
}

impl TryFrom<usize> for Val {
    type Error = Error;
    fn try_from(num: usize) -> std::result::Result<Self, Self::Error> {
        match i16::try_from(num) {
            Ok(len) => Ok(Val::Integer(len)),
            Err(_) => {
                debug_assert!(false, "LEN VAL TOO BIG");
                Err(error!(Overflow))
            }
        }
    }
}