Created
February 10, 2021 12:09
-
-
Save matozoid/b334f06dad049b78344c5e11a889751a to your computer and use it in GitHub Desktop.
Minimal Java interpreter which only understands integer addition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Author
matozoid
commented
Feb 10, 2021
- "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