CalcLox is a standalone Java 21 library for embedding a small, calculator-oriented scripting language. It supports variables, arithmetic and logical expressions, control flow, functions, host-provided numeric values, and output callbacks.
The language is a simplified version of Lox, without some features like classes and inheritance, and is designed to be used in a calculator application.
./gradlew buildThe published module coordinates are tech.ixor:calclox:<version>.
Implement CalculatorFrontend to expose mutable numeric variables and collect output, then pass
it and a program to CalcLoxRunner.run:
import tech.ixor.calclox.CalcLoxRunner;
import tech.ixor.calclox.CalculatorFrontend;
import java.util.HashMap;
import java.util.Map;
Map<String, Double> variables = new HashMap<>();
variables.put("principal", 100.0);
CalculatorFrontend frontend = new CalculatorFrontend() {
public Map<String, Double> variables() { return variables; }
public void output(String result) { System.out.println(result); }
};
CalcLoxRunner.run(frontend, """
define principal;
var doubled = principal * 2;
output doubled;
""");define imports an existing host variable. Numeric declarations and assignments are written
back to the frontend map. Each call uses an isolated interpreter. Invalid source or runtime
failures throw CalcLoxRunnerError, whose getLine() method identifies the source line.
fun square(value) {
return value * value;
}
for (var i = 1; i <= 3; i = i + 1) {
output square(i);
}
CalcLox intentionally omits classes and inheritance. The built-in clock() returns Unix time in
seconds, and eval(string) evaluates a CalcLox expression in the current program environment.
Full documentation:
- Crafting Interpreters by Bob Nystrom. This book introduces the Lox language. This book also contains a guide for building a tree-walk interpreter, which was used as a reference for building the CalcLox interpreter.
- Project Structure Generated from https://github.com/thriving-dev/java-library-template.