Rhino リハビリ5 JavaScriptコンパイラを使ってみる

昔は普通に使いこなしてた記憶があるんだけど、classpathのことをすっかり忘れてて1時間ぐらいハマってしまった。。。classpathにカレントディレクトリ付けないとダメとかすぐに忘れるって。。。

コンパイルするコード(test.js)

print("hoge");

コンパイル

$ java -cp .;js.jar org.mozilla.javascript.tools.jsc.Main  test.js

ここでは別にclasspathにカレントディレクトリ付ける必要がないんだけど、まぁ一応。

コンパイル後のバイトコード(.class)を実行

$ java -cp .;js.jar test

実行時にはjs.jarとclassファイルのあるディレクトリをclasspathに指定する必要あり。ここではカレントディレクトリにtest.classが存在している前提。

おまけ

Rhinoでコンパイルした .class をjadで逆コンパイルした結果を貼っておく。

import org.mozilla.javascript.*;
import org.mozilla.javascript.optimizer.*;

public class test extends NativeFunction
    implements Script {

    private int _id;
    private test _dcp;
    private Object _re[];

    public test() {
        _id = 0;
    }

    public static void main(String args[]) {
        OptRuntime.main(new test(), args);
    }

    public final Object exec(Context context, Scriptable scriptable) {
        return call(context, scriptable, scriptable, null);
    }

    public final Object call(Context context, Scriptable scriptable, Scriptable scriptable1, Object aobj[]) {
        if(!ScriptRuntime.hasTopCall(context)) {
            return ScriptRuntime.doTopCall(this, context, scriptable, scriptable1, aobj);
        } else {
            return _c0(this, context, scriptable, scriptable1, aobj);
        }
    }

    public int getLanguageVersion() {
        return 0;
    }

    public String getFunctionName() {
        return "";
    }

    public int getParamCount() {
        return 0;
    }

    public int getParamAndVarCount() {
        return 0;
    }

    public String getParamOrVarName(int i) {
        return null;
    }

    public String getEncodedSource() {
        return "\207'\005printV)\004hogeWQ\001".substring(0, 18);
    }

    public boolean getParamOrVarConst(int i) {
        return false;
    }

    private static Object _c0(test test1, Context context, Scriptable scriptable, Scriptable scriptable1, Object aobj[]) {
        ScriptRuntime.initScript(test1, scriptable1, context, scriptable, false);
        Object obj = Undefined.instance;
        obj = OptRuntime.callName(new Object[] {
            "hoge"
        }, "print", context, scriptable);
        return obj;
    }
}

このコードじゃ速くはないよなぁ・・・