Compiler in JavaScript using ANTLR

Alena Khineika
Jul 3, 2018 · 15 min read
Image for post
Image for post
Image for post
Image for post

Terms

Investigation

Image for post
Image for post
Image for post
Image for post

Writing a compiler

ANTLR installation

$ brew cask install java
$ cd /usr/local/lib
$ curl -O http://www.antlr.org/download/antlr-4.7.1-complete.jar
$ export CLASSPATH=".:/usr/local/lib/antlr-4.7.1-complete.jar:$CLASSPATH"
$ alias antlr4='java -Xmx500M -cp "/usr/local/lib/antlr-4.7.1-complete.jar:$CLASSPATH" org.antlr.v4.Tool'
$ alias grun='java org.antlr.v4.gui.TestRig'
$ java org.antlr.v4.Tool
Image for post
Image for post

Creating a Node.js project with ANTLR

$ mkdir js-runtime
$ cd js-runtime
$ npm init
$ npm i antlr4 --save
$ mkdir grammars
$ curl --http1.1 https://github.com/antlr/grammars-v4/blob/master/ecmascript/ECMAScript.g4 --output grammars/ECMAScript.g4
$ java -Xmx500M -cp '/usr/local/lib/antlr-4.7.1-complete.jar:$CLASSPATH' org.antlr.v4.Tool  -Dlanguage=JavaScript -lib grammars -o lib -visitor -Xexact-output-dir grammars/ECMAScript.g4
Image for post
Image for post
$ java -Xmx500M -cp '/usr/local/lib/antlr-4.7.1-complete.jar:$CLASSPATH' org.antlr.v4.Tool  -Dlanguage=JavaScript -lib grammars -o lib -visitor -Xexact-output-dir grammars/ECMAScript.g4

Source code analysis and syntax tree construction

Image for post
Image for post

Code generation

$ mkdir codegeneration
$ cd codegeneration
$ touch PythonGenerator.js
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
$ npm run compile
Image for post
Image for post

Error handling

Image for post
Image for post
$ mkdir error
$ cd error
$ touch helper.js
$ touch config.json
Image for post
Image for post
Image for post
Image for post

Conclusion

DailyJS

JavaScript news and opinion.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store