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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
use num_enum::IntoPrimitive;
use std::fmt;

use num_enum::TryFromPrimitive;

#[derive(IntoPrimitive, TryFromPrimitive, Copy, Clone, PartialEq, Debug)]
#[repr(u8)]
#[allow(missing_docs)]
pub enum BasicTokenNoPrefix {
    EndOfTokenisedLine = 0,

    StatementSeparator = 1,

    IntegerVariableDefinition = 2,
    StringVariableDefinition = 3,
    FloatingPointVariableDefinition = 4,

    VarUnknown1 = 6,
    VarUnknown2 = 7,
    VarUnknown3 = 8,
    VarUnknown4 = 9,
    VarUnknown5 = 0xa,

    VariableDefinition1 = 0xb,
    VariableDefinition2 = 0xc,
    VariableDefinition3 = 0xd,

    ConstantNumber0 = 0x0e,
    ConstantNumber1 = 0x0f,
    ConstantNumber2 = 0x10,
    ConstantNumber3 = 0x11,
    ConstantNumber4 = 0x12,
    ConstantNumber5 = 0x13,
    ConstantNumber6 = 0x14,
    ConstantNumber7 = 0x15,
    ConstantNumber8 = 0x16,
    ConstantNumber9 = 0x17,
    ConstantNumber10 = 0x18,

    ValueIntegerDecimal8bits = 0x19,

    ValueIntegerDecimal16bits = 0x1a,
    ValueIntegerBinary16bits = 0x1b,
    ValueIntegerHexadecimal16bits = 0x1c,

    LineMemoryAddressPointer = 0x1d,
    LineNumber = 0x1e,

    ValueFloatingPoint = 0x1f,

    CharSpace = 0x20,
    CharExclamation = 0x21,

    ValueQuotedString = 0x22,

    // TODO add all ascii symbols from 23 to 7b
    CharUpperA = 65,
    CharUpperB,
    CharUpperC,
    CharUpperD,
    CharUpperE,
    CharUpperF,
    CharUpperG,
    CharUpperH,
    CharUpperI,
    CharUpperJ,
    CharUpperK,
    CharUpperL,
    CharUpperM,
    CharUpperN,
    CharUpperO,
    CharUpperP,
    CharUpperQ,
    CharUpperR,
    CharUpperS,
    CharUpperT,
    CharUpperU,
    CharUpperV,
    CharUpperW,
    CharUpperX,
    CharUpperY,
    CharUpperZ,

    CharLowerA = 97,
    CharLowerB,
    CharLowerC,
    CharLowerD,
    CharLowerE,
    CharLowerF,
    CharLowerG,
    CharLowerH,
    CharLowerI,
    CharLowerJ,
    CharLowerK,
    CharLowerL,
    CharLowerM,
    CharLowerN,
    CharLowerO,
    CharLowerP,
    CharLowerQ,
    CharLowerR,
    CharLowerS,
    CharLowerT,
    CharLowerU,
    CharLowerV,
    CharLowerW,
    CharLowerX,
    CharLowerY,
    CharLowerZ,

    Pipe = 0x7c,

    Unused7d = 0x7d,
    Unused7e = 0x7e,
    Unused7f = 0x7f,

    After = 0x80,
    Auto,
    Border,
    Call,
    Cat,
    Chain,
    Clear,
    Clg,
    Closein,
    Closeout,
    Cls,
    Cont,
    Data,
    Def,
    Defint,
    Defreal,
    Defstr,
    Deg,
    Delete,
    Dim,
    Draw,
    Drawr,
    Edit,
    Else,
    End,
    Ent,
    Env,
    Erase,
    Error,
    Every,
    For,
    Gosub,
    Goto,
    If,
    Ink,
    Input,
    Key,
    Let,
    Line,
    List,
    Load,
    Locate,
    Memory,
    Merge,
    MidDollar,
    Mode,
    Move,
    Mover,
    Next,
    New,
    On,
    OnBreak,
    OnErrorGoto,
    Sq,
    Openin,
    Openout,
    Origin,
    Out,
    Paper,
    Pen,
    Plot,
    Plotr,
    Poke,
    Print,
    SymbolQuote,
    Rad,
    Randomize,
    Read,
    Release,
    Rem,
    Renum,
    Restore,
    Resume,
    Return,
    Run,
    Save,
    Sound,
    Speed,
    Stop,
    Symbol,
    Tag,
    Tagoff,
    Troff,
    Tron,
    Wait,
    Wend,
    While,
    Width,
    Window,
    Write,
    Zone,
    Di,
    Ei,
    Fill,
    Graphics,
    Mask,
    Frame,
    Cursor,
    UnusedE2,
    Erl,
    Fn,
    Spc,
    Step,
    Swap,
    UnusedE8,
    UnusedE9,
    Tab,
    Then,
    To,
    Using,
    GreaterThan,
    Equal,
    GreaterOrEqual,
    LessThan,
    NotEqual,
    LessThanOrEqual,
    Addition,
    SubstractionOrUnaryMinus,
    Multiplication,
    Division,
    Power,
    IntegerDivision,
    And,
    Mod,
    Or,
    Xor,
    AdditionalTokenMarker,
}

impl fmt::Display for BasicTokenNoPrefix {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let tag = match self {
            Self::Call => "CALL",
            Self::Print => "PRINT",
            Self::Rem => "REM",

            Self::SymbolQuote => "'",
            Self::StatementSeparator => ":",

            Self::CharSpace => " ",

            _ => unimplemented!("{:?}", self),
        };
        write!(f, "{}", tag)
    }
}

impl BasicTokenNoPrefix {
    /// Returns the 8bit code that represents the token
    pub fn value(self) -> u8 {
        self.into()
    }
}

#[derive(IntoPrimitive, TryFromPrimitive, Copy, Clone, PartialEq, Debug)]
#[repr(u8)]
#[allow(missing_docs)]
pub enum BasicTokenPrefixed {
    Abs = 0,
    Asc,
    Atn,
    CharDollar,
    Cint,
    Cos,
    Creal,
    Exp,
    Fix,
    Fre,
    Inkey,
    Inp,
    Joy,
    Len,
    Log,
    Log10,
    LowerDollar,
    Peek,
    Remain,
    Sign,
    SpaceDollar,
    Sq,
    Sqr,
    StrDollar,
    Tan,
    Unt,
    UpperDollar,
    Val = 0x1d,

    Eof = 0x40,
    Err,
    Himem,
    InkeyDollar,
    Pi,
    Rnd,
    Time,
    Xpos,
    Ypos,
    Derr = 0x49,

    BinDollar = 0x71,
    DecDollar,
    HexDollar,
    Instr,
    LeftDollar,
    Max,
    Min,
    Pos,
    RightDollar,
    Round,
    StringDollar,
    Test,
    Teststr,
    CopycharDollar,
    Vpos = 0x7f,
}

impl fmt::Display for BasicTokenPrefixed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let tag = match self {
            Self::Abs => "ABS",
            _ => unimplemented!("{}", self),
        };
        write!(f, "{}", tag)
    }
}

/*
impl From<u8> for BasicTokenPrefixed {
    fn from(val: u8) -> BasicTokenPrefixed {
        val.try_into().unwrap()
    }
}
*/

impl BasicTokenPrefixed {
    /// Returns the 8bits code that represents the prefixed token
    pub fn value(self) -> u8 {
        self.into()
    }
}

#[derive(Debug, Clone, PartialEq)]
/// Encode a Basic value
pub enum BasicValue {
    /// 16bits integer value
    Integer(u8, u8),
    /// 5bytes float value
    Float(u8, u8, u8, u8, u8),
    /// String
    String(String),
}

#[allow(missing_docs)]
impl BasicValue {
    pub fn new_integer(word: u16) -> Self {
        BasicValue::Integer((word % 256) as u8, (word / 256) as u8)
    }

    pub fn new_string(_value: &str) -> Self {
        unimplemented!()
    }

    pub fn new_float(_value: i32) -> Self {
        unimplemented!()
    }

    pub fn as_bytes(&self) -> Vec<u8> {
        match self {
            Self::Integer(ref low, ref high) => vec![*low, *high],
            _ => unimplemented!(),
        }
    }

    /// Return the integer value when it is an integer
    pub fn as_integer(&self) -> Option<u16> {
        match self {
            Self::Integer(ref low, ref high) => Some(u16::from(*low) + 256 * u16::from(*high)),
            _ => None,
        }
    }

    pub fn int_hexdecimal_representation(&self) -> Option<String> {
        self.as_integer().map(|i| format!("&{:X}", i))
    }

    pub fn int_decimal_representation(&self) -> Option<String> {
        self.as_integer().map(|i| format!("{}", i))
    }
}

/// Represents any kind of token
#[derive(Debug, Clone, PartialEq)]
pub enum BasicToken {
    /// Simple tokens.
    SimpleToken(BasicTokenNoPrefix),
    /// Tokens prefixed by 0xff
    PrefixedToken(BasicTokenPrefixed),
    /// Encode a RSX call
    Rsx(String),
    /// Encode a variable set
    Variable(String, BasicValue),
    /// Encode a constant. The first field can only take ValueIntegerDecimal8bits, ValueIntegerDecimal16bits, ValueIntegerBinary16bits, ValueIntegerHexadecimal16bits
    Constant(BasicTokenNoPrefix, BasicValue),
    /// Encode a comment
    Comment(BasicTokenNoPrefix, Vec<u8>),
}

impl fmt::Display for BasicToken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BasicToken::SimpleToken(ref tok) => {
                write!(f, "{}", tok.to_string())?;
            }
            BasicToken::PrefixedToken(ref tok) => {
                write!(f, "{}", tok.to_string())?;
            }
            BasicToken::Comment(ref tok, ref comment) => {
                write!(f, "{}", tok.to_string())?;
                write!(f, "{},", String::from_utf8(comment.to_vec()).unwrap())?;
            }
            BasicToken::Constant(ref kind, ref constant) => {
                let repr = match kind {
                    BasicTokenNoPrefix::ValueIntegerHexadecimal16bits => {
                        constant.int_hexdecimal_representation().unwrap()
                    }
                    BasicTokenNoPrefix::ValueIntegerDecimal16bits => {
                        constant.int_decimal_representation().unwrap()
                    }
                    _ => unimplemented!("{:?}", kind),
                };
                write!(f, "{}", repr)?;
            }
            _ => unimplemented!("{:?}", self),
        }

        Ok(())
    }
}

#[allow(missing_docs)]
impl BasicToken {
    pub fn as_bytes(&self) -> Vec<u8> {
        match self {
            BasicToken::SimpleToken(ref tok) => vec![tok.value()],

            BasicToken::PrefixedToken(ref tok) => vec![
                BasicTokenNoPrefix::AdditionalTokenMarker.value(),
                tok.value(),
            ],

            BasicToken::Rsx(ref _name) => {
                let encoded_name = self.rsx_encoded_name().unwrap();
                let mut data = vec![BasicTokenNoPrefix::Pipe.value(), encoded_name.len() as u8];
                data.extend_from_slice(&encoded_name);
                data
            }

            BasicToken::Constant(ref kind, ref constant) => {
                let mut data = vec![kind.value()];
                data.extend_from_slice(&constant.as_bytes());
                data
            }

            BasicToken::Comment(ref comment_type, ref comment) => {
                let mut data = vec![comment_type.value()];
                data.extend_from_slice(&comment);
                data
            }

            _ => unimplemented!(),
        }
    }

    /// Returns the encoded version of the rsx name (bit 7 to 1 of last char)
    pub fn rsx_encoded_name(&self) -> Option<Vec<u8>> {
        match self {
            BasicToken::Rsx(ref name) => Some(Self::encode_string(name)),
            _ => None,
        }
    }

    pub fn variable_encoded_name(&self) -> Option<Vec<u8>> {
        match self {
            BasicToken::Variable(ref name, _) => Some(Self::encode_string(name)),
            _ => None,
        }
    }

    /// Encode a string by setting the bit 7 of last char. Returns a vector of bytes.
    fn encode_string(name: &str) -> Vec<u8> {
        let mut copy = name.as_bytes().to_vec();
        copy.pop(); // Remove \0
        if let Some(c) = copy.last_mut() {
            *c += 0b1000_0000; // Set bit 7 to last char
        }
        copy
    }
}

#[cfg(test)]
mod test {
    use crate::tokens::*;
    use std::convert::TryInto;

    #[test]
    fn test_conversion() {
        assert_eq!(BasicTokenNoPrefix::Pipe.value(), 0x7c);
        assert_eq!(BasicTokenNoPrefix::After.value(), 0x80);

        assert_eq!(BasicTokenNoPrefix::Goto.value(), 0xa0);

        assert_eq!(BasicTokenNoPrefix::SymbolQuote.value(), 0xc0);

        assert_eq!(BasicTokenNoPrefix::Frame.value(), 0xe0);

        assert_eq!(BasicTokenNoPrefix::GreaterOrEqual.value(), 0xf0);

        assert_eq!(BasicTokenNoPrefix::Division.value(), 0xf7);

        let token: BasicTokenNoPrefix = 0xf7.try_into().unwrap();
        assert_eq!(token, BasicTokenNoPrefix::Division);
    }
}