user1870035
user1870035

Reputation:

State and Visitor Pattern

In an application I am building, I am trying to collect a good amount of state using the visitor pattern that will later be manipulated. Is this a typical way to collect state using ANTLR 4 or is it an anti pattern? If it's not could you please provide an example of how to handle state?

Also should you update your domain objects while traversing or implement all the business logic after traversal outside the visitor?

All of the ANTLR 4 examples I have seen are too small and I'm really looking for how it would be used in a real world scenario.

Thank you.

public class JavaClassVisitor extends JavaBaseVisitor < String > {

    private JavaClassVisitorState jcvs = new JavaClassVisitorState();

    @Override
    public List < String > visitParseContext(ParseContext ctx) {
        visitChildren(ctx);
        return jvcs.getAccessSpecifiers().toString();
    }

    @Override
    public List < String > visitClassDeclaration(ClassDeclarationContext ctx) {
        IdentifierContext idCtx = ctx.Identifier();
        if (idCtx != null) {
            String accessSpecifier = idCtx.getText();
            List < String > accessSpecifiers = jcvs.getAccessSpecifiers();
            accessSpecifiers.add(accessSpecifier);
        }
        return visitChildren(ctx);
    }

    @Override
    public List < String > visitMethodDeclaration(MethodDeclarationContext ctx) {
        IdentifierContext idCtx = ctx.Identifier();
        if (idCtx != null) {
            String accessSpecifier = idCtx.getText();
            List < String > accessSpecifiers = jcvs.getAccessSpecifiers();
            accessSpecifiers.add(accessSpecifier);
        }
        return visitChildren(ctx);
    }

}

Upvotes: 0

Views: 270

Answers (1)

Mike Lischke
Mike Lischke

Reputation: 53357

In order to maintain the typical Q&A style of Stackoverflow I answer one question, which is the core here IMO.

I'm not aware of a "typical" visitor pattern for ANTLR4. It all depends on the context and what you are trying to accomplish. If you need to update your domain objects and decide to do that in a visitor, then so be it.

The visitor pattern doesn't restrict itself to just collecting data. Update is also a valid action. Both visitors and listeners in ANTLR4 work pretty similar, by walking depth-first over a parse tree. Both call methods specific to each parse context they see in the tree. The main difference is that a listener does a generic walk, while the visitor can return a custom value (good for things like evaluators, even though you could also keep intermediate values in a member variable of the visitor).

Upvotes: 1

Related Questions