|
| 1 | +package toylangs.imp; |
| 2 | + |
| 3 | +import cma.CMaInterpreter; |
| 4 | +import cma.CMaProgram; |
| 5 | +import cma.CMaProgramWriter; |
| 6 | +import cma.CMaStack; |
| 7 | +import toylangs.imp.ast.*; |
| 8 | + |
| 9 | +import java.io.IOException; |
| 10 | +import java.nio.file.Paths; |
| 11 | +import java.util.*; |
| 12 | + |
| 13 | +import static toylangs.imp.ast.ImpNode.*; |
| 14 | + |
| 15 | +public class ImpCompiler { |
| 16 | + private final CMaProgramWriter pw = new CMaProgramWriter(); |
| 17 | + |
| 18 | + public static CMaProgram compile(ImpProg prog) { |
| 19 | + ImpCompiler impCompiler = new ImpCompiler(); |
| 20 | + impCompiler.compileNode(prog); |
| 21 | + return impCompiler.pw.toProgram(); |
| 22 | + } |
| 23 | + |
| 24 | + private void compileNode(ImpNode node) { |
| 25 | + throw new UnsupportedOperationException(); |
| 26 | + } |
| 27 | + |
| 28 | + static void main() throws IOException { |
| 29 | + ImpProg prog = prog( |
| 30 | + var('x'), |
| 31 | + |
| 32 | + assign('x', num(5)), |
| 33 | + assign('y', add(var('x'), num(1))), |
| 34 | + assign('x', add(var('y'), num(1))) |
| 35 | + ); |
| 36 | + |
| 37 | + // väärtustame otse |
| 38 | + System.out.printf("eval: %d%n", ImpEvaluator.eval(prog)); |
| 39 | + |
| 40 | + // kompileeri avaldist arvutav CMa programm |
| 41 | + CMaProgram program = compile(prog); |
| 42 | + |
| 43 | + // kirjuta programm faili, mida saab Vam-iga vaadata |
| 44 | + CMaStack initialStack = new CMaStack(); |
| 45 | + program.toFile(Paths.get("cmas", "imp.cma"), initialStack); |
| 46 | + |
| 47 | + // interpreteeri CMa programm |
| 48 | + CMaStack finalStack = CMaInterpreter.run(program, initialStack); |
| 49 | + System.out.printf("compiled: %d%n", finalStack.peek()); |
| 50 | + System.out.printf("finalStack: %s%n", finalStack); |
| 51 | + } |
| 52 | +} |
0 commit comments