1

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)})}

1 Answers1

0

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

deanWombourne
  • 38,189
  • 13
  • 98
  • 110
  • So, are you saying that paraExpr (which extends Expr,which is abstract) looks for a definition of the function there, but not finding any, looks into sibling classes for a function definition? – Hariharan Muralidharan Nov 19 '15 at 16:41
  • 1
    Almost. IntExpr is a subclass of Expr. paraExpr is a variable that points to an object that is _at least_ an Expr but could be a subclass. When you call a method on an object, it starts at the subclass (in this case IntExpr) and works its way up the class hierarchy until it finds an implementation. Here, because IntExpr implemented rep() it doesn't need to look anywhere else. – deanWombourne Nov 21 '15 at 09:51