Search code examples
abstract-syntax-treecompiler-constructioncup

How is it that the val() and rep() functions are called in this code(there's no definition for them)?


I'm using a parser generator called CUP. I was provided with the grammar (CUP specification) and this piece of supporting code (Expr.java) for the class definitions.

In the CUP specification, the grammar productions have a semantic action associated with them like this:

expr ::= expr:e1 PLUS expr:e2
{: RESULT = new OpExpr(e1,e2,sym.PLUS); :};

The class definition is something like this:

package java_cup.output;
abstract class Expr {

    protected static String symbols[] = new String[12];

    .
    .
    .

    public abstract Integer val();

    public abstract String rep();

}

There's a class for Integer expressions

class IntExpr extends Expr{

    Integer intExpr;

    public IntExpr(Integer e) { intExpr = e; }

    public Integer val() { return intExpr; }

    public String rep() { return "Integer{"+intExpr.toString()+"}"; }

}

And then, there are classes like:

class ParaExpr extends Expr {

    Expr paraExpr;

    public ParaExpr(Expr e) { paraExpr = e; }

    public Integer val() { return paraExpr.val(); }

    public String rep() { return "ParaExpr{("+paraExpr.rep()+")}"; }

}

Essentially, my question is this: There is no definition given for the rep() function of the Expr class (because it is abstract). Then what does this function call do ? paraExpr.rep()

When I create a project, build the parser and and parse an input string, it creates an AST and prints it out like this:

ParaExpr{(IntExpr{(1)}+IntExpr{(2)})}


Solution

  • Nothing, it's an abstract method so doesn't have any implementation. but you already knew that.

    You won't have an instance of Expr when you are calling paraExpr.rep(), paraExp will be a subclass of Expr, one which does implement rep() .e.g. IntExpr