ARTICLE AD BOX
I'm using an external library which builds an internal representation of an abstract syntax tree (AST) for a toy programming language given an XML file representation of the AST.
The method I'm using, fromXML, returns an AST, but according to the library documentation, AST is an abstract class. It has many concrete subclasses such as AST.program, AST.expr, and AST.stmt_list. My goal is to generate assembly-like code for a program given its AST, yet to do that I have to work with an instance of a concrete class, as AST has no fields.
The only way I could think of solving this problem is by checking (with the instanceof operator) whether the AST returned by fromXML is an AST.program and casting it into an AST.program. This has worked so far, since fromXML has only returned AST.programs. My question is, is there a better solution to this problem? Could there be a way to refrain from casting the AST yet access the fields of AST.program?
My code:
import AST; // The AST library import java.io.File; public class CalcBack { public static void main(String[] args) { File f_xml = new File(args[0]); AST.program prog = null; try { AST ast_from_xml = AST.fromXML(f_xml); // May throw Exception if (ast_from_xml instanceof AST.program) { prog = (AST.program) ast_from_xml; // Casting AST to AST.program } else { System.err.println("Not a program!"); } } catch (Exception e) { System.err.println(e); } if (prog == null) { System.exit(1); } System.out.println(prog.statements); // I can do something with prog } }Output:
% java -cp AST.jar CalcBack.java gcd.xml AST$stmt_list@5c909414