Monday, February 6, 2012

Eclipse integrated JavaScript Interpreter

I am working on an integration of Rhino (a Java based JavaScript interpreter) into the Eclipse IDE. Target is to execute JavaScript code directly within the running Eclipse environment. Such an interpreter might be used to script Eclipse itself. Wouldn't it be nice to have macro support?

Therefore I raised bug 365133. As I finally was able to post some code I'd like to give a short overview of what can be done.

Run Plug-ins

You need at least Eclipse 3.7 with JSDT tools installed (get them from the Indigo repository).

Import all four projects from the archive to your workspace. Right click one one of them in Package Explorer and select Run As -> Eclipse Application.

JavaScript Shell

Before we have a look at the integrated JS shell we will quickly adjust some settings: open menu Window -> Preferences and navigate to JavaScript -> Shell. Set all output values to "Shell".

Now open the shell view: select menu Window -> Show View -> Other... Then open view JavaScript -> JavaScript Shell.

The shell consists of a big output pane and an input line at the bottom. Start entering your first JS code there:
i = 2+2;
You will see the result right in the output pane. There is a print command available that will dump text to the Console view.
print("Hello world!");

An integrated help is available when hitting the help toolbar button.

JavaScript Run target

To execute JavaScript files there exists a new run target that allows to right click any JS source file and select Run As -> JavaScript. This will create a new interpreter (so it will not run in the same context as the shell) and execute the file.

Loadable Modules

For developers there exists an interesting Plug-in: It is an example how to extend JS functionality. Every method within this class augmented with @WrapToJavaScript
will be available as JS function automagically. This way JS functionality can be easily extended while using the benefits of Java.

Due to Rhino and the used ClassLoader it is possible to mix JavaScript code and pure Java classes. Eg the following JS code will create an instance of and call a method upon it:
var myFile = new"~/.bashrc");

Wrap up

Having a native JS interpreter within Eclipse will provide great new ways to build applications. It might give us macro support, rapid testing facilities for programmers (just load your Plug-in and access it with the Script Shell) and maybe a lot more things I can currently not think of.

If you want to support this idea please vote on bug 365133 or help in finding ways to make this part of Eclipse.

No comments:

Post a Comment