/brainfuck/lib/bf_c_translator.rb

https://github.com/vybirjan/MI-RUB-ukoly · Ruby · 53 lines · 44 code · 9 blank · 0 comment · 2 complexity · 42c68b2b900c16ba37914d4a83e1d116 MD5 · raw file

  1. require_relative 'brainfuck_ast.rb'
  2. class BrainfuckCTranslator
  3. def self.to_c_source(ast)
  4. source = ""
  5. source << PROLOG
  6. element = ast
  7. tabcount = 1
  8. while(element != nil)
  9. source << tabs(tabcount)
  10. case element
  11. when IncrementValue
  12. source << "memory[pointer]++;\n"
  13. when DecrementValue
  14. source << "memory[pointer]--;\n"
  15. when IncrementPointer
  16. source << "pointer++;\n"
  17. when DecrementPointer
  18. source << "pointer--;\n"
  19. when ReadInput
  20. source << "memory[pointer] = getchar();\n"
  21. when PrintValue
  22. source << "putchar(memory[pointer]);\n"
  23. when LoopStart
  24. source << "while(memory[pointer] != 0) {\n"
  25. tabcount = tabcount + 1
  26. when LoopEnd
  27. source << "}\n"
  28. tabcount = tabcount - 1
  29. end
  30. element = element.next
  31. end
  32. source << EPILOG
  33. end
  34. private
  35. def self.tabs(count)
  36. ret = ""
  37. 1.upto(count) do
  38. ret << "\t"
  39. end
  40. return ret
  41. end
  42. PROLOG = "#include <stdio.h>\n\nint main(void)\n{\n\tstatic char memory[30000];\n\tint pointer = 0;\n"
  43. EPILOG = "\treturn 0;\n}"
  44. end