1
\$\begingroup\$

I am trying to make a simple expression evaluator in Java using Jacc (a parser generator). I am done with the AST creation and now need to create an evaluator. For this I made a simple test to try to understand how visitors work. Here is my code

interface Visitor
{
    public void visitB(B b);
    public void visitC(C c);
    public void visitD(D d);
}

class PrintVisitor implements Visitor
{
    public void visitB(B b)
    {
        b.child1.accept(this);
        b.child2.accept(this);
        System.out.println("a B visited: " + b.name);
    }

    public void visitC(C c)
    {
        c.child.accept(this);
        System.out.println("a C visited: " + c.name);
    }

    public void visitD(D d)
    {
        System.out.println("a D visited: " + d.name);
    }
}

abstract class A
{
    public String name;
    abstract void accept(Visitor v);
}

class B extends A
{
    public A child1;
    public A child2;

    public B(String name)
    {
        this.name = name;
    }

    @Override
    void accept(Visitor v)
    {
        v.visitB(this);
    }
}

class C extends A
{
    public A child;

    public C(String name)
    {
        this.name = name;
    }

    @Override
    void accept(Visitor v)
    {
        v.visitC(this);
    }
}

class D extends A
{
    public D(String name)
    {
        this.name = name;
    }

    @Override
    void accept(Visitor v)
    {
        v.visitD(this);
    }
}

class Main
{
    public static void main(String[] args)
    {
        B b1 = new B("b1");
        B b2 = new B("b2");

        C c1 = new C("c1");
        C c2 = new C("c2");

        D d1 = new D("d1");
        D d2 = new D("d2");
        D d3 = new D("d3");
        D d4 = new D("d4");

        /*
            b1
          /   \
        c1    c2
      /         \
    b2           d2
   /  \
 d3   d4

        */

        b1.child1 = c1;
        b1.child2 = c2;

        c1.child = b2;
        c2.child = d2;

        b2.child1 = d3;
        b2.child2 = d4;

        PrintVisitor v = new PrintVisitor();
        b1.accept(v);
    }
}

I would appreciate if you guys commented on my understanding of visitors.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.