An interpreter that can recognize a JS-like language. It can parse very simple JavaScript programs but is still missing a bunch of features. I intend to finish it once I have some time off freelancing. The plan is to have the parser recognize all the syntactical elements of ECMA-262 and once there, generate Java bytecode (or LLVM IR) based on the AST which can be interpreted by a VM (JVM or LLVM).
Building and running the tests is a two-stage process.
git clone https://github.com/devsh0/JsInterpreter.git
cd JsInterpreter
mvn test
Note: Ubuntu doesn't play nice with maven 3.6.x. If you encounter an error, upgrade to maven 3.8.x.
Although the interpreter isn't ready to be used as a standalone library, you can still take it for a test drive. Steps to do that are pretty straight-forward:
- Install the library to your local maven repository.
cd JsInterpreter
mvn install
- Create new Maven project and add the following dependency in
pom.xml
.
<dependency>
<groupId>org.devsh0</groupId>
<artifactId>JsInterpreter</artifactId>
<version>0.1</version>
</dependency>
Also add this property to help the exec plugin find your main class. Replace com.my.package
with your own package specifier.
<properties>
<exec.mainClass>com.my.package.Main</exec.mainClass>
</properties>
- Create a JavaScript source file in your project root and paste the following code.
function fizzbuzz(input) {
let value = "";
if (input % 3 == 0)
value += "fizz";
if (input % 5 == 0)
value += "buzz";
return value;
}
// By default, the last expression is fed back to Java as output.
fizzbuzz(10);
- Create
Main.java
for your main class insrc/main/java
and paste the following code.
public class Main {
public static void main(String[] args) throws IOException {
String code = Files.readString(Paths.get("fizzbuzz.js"));
Program program = Parser.parse(code);
Interpreter interpreter = Interpreter.get();
var output = interpreter.run(program);
System.out.println(output.toString()); // "buzz".
}
}
- Run the application.
mvn exec:java
This should run the application and print "buzz" somewhere in stdout. If you encounter a ClassNotFoundExecption
pointing
to Main
, you probably need this instead:
mvn -X clean install exec:java -Dexec.mainClass="com.my.package.Main" -Dexec.classpathScope=test -e