Skip to content

Instantly share code, notes, and snippets.

@matozoid
Created February 10, 2021 12:09
Show Gist options
  • Save matozoid/b334f06dad049b78344c5e11a889751a to your computer and use it in GitHub Desktop.
Save matozoid/b334f06dad049b78344c5e11a889751a to your computer and use it in GitHub Desktop.
Minimal Java interpreter which only understands integer addition
package test;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.expr.BinaryExpr;
import com.github.javaparser.ast.expr.IntegerLiteralExpr;
import com.github.javaparser.ast.visitor.GenericVisitorAdapter;
public class Test {
public static void main(String[] args) {
System.out.println(StaticJavaParser.parseExpression("1+2+3").accept(new IntegerLiteralVisitor(), null));
}
static class IntegerLiteralVisitor extends GenericVisitorAdapter<Integer, Void> {
@Override
public Integer visit(BinaryExpr n, Void arg) {
Integer leftValue = n.getLeft().accept(this, arg);
Integer rightValue = n.getRight().accept(this, arg);
return leftValue + rightValue;
}
@Override
public Integer visit(IntegerLiteralExpr integerLiteralExpr, Void arg) {
return integerLiteralExpr.asNumber().intValue();
}
}
}
@matozoid
Copy link
Author

  • "intValue" can fail in a very extreme case (see Javadoc)
  • only integer literals and binary expressions are understood
  • every binary expression is assumed to be an integer addition

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment