Crate rcalc [] [src]

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:

  1. The Lexer reads in tokens from the program, one at a time.
  2. The Parser attempts to identify the significance and type of each token, observing mathematical orders of operations during this analysis.
  3. The Parser places each token in an Abstract Syntax Tree, in a position relative to the relationships the current token has with adjacent tokens.
  4. 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.

Examples

A mathematical expression can quickly be evaluated in rcalc:

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.

This code doesn't compile so be extra careful!
let lexer = Lexer::from(expr);
let parser = Parser::from(lexer);
let program = Interpreter::from(parser); // will fail!

Structs

ASTNode

Describes a node in an Abstract Syntax Tree.

Interpreter

An interpreter for a mathematical expression.

Lexer

A lexer (tokenizer) for a mathematical expression.

Parser

A parser for a mathematical expression.

Enums

Token

Describes a Token scanned by the Lexer.