Skip to content

Instantly share code, notes, and snippets.

@thosakwe
Last active May 13, 2016 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thosakwe/ab4d132702ca1903f72d1e7a983b5e97 to your computer and use it in GitHub Desktop.
Save thosakwe/ab4d132702ca1903f72d1e7a983b5e97 to your computer and use it in GitHub Desktop.
Creating a....
var BaseListener = require('./FooListener').FooListener;
function FooTranspiler() {
BaseListener.call(this);
this.output = "";
}
FooTranspiler.prototype.enterAssignStmt = function(ctx) {
var target = ctx.ID().getText();
var value = this.resolveExpr(ctx.expr());
this.output += "var " + target + " = " + value + ";";
};
FooTranspiler.prototype.enterInvocationStmt = function(ctx) {
var functionName = ctx.name.text;
this.output += functionName + "(";
var expressions = ctx.expr();
for (var i = 0; i < expressions.length; i++) {
if (i > 0) {
this.output += ", ";
}
this.output += this.resolveExpr(expressions[i]);
}
this.output += ");";
};
FooTranspiler.prototype.resolveExpr = function(ctx) {
if (ctx.INT() != null) {
return ctx.INT().getText();
} else if (ctx.ID() != null) {
return ctx.ID().getText();
} else if (ctx.STRING() != null) {
// Replace any occurrence of ${expr}
// with " + expr + "
// i.e.
// "Hello, ${user}!" -> "Hello, " + user + "!"
return ctx.STRING().getText().replace(/\$\{([^\}]+)\}/g, '" + $1 + "');
} else return "undefined";
}
module.exports = FooTranspiler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment