Compiling Scripts from Java

pnuts.compiler.Compiler

public Compiler()
public Compiler(String className)
public Compiler(String className, boolean automatic)
public Compiler(String className, boolean automatic, boolean useDynamicProxy)

Three parameters can be passed to the constructors. className is the class name of the compiled code. If automatic is true (default), compiled code is automatically loaded and executed. If useDynamicProxy is true (default), method calls in the script are optimized but the compiled code depends on pnuts.compiler package.

import pnuts.lang.*;

public void compile(PnutsFunction function, Context context)
public Pnuts compile(String expr, Context context)
public Pnuts compile(Pnuts pnuts, Context context)

pnuts.compiler.Compiler class provides these public methods to compile functions, expressions, and parsed scripts. java.lang.ClassFormatError may occur when its compilation fails.

e.g.
import pnuts.lang.*;
import pnuts.compiler.*;

class CompileTest {
  public Object compileAndRun(InputStream in, Context context) throws ParseException {
    Compiler compiler = new Compiler();
    Pnuts pn = null;
    try {
      pn = Pnuts.parse(in);
      pn = compiler.compile(pn, context);
      return pn.run(context);
    } catch (ParseException pe){
      throw pe;
    } catch (ClassFormatError cfe){
      return new PnutsInterpreter().accept(pn, context);
    }
  }
  ...
}
import pnuts.lang.*;

public Object compile(PnutsFunction function, ClassFileHandler handler)
public Object compile(String expr, ClassFileHandler handler)
public Object compile(Pnuts pnuts, ClassFileHandler handler)

The class also provides public methods to define how generated class files are processed. pnuts.compiler.ClassFileHandler is an abstract interface to get a result of compilation.

Two concrete classes of ClassFileHandler are provided: pnuts.compiler.FileWriterHandler and pnuts.compiler.ZipWriterHandler. The following code compiles the expression 1+2 and saves the result in "e:\tmp\test.class".

e.g.
String expression = "1 + 2";
Compiler compiler = new Compiler("test");
try {
    compiler.compile(Pnuts.parse(expression), new FileWriterHandler(new File("e:\\tmp")));
} catch (ParseException pe){
} catch (ClassFormatError cfe){
    ...
}

There are two ways to load a compiled script:

  1. Set the property 'pnuts.compiled.script.prefix' to the package name of the generated class, then call load().
    load("test")
    
  2. Call Runtime.execute(Context) method on an instance of the generated class.

    test().execute(getContext())
    

Back