示例#1
0
  public CompiledScript compile(Script script, String className) {
    try (CodeSizeAnalysis analysis = new CodeSizeAnalysis()) {
      analysis.submit(script);
    } catch (CodeSizeException e) {
      e.printStackTrace();
      throw new CompilationException(e.getMessage());
    }

    // set-up
    // prepend '#' to mark generated classes, cf. ErrorPrototype
    String clazzName = "#" + className;
    String superClassName = Types.CompiledScript.getInternalName();
    Code code = new Code(clazzName, superClassName, script.getSourceFile(), sourceMap(script));

    // generate code
    try (CodeGenerator codegen = new CodeGenerator(code, script.getOptions())) {
      codegen.compile(script);
    }

    // finalize
    CodeLoader loader = new CodeLoader();
    List<ClassCode> classes = code.getClasses();
    for (ClassCode classCode : classes) {
      byte[] bytes = classCode.toByteArray();
      if (compilerOptions.contains(Option.Debug)) {
        debug(bytes);
      }
      // System.out.printf("define class '%s'%n", classCode.className);
      loader.defineClass(classCode.className, bytes);
    }

    try {
      Class<?> c = loader.loadClass(clazzName);
      return (CompiledScript) c.newInstance();
    } catch (ReflectiveOperationException e) {
      throw new RuntimeException(e);
    }
  }
示例#2
0
  private CompiledFunction compile(FunctionNode function, String className) {
    try (CodeSizeAnalysis analysis = new CodeSizeAnalysis()) {
      analysis.submit(function);
    } catch (CodeSizeException e) {
      throw new CompilationException(e.getMessage());
    }

    // set-up
    // prepend '#' to mark generated classes, cf. ErrorPrototype
    String clazzName = "#" + className;
    String superClassName = Types.CompiledFunction.getInternalName();
    Code code = new Code(clazzName, superClassName, "<Function>", null);

    // generate code
    try (CodeGenerator codegen = new CodeGenerator(code, optionsFrom(function))) {
      codegen.compileFunction(function);
    }

    // finalize
    CodeLoader loader = new CodeLoader();
    List<ClassCode> classes = code.getClasses();
    for (ClassCode classCode : classes) {
      byte[] bytes = classCode.toByteArray();
      if (compilerOptions.contains(Option.Debug)) {
        debug(bytes);
      }
      loader.defineClass(classCode.className, bytes);
    }

    try {
      Class<?> c = loader.loadClass(clazzName);
      return (CompiledFunction) c.newInstance();
    } catch (ReflectiveOperationException e) {
      throw new RuntimeException(e);
    }
  }