www.delorie.com/gnu/docs/kawa/kawa-tour_16.html   search  
 
Buy GNU books!


Kawa: Compiling Scheme to Java

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

1.15 The codegen package

The ClassType and Method classes are in a separate codegen package, which is an intermediate-level interface to code generation and Java .class files. It is essentially independent of Scheme or the rest of Kawa, and could be used for generating code for other languages.

 
class ClassType extends Type {
  CpoolEntry[] constant_pool;
  Method methods; // List of methods.
  Field fields; // List of fields.
  public Field new_field (String name, Type type, int flags)
  { Create new field. }
  public method new_method (String name, ...)
  { Create new method. }
  public void emit_to_stream (OutputStream stream)
  { ... }
  public void emit_to_file (String filename)
  { ... }
  public byte[] emit_to_array ()
  { ... }
  ...
}

The ClassType class is the main class of the codegen package. It manages a list Fields , a list of Methods, and the constant pool. There are utility methods for adding new fields, methods, and constant pool entries.

When the ClassType has been fully built, the emit_to_file method can be used to write out the contents into a file. The result has the format of a .class file T. Lindholm and F.~Yellin: The Java Virtual Machine Specification, Addison-Wesley, 1996. Alternatively, the class can be written to an internal byte array (that has the same layout as a .class file) using the emit_to_array method. The resulting byte array may be used by a ClassLoader to define a new class for immediate execution. Both of the these methods are implemented on top of the more general emit_to_stream.

The largest class in the codegen package is Method.

 
class Method {
  Variable new_local (Type type, String name)
  { ... }
  public void compile_push_value (Variable var)
  { ... }
  public void compile_push_int (int i)
  { ... }
  public void compile_linenumber (int linenumber)
  { ... }
  ...
}

As an example of the level of functionality, compile_push_int compiles code to push an integer i on stack. It selects the right instruction, and if i is too big for one of the instructions that take an inline value, it will create a constant pool entry for i, and push that.

The method new_local creates a new local variable (and makes sure debugging information is emitted for it), while compile_push_value pushes the value of the variable on the stack.

Kawa calls compile_linenumber to indicate that the current location corresponds to a given line number. These are emitted in the .class file, and most Java interpreters will use them when printing a stack trace.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster   donations   bookstore     delorie software   privacy  
  Copyright © 2003   by The Free Software Foundation     Updated Jun 2003