You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

47 lines
1.4 KiB

  1. /*!! Printer */
  2. /*!
  3. ProgramPrinter
  4. ==============
  5. The `ProgramPrinter` is used for string serialization of a given `Program`.
  6. */
  7. /*!- Header */
  8. package printer;
  9. import interpreter.Visitor;
  10. import program.*;
  11. /*!
  12. The `ProgramPrinter` implements the string serialization with the help of the
  13. [Visitor](${basePath}/src/main/java/interpreter/Visitor.java.html).
  14. */
  15. public class ProgramPrinter extends Visitor<String> {
  16. private final ExpressionPrinter printer = new ExpressionPrinter();
  17. public String visitAssignment(Assignment assignment) {
  18. return printer.print(assignment.identifier) + " := " + printer.print(assignment.expression);
  19. }
  20. public String visitComposition(Composition composition) {
  21. return visit(composition.first) + " ; " + visit(composition.second);
  22. }
  23. public String visitConditional(Conditional conditional) {
  24. return "if (" + printer.print(conditional.condition) + ") then { " + visit(conditional.thenCase) + " } else { " + visit(conditional.elseCase) + " }";
  25. }
  26. public String visitLoop(Loop loop) {
  27. return "while (" + printer.print(loop.condition) + ") { " + visit(loop.program) + " }";
  28. }
  29. /*!
  30. The `print` function takes a `Program` instance as an argument and returns
  31. the string serialization of the given program.
  32. */
  33. public String print(Program program) {
  34. return visit(program);
  35. }
  36. }