rcalc is a glorified calculator with a lexer, parser, and interpreter written in Rust. This
documentation covers the library form of
rcalc; creating an application from the library is
trivial, as will be shown later on.
rcalc parses mathematical expressions, observing accepted operand precedence and computing
the results of the expressions. Its operation is fairly simple:
- The Lexer reads in tokens from the program, one at a time.
- The Parser attempts to identify the significance and type of each token, observing mathematical orders of operations during this analysis.
- The Parser places each token in an Abstract Syntax Tree, in a position relative to the relationships the current token has with adjacent tokens.
- The Interpreter traverses the AST node-by-node, building up the result of the program.
Each component of
rcalc has been split into individual components for purposes of
readibility, fast access, and easy refactoring. The Lexer, Parser, and Interpreter should be
fairly easy to understand and extend in other applications or libraries.
A mathematical expression can quickly be evaluated in
let expr = "2 + 3 * 5"; let mut program = Interpreter::from(expr); let result = program.interpret().unwrap(); // => 17
The Lexer and Parser can also be implemented indendependently. However, the only public APIs avaliable are to generate the next token of the program, and to create an AST from the Parser.
let mut lexer = Lexer::from(expr); let next_token: Token = lexer.next_token().unwrap(); let mut parser = Parser::from(lexer); let tree: ASTNode = parser.parse().unwrap();
An Interpereter can currently only be created from a String representing a program. Attempts to create an Interpreter from a Parser or AST are currently impossible, but may be supported later.
let lexer = Lexer::from(expr); let parser = Parser::from(lexer); let program = Interpreter::from(parser); // will fail!
Describes a node in an Abstract Syntax Tree.
An interpreter for a mathematical expression.
A lexer (tokenizer) for a mathematical expression.
A parser for a mathematical expression.
Describes a Token scanned by the Lexer.