brainhug/haskell/mod.rs
1use super::tokenize;
2use super::Token;
3use super::Token::*;
4
5fn generate(tokens: &[Token]) -> String {
6 let mut output = String::from(include_str!("preface.hs"));
7 let mut indent = 1;
8
9 for &token in tokens {
10 match token {
11 Add => {
12 for _ in 0..indent {
13 output.push_str(" ");
14 }
15 // Increment the value at the selected cell
16 output.push_str(">=> inc\n");
17 }
18
19 Sub => {
20 for _ in 0..indent {
21 output.push_str(" ");
22 }
23 // Decrement the value at the selected cell
24 output.push_str(">=> dec\n");
25 }
26
27 Right => {
28 for _ in 0..indent {
29 output.push_str(" ");
30 }
31 // Change our selected cell to the next to the right
32 output.push_str(">=> right\n");
33 }
34
35 Left => {
36 for _ in 0..indent {
37 output.push_str(" ");
38 }
39 // Change our selected cell to the next to the left
40 output.push_str(">=> left\n");
41 }
42
43 Read => {
44 for _ in 0..indent {
45 output.push_str(" ");
46 }
47 // Read a single character into the selected cell
48 output.push_str(">=> getC\n");
49 }
50
51 Write => {
52 for _ in 0..indent {
53 output.push_str(" ");
54 }
55 // Print the character at the selected cell
56 output.push_str(">=> putC\n");
57 }
58
59 BeginLoop => {
60 for _ in 0..indent {
61 output.push_str(" ");
62 }
63 indent += 1;
64 // Begin a loop at the current cell
65 output.push_str(">=> while (return\n");
66 }
67
68 EndLoop => {
69 indent -= 1;
70 for _ in 0..indent {
71 output.push_str(" ");
72 }
73 // Close a loop
74 output.push_str(")\n");
75 }
76 }
77 }
78
79 output.push('\n');
80
81 output
82}
83
84/// generate string of Haskell code from a Brainf*ck string
85pub fn brains(input: &str) -> String {
86 let tokens = tokenize(input);
87
88 generate(&tokens)
89}