Monday, 4 November 2013

The Code Model for a java compiler API

This is a big project, so let’s start small. Everything in the tool works on an abstraction of the source codebase,so we need to build a core model. The actual tree structures provided by the Java Compiler API contain all the
information we need, but they are not in a convenient package, so we will build our own wrapper classes. First is the MethodModel, which represents everything we know about a single method. A method has a name, the body (the actual statements inside the method), and a list of parameter
variables and their types.
public class MethodModel implements Comparable<MethodModel> {
public String name = "";
public String body = "";
public CompilationUnitTree compUnit;
public long start;
public long end;
private List<String> varTypes = new ArrayList<String>();
private List<String> varNames = new ArrayList<String>();

I’ve also included two longs for start and end as well as a reference to the
CompilationUnitTree. I will explain these later. Next is the class model,
which represents a single class in the codebase. It has a class name and two collections of MethodModel representing the methods within this class. I am using both a list and a method map because I need the methods
to be ordered (which the list provides) and also addressable by name (which the map provides). Next is the ClassModel definition
public class ClassModel implements Comparable<ClassModel> {
public String name;
private List<MethodModel> methods = new ArrayList<MethodModel>();
private Map<String,MethodModel> methodMap = new HashMap<String, MethodModel>();
There are also accessor and utility methods for getting a particular method by name or index and for sorting the methods.These accessors are
not shown. See the full source for details. The methodMap also ensures that the methods are unique. Java allows two methods to have the same name,
so we can’t use just the name as the key for the hash map. We need something unique. To fix this, MethodModel.getUniqueName()
will return a unique key based on the method name as well as the
names of the parameters, which must be unique. The PackageModel and
CodebaseModel classes look very similar to the ClassModel; they are just higher levels
 public class PackageModel {
public String name;
public Set<ClassModel> classSet = new HashSet<ClassModel>();
public List<ClassModel> classList = new ArrayList<ClassModel>();
public Map<String,ClassModel> classMap = new HashMap<String, ClassModel>();
public class CodebaseModel {
List<String> packageList = new ArrayList<String>();
Map<String,PackageModel> packageMap = new HashMap<String, PackageModel>();
PackageModel represents a single package. The CodebaseModel represents

the entire codebase full of packages. Again, utility and accessor methods are not shown.

No comments:

Post a Comment