summary refs log tree commit diff
path: root/src/main.rs
blob: 41e5e3ae481734792a56a6d2bd3288607af4c81d (plain)
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
use num_traits::pow::Pow;
use std::collections::{ BTreeMap, HashMap };
// use std::env; // TODO: Get args from here
use std::io::{ self, BufRead };
use std::fmt;
use std::rc::Rc;
use rust_decimal::prelude::*;
use rust_decimal_macros::dec;

mod tests;


const HELP_TEXT: &str =
    "LITERALS\n\
     0-9     integers\n\
     _       toggle sign (or, as a command, negate the top item on the stack)\n\
     [...]   string\n\
     (...)   named command (see below)\n\
     \n\
     ARITHMETIC OPERATIONS\n\
     +       add the top two items on the stack\n\
     -       subtract the top item on the stack from the second item\n\
     *       multiply the top two items on the stack\n\
     /       divide the second item on the stack by the top item\n\
     %       take the modulus of the second item by the base of the top item\n\
     ^       raise the second item to the power of the top item\n\
     v       take the square root of the top item on the stack\n\
     \n\
     STACK OPERATIONS\n\
     d       duplicate the top item on the stack\n\
     c       clear the stack\n\
     ,       drop the top item from the stack\n\
     !       something semi-implemented\n\
     \n\
     REGISTER OPERATIONS\n\
     l       load from register (register name as next character)\n\
     s       store to register (register name as next character)\n\
     \n\
     CONTROL FLOW\n\
     x       evaluate string\n\
     \n\
     META\n\
     p       print the top item of the stack, leaving it in place\n\
     n       print the top item of the stack, popping it\n\
     q       quit (you can also ^D)\n\
     ?       help (this message)\n\
     \n\
     Good luck!\n\n";


#[derive(Debug,PartialEq,Eq,Clone)]
enum Value {
  Str(String),
  Num(Decimal),
}

impl fmt::Display for Value {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Value::Str(s) => write!(f, "[{}]", s),
      Value::Num(d) => write!(f, "{}", d),
    }
  }
}

fn print_value(v: &Value) {
  match v {
    Value::Str(s) => print!("{}", s),
    Value::Num(d) => print!("{}", d),
  }
}


#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
enum Mode {
  Integer,
  Decimal,
  Str,
  CommandChar,
  CommandNamed,
  RegisterChar,
  RegisterStr,
}


#[derive(Debug)]
enum Exit {
  WithMessage(String),
  Quit,
}

fn err_msg(msg: String) -> Exit {
  Exit::WithMessage(msg)
}


fn baseline_registers() -> HashMap<String, Value> {
  let kvs = [
    ("F->C", "1! 32- 5 9/*"),
    ("C->F", "1! 9 5/* 32+"),
    ("C->K", "1! 273+"),
    ("K->C", "1! 273-"),
    ("Km->mi", "1! 1.609344/"),
    ("mi->Km", "1! 1.609344*"),
  ].map(|kv: (&str, &str)| (String::from(kv.0), Value::Str(kv.1.into())));

  HashMap::from(kvs)
}


fn main() {
  let mut state = RPState {
    registers: baseline_registers(),
    stack: Vec::new(),
    mode: Mode::CommandChar,
    readtables: BTreeMap::from([
      (Mode::Integer, make_integer_readtable()),
    ]),
    wip_str: String::from(""),
    // TODO: I don't think we need a return stack
    // But this the closest thing we have right now
    reg_command: String::from(""),
    eat_count: 0,
    num: dec!(0.0),
    is_num_negative: false,
    decimal_offset: dec!(1),
  };
  let stdin = io::stdin();
  for line in stdin.lock().lines() {
    match eval(&line.unwrap(), &mut state) {
      Ok(()) => {
        let mut first = true;
        print!("{}", "stack: {");
        for elem in state.stack.iter() {
          if !first { print!("{}", ", "); }
          print!("{}", elem);
          first = false;
        }
        println!("{}", "}");
      },
      Err(Exit::WithMessage(msg)) => println!("Error: {}", msg),
      Err(Exit::Quit) => break,
    }
  }
}


const RADIX: u32 = 10;
const INTEGER_RADIX: Decimal = dec!(10);

fn to_decimal(input: u32) -> Decimal {
  <u32 as Into<Decimal>>::into(input)
}

fn usize_to_decimal(input: usize) -> Decimal {
  <usize as Into<Decimal>>::into(input)
}


type ReadAction = Rc<dyn Fn(char, &mut RPState) -> Result<(), Exit>>;

struct ReadTable {
  action_map: BTreeMap<char, ReadAction>,
  default_action: ReadAction,
}


struct RPState {
  registers: HashMap<String, Value>,
  stack: Vec<Value>,
  mode: Mode,
  readtables: BTreeMap<Mode, ReadTable>,
  reg_command: String,
  wip_str: String,
  eat_count: u32,
  is_num_negative: bool,
  num: Decimal,
  decimal_offset: Decimal
}


// TODO: Generalized shuffles
// [[a-aa\](shuf)]s[dup]
// [[ab-ba\](shuf)]s[swap]
// [[ab-b\](shuf)]s[nip]
//
// fn shuffle(_state: &mut RPState) -> Result<(), Exit> {
//    Err(err_msg("(shuf) not implemented yet!".into()))
// }

fn command_str(c: char, state: &mut RPState) -> Result<(), Exit> {
  if c != ')' {
    state.wip_str.push(c);
  } else if c == ')' {
    match state.wip_str.as_str() {
      // TODO:
      // (times)
      // (while)
      // (?) -- (cond ifTrue ifFalse)
      // [(?)x]s[if-else]
      // [[\](?)x]s[if]
      // (r?) -- show contents of registers
      // Scope out
      word => {
        if state.registers.contains_key(word) {
          match &state.registers[word].clone() {
            Value::Str(eval_body) => {
              state.wip_str.clear();
              state.mode = Mode::CommandChar;
              return eval(&eval_body, state);
            }
            _ => {
              return Err(err_msg(format!(
                  "Unable to execute ({}) as a named word", word)))
            }
          }
        } else {
          return Err(err_msg(format!(
              "Unable to execute ({}) as a named word", word)))
        }
      }
    }
  }

  Ok(())
}


fn command_char(c: char, state: &mut RPState) -> Result<(), Exit> {
  if c.is_digit(RADIX) {
    state.mode = Mode::Integer;
    state.num = dec!(0);
    state.num += to_decimal(c.to_digit(10)
        .ok_or_else(|| err_msg(format!("{} isn't a digit", c)))?);
    Ok(())
  } else if c == '_' {
    state.mode = Mode::Integer;
    state.num = dec!(0);
    state.is_num_negative = true;
    Ok(())
  } else if c == ' ' {
    // do nothing
    Ok(())
  } else if c == '(' {
    state.mode = Mode::CommandNamed;
    state.wip_str.clear();
    state.eat_count = 0;
    Ok(())
  } else if c == '[' {
    state.mode = Mode::Str;
    state.wip_str.clear();
    state.eat_count = 0;
    Ok(())
  } else if let 'p' | 'n' | 'q' | 'l' | 's' | 'v' | 'x' | 'd' | ',' | 'c'
              | '!' | '?' = c
  {
    match c {
      '?' => {
        print!("{}", HELP_TEXT);
      },
      '!' => {
        if state.stack.is_empty() {
          return Err(err_msg("Data underflow!".into()));
        }
        match state.stack.pop() {
          Some(Value::Num(d)) => {
            if usize_to_decimal(state.stack.len()) < d {
              return Err(err_msg(format!(
                  "Stack depth should be at least: {}", d)));
            }
          }
          Some(Value::Str(_)) => return Err(err_msg(
              "Cannot assert a string as a stack depth".into())),
          None => return Err(err_msg("Data underflow!".into()))
        }
      },
      'q' => return Err(Exit::Quit),
      'c' => state.stack.clear(),
      'l' => {
        state.reg_command = "l".into();
        state.mode = Mode::RegisterChar;
      }
      'x' => {
        if state.stack.is_empty() {
          return Err(err_msg("Data underflow!".into()));
        }
        match state.stack.pop() {
          Some(Value::Str(s)) => {
            return eval(&s, state)
          }
          Some(v) => {
            return Err(err_msg(format!("Cannot eval {}", v)));
          }
          None => {
            return Err(err_msg("Data underflow!".into()));
          }
        }
      }
      's' => {
        state.reg_command = "s".into();
        state.mode = Mode::RegisterChar;
      }
      'd' => {
        if state.stack.is_empty() {
          return Err(err_msg("Data underflow!".into()));
        }
        let val = state.stack.pop().unwrap();
        state.stack.push(val.clone());
        state.stack.push(val.clone());
      }
      ',' => {
        if state.stack.is_empty() {
          return Err(err_msg("Data underflow!".into()));
        }
        state.stack.pop();
      }
      'v' => {
        if state.stack.is_empty() {
          return Err(err_msg("Data underflow!".into()));
        }
        match state.stack.pop() {
          Some(Value::Num(d)) => {
            match d.sqrt() {
              Some(n) => state.stack.push(Value::Num(n)),
              None => return Err(err_msg(
                  "Error attempting square root!".into())),
              }
          }
          Some(v) => {
            return Err(err_msg(format!("Invalid attempt to sqrt {}", v)));
          }
          None => {
            return Err(err_msg("Impossible data underflow!".into()));
          }
        }
      }
      'p' =>  {
        if state.stack.is_empty() {
          return Err(err_msg("Data underflow!".into()));
        }
        print_value(state.stack.last().unwrap());
      },
      'n' => {
        if state.stack.is_empty() {
          return Err(err_msg("Data underflow!".into()));
        }
        print_value(&state.stack.pop().unwrap());
      },
      _ => return Err(err_msg(format!(
          "{} is unimplemented, this shouldn't be reachable!", c))),
    }

    Ok(())
  } else if let '+' | '-' | '/' | '*' | '%' | '^' = c {
    if state.stack.len() < 2 {
      return Err(err_msg("Data underflow!".into()));
    }

    let a = state.stack.pop().ok_or_else(|| err_msg(
        "Data underflow!".into()))?;
    let b = state.stack.pop().ok_or_else(|| err_msg(
        "Data underflow!".into()))?;

    match (&a, &b) {
      (Value::Num(ia), Value::Num(ib)) => {
        let value = match c {
          '+' => Some(*ib + *ia),
          '-' => Some(*ib - *ia),
          '/' => Some(*ib / *ia),
          '*' => Some(*ib * *ia),
          '%' => Some(*ib % *ia),
          '^' => Some(Decimal::pow(*ib, *ia)),
          _ => None
        }.ok_or_else(|| err_msg("This should never happen".into()))?;

        state.stack.push(Value::Num(value));
      }
      _ =>  {
        state.stack.push(b);
        state.stack.push(a);
        return Err(err_msg(format!(
            "Invalid operation {} on non-numbers!", c)))
      }
    }
    Ok(())
  } else {
    panic!("{} isn't implemented yet!", c)
  }
}


fn finish_num(c: char, state: &mut RPState) -> Result<(), Exit> {
  // print!("finishing number, negative? {}", state.is_num_negative);
  if state.is_num_negative {
    state.num *= dec!(-1);
  }
  state.stack.push(Value::Num(state.num));
  state.mode = Mode::CommandChar;
  state.is_num_negative = false;
  command_char(c, state)
}


fn make_integer_readtable() -> ReadTable {
  let mut items: Vec<(char, ReadAction)> = vec![
    ('.', Rc::new(move |_, state| {
      state.decimal_offset = dec!(1);
      state.mode = Mode::Decimal;

      Ok(())
    })),
    ('_', Rc::new(move |_, state| {
      state.is_num_negative = true;

      Ok(())
    })),
  ];

  let handle_digit = move |c: char, state: &mut RPState| {
    if c.is_digit(RADIX) {
      state.num *= INTEGER_RADIX;
      state.num += to_decimal(c.to_digit(10).unwrap());
    }

    Ok(())
  };

  for range in ['0' ..= '9', 'a' ..= 'z', 'A' ..= 'Z'] {
    for c in range {
      if c.is_digit(RADIX) {
        items.push((c, Rc::new(handle_digit.clone())));
      }
    }
  }

  ReadTable {
    action_map: BTreeMap::from_iter(items.into_iter()),
    default_action: Rc::new(finish_num),
  }
}


fn decimal(c: char, state: &mut RPState) -> Result<(), Exit> {
  if c.is_digit(RADIX) {
    state.decimal_offset *= dec!(0.1);
    state.num += to_decimal(c.to_digit(10).unwrap())
                 * state.decimal_offset;
  } else {
    return finish_num(c, state)
  }
  return Ok(());
}


fn string(c: char, state: &mut RPState) -> Result<(), Exit> {
  if state.eat_count > 0 {
    state.eat_count-=1;
    state.wip_str.push(c);
  } else if c == '\\' {
    state.eat_count = 1;
  } else if c != ']' {
    state.wip_str.push(c);
  } else if c == ']' {
    state.mode = Mode::CommandChar;
    state.stack.push(Value::Str(state.wip_str.clone()));
    state.wip_str.clear();
  } else {
    return Err(err_msg("Should Not Get Here!".into()))
  }
  Ok(())
}


fn register_str(c: char, state: &mut RPState) -> Result<(), Exit> {
  match (c, state.reg_command.as_str()) {
    (']', "l")  => {
      if state.registers.contains_key(&state.wip_str) {
        state.stack.push(state.registers[&state.wip_str].clone());
      }
      state.wip_str.clear();
      state.mode = Mode::CommandChar;
    }
    (']', "s")  => {
      if state.stack.is_empty() {
        return Err(err_msg(format!(
            "Data underflow attempting to store to register {}", c)));
      }
      state.registers.insert(state.wip_str.clone(),
                             state.stack.pop().unwrap());
      state.wip_str.clear();
      state.mode = Mode::CommandChar;
    }
    (_, "l"|"s") => {
      state.wip_str.push(c)
    }
    _ => {
      state.mode = Mode::CommandChar;
      return Err(err_msg(format!(
          "Unsupported register command {}", state.reg_command)));
    }
  }

  Ok(())
}


fn register_char(c: char, state: &mut RPState) -> Result<(), Exit> {
  match (state.reg_command.as_str(), c) {
    (_, '[') => {
      state.mode = Mode::RegisterStr;
      Ok(())
    }
    ("s", c) => {
      if state.stack.is_empty() {
          return Err(err_msg(format!(
              "Data underflow attempting to store to register {}", c)));
      }
      state.registers.insert(String::from(c),
                             state.stack.pop().unwrap());
      state.mode = Mode::CommandChar;
      Ok(())
    }
    ("l", c) => {
      if state.registers.contains_key(&String::from(c)) {
          state.stack.push(state.registers[&String::from(c)].clone());
      }
      state.mode = Mode::CommandChar;
      Ok(())
    }
    _ => {
      state.mode = Mode::CommandChar;
      return Err(err_msg(format!(
          "Unsupported register command {}", state.reg_command)));
    }
  }
}


fn eval(input: &str, state: &mut RPState) -> Result<(), Exit> {
  for (_cpos, c) in input.char_indices() {
    // TODO eventually this slightly weird logic will go away because
    // everything will be in a readtable
    let action = {
      if let Some(readtable) = state.readtables.get_mut(&state.mode) {
        if let Some(action) = readtable.action_map.get_mut(&c) {
          Some(Rc::clone(&action))
        } else {
          Some(Rc::clone(&readtable.default_action))
        }
      } else {
        None
      }
    };

    if let Some(action) = action {
      action(c, state)?;
    } else {
      match state.mode {
        Mode::CommandChar => command_char(c, state),
        Mode::CommandNamed => command_str(c, state),
        Mode::Decimal => decimal(c, state),
        Mode::Str => string(c, state),
        Mode::RegisterChar => register_char(c, state),
        Mode::RegisterStr => register_str(c, state),
        _ => return Err(err_msg(
            "Mode has neither readtable nor hardcoded case".to_string())),
      }?;
    }
  }
  match state.mode {
    Mode::Integer | Mode::Decimal => {
      return finish_num(' ', state)
    },
    _ => { }
  };

  Ok(())
}