Pavel Vlasov
Pavel Vlasov

Reputation: 4331

How to return a value from ANTLR action?

I'd like to know how:

  1. return a runtime value from a rule action
  2. access that value from the parent rule's action.

With ANTLR I want to build a custom tree using actions (not listeners/visitors which are too complex). And I'd like to have a parser implementation where each action knows about its children but not about its parent.

It is possible to access parent action's $variables but instead I'd like to access runtime values returned from children (and I don't know how).

For example with Ruby's treetop I can build a custom tree like below. Is this approach available for ANTLR too?

// sample input: "hello joe"
grammar Test
    rule greeting
        'hello' name {
            // here `name.value` returns an instance of Name (below)
            return new Greeting(name.value)
        }
    end
    rule name
        ID {
            return new Name(ID.text)
        }
    end

Upvotes: 1

Views: 785

Answers (1)

Pavel Vlasov
Pavel Vlasov

Reputation: 4331

It is possible to (pseudo) return a custom value from action via assigning a special field which can be accessed from outside then:

greeting returns [MyGreeting value] : 'hello' name
{
    $value = new MyGreeting();
    System.out.println("statement with name " + $name.value); // accessing
};
name returns [MyName value] : ID
{
    $value = new MyName(); // assigning
    System.out.println("name...");
};

Upvotes: 1

Related Questions