001package visitor.typecase;
002import enumeration.Op;
003
004public class Main {
005        public static void main (String[] args) {
006                Expr one = new Const(1);
007                Expr onePtwo = new BinOp (new Const(1), Op.ADD, new Const(2));
008                Expr threeMfour = new BinOp (new Const(3), Op.MUL, new Const(4));
009                Expr m = new BinOp (onePtwo, Op.SUB, threeMfour);
010                Expr n = new BinOp (m, Op.DIV, new Const(5));
011
012                System.out.println (PostorderPrint.run(n));
013                System.out.println ("Value: " + Eval.run(n));
014        }
015}
016
017class PostorderPrint {
018        private PostorderPrint() {}
019        static private StringBuilder b = new StringBuilder();
020        static private StringBuilder runConst(int c) {
021                b.append(c + " ");
022                return b;
023        }
024        static private StringBuilder runBinOp(Expr l, Op op, Expr r) {
025                run(l); run(r); b.append(op + " ");
026                return b;
027        }
028        static public StringBuilder run(Expr e) {
029                if (e instanceof BinOp) {
030                        BinOp x = (BinOp) e;
031                        return runBinOp(x.l, x.op, x.r);
032                } else {
033                        Const x = (Const) e;
034                        return runConst(x.c);
035                }
036        }
037}
038
039class Eval {
040        private Eval() {}
041        static private Integer runConst(int c) {
042                return c;
043        }
044        static private Integer runBinOp(Expr l, Op op, Expr r) {
045                return op.eval(run(l), run(r));
046        }
047        static public Integer run(Expr e) {
048                if (e instanceof BinOp) {
049                        BinOp x = (BinOp) e;
050                        return runBinOp(x.l, x.op, x.r);
051                } else {
052                        Const x = (Const) e;
053                        return runConst(x.c);
054                }
055        }
056}
057