java.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. use super::super::{ir, formatter};
  2. use ir::Instruction;
  3. use formatter::Formatter;
  4. pub fn transpile(instrs: &Vec<ir::Instruction>) -> String {
  5. let mut formatter = Formatter::new();
  6. formatter.add_line("class Brainfuck {");
  7. formatter.indent();
  8. formatter.add_line("public static void main(String[] args) {");
  9. formatter.indent();
  10. formatter.add_line("byte[] mem = new byte[0x10000];");
  11. formatter.add_line("int ptr = 0;");
  12. formatter.add_line("");
  13. generate(&mut formatter, instrs);
  14. formatter.unindent();
  15. formatter.add_line("}");
  16. formatter.unindent();
  17. formatter.add_line("}");
  18. formatter.get_code()
  19. }
  20. fn generate(formatter: &mut Formatter, instrs: &Vec<Instruction>) {
  21. for instr in instrs {
  22. match instr {
  23. Instruction::Nop => {},
  24. Instruction::Add{ offset, value } => {
  25. formatter.add_line(&format!("mem[(ptr + {}) & 0xFFFF] += {};", offset, value));
  26. },
  27. Instruction::Set{ offset, value } => {
  28. formatter.add_line(&format!("mem[(ptr + {}) & 0xFFFF] = {};", offset, value));
  29. },
  30. Instruction::LinearLoop{ offset, factors } => {
  31. for (off, factor) in factors {
  32. formatter.add_line(&format!("mem[(ptr + {}) & 0xFFFF] += {} * mem[(ptr + {}) & 0xFFFF];", offset + off, factor, offset));
  33. }
  34. formatter.add_line(&format!("mem[(ptr + {}) & 0xFFFF] = 0;", offset));
  35. },
  36. Instruction::MovePtr(offset) => {
  37. formatter.add_line(&format!("ptr += {};", offset));
  38. },
  39. Instruction::Loop(instructions) => {
  40. formatter.add_line("while(mem[ptr & 0xFFFF] != 0) {");
  41. formatter.indent();
  42. generate(formatter, instructions);
  43. formatter.unindent();
  44. formatter.add_line("}");
  45. },
  46. Instruction::Read(offset) => {
  47. formatter.add_line(&format!("mem[(ptr + {}) & 0xFFFF] = (byte) System.in.read();", offset));
  48. },
  49. Instruction::Write(offset) => {
  50. formatter.add_line(&format!("System.out.write(mem[(ptr + {}) & 0xFFFF]);", offset));
  51. formatter.add_line(&format!("System.out.flush();"));
  52. }
  53. }
  54. }
  55. }