fork download
  1. fn main() {
  2. let source = "
  3. var A as Integer
  4. print A
  5. A = 10
  6. print A
  7. A += 5
  8. print A
  9. A += -3
  10. print A
  11. ";
  12.  
  13. let code_block = parse(source);
  14.  
  15. run(code_block);
  16. }
  17.  
  18. fn parse(source: Str) -> CodeBlock {
  19. let mut code_block = CodeBlock::new();
  20.  
  21. for line in source.lines() {
  22. let tokens: Vec<_> = line.split_whitespace().collect();
  23. match tokens.first() {
  24. Some(&"var") => code_block.push(Code::Var(tokens[1], tokens[3])),
  25. Some(&"print") => code_block.push(Code::Print(tokens[1])),
  26. Some(v) => {
  27. if tokens[1] == "=" {
  28. code_block.push(Code::Copy(v, tokens[2]))
  29. } else {
  30. code_block.push(Code::AddInto(v, tokens[2]))
  31. }
  32. }
  33. _ => {}
  34. }
  35. }
  36. code_block
  37. }
  38.  
  39. fn run(code_block: CodeBlock) {
  40. let mut integer_vars = std::collections::HashMap::new();
  41. for code in &code_block {
  42. match code {
  43. Code::Var(var_name, var_type) => {
  44. if *var_type == "Integer" {
  45. integer_vars.insert(var_name, 0i32);
  46. }
  47. }
  48. Code::Copy(var_name, new_value) => {
  49. if let Some(var_value) = integer_vars.get_mut(var_name) {
  50. if let Ok(new_value) = new_value.parse::<i32>() {
  51. *var_value = new_value;
  52. }
  53. }
  54. }
  55. Code::AddInto(var_name, add_value) => {
  56. if let Some(var_value) = integer_vars.get_mut(var_name) {
  57. if let Ok(add_value) = add_value.parse::<i32>() {
  58. *var_value += add_value;
  59. }
  60. }
  61. }
  62. Code::Print(var_name) => {
  63. if let Some(var_value) = integer_vars.get(var_name) {
  64. println!("{}", *var_value);
  65. }
  66. }
  67. }
  68. }
  69. }
  70.  
  71. type CodeBlock = Vec<Code>;
  72.  
  73. type Str = &'static str;
  74.  
  75. enum Code {
  76. Var(Str, Str),
  77. Copy(Str, Str),
  78. AddInto(Str, Str),
  79. Print(Str),
  80. }
  81.  
Success #stdin #stdout 0s 4440KB
stdin
Standard input is empty
stdout
0
10
15
12