📜 Add better documentation across the compiler. (#3)
These changes pay particular attention to API endpoints, to try to ensure that any rustdocs generated are detailed and sensible. A good next step, eventually, might be to include doctest examples, as well. For the moment, it's not clear that they would provide a lot of value, though. In addition, this does a couple refactors to simplify the code base in ways that make things clearer or, at least, briefer.
This commit is contained in:
@@ -4,6 +4,10 @@ use crate::ir::{Expression, Program, Statement};
|
||||
use super::{Primitive, ValueOrRef};
|
||||
|
||||
impl Program {
|
||||
/// Evaluate the program, returning either an error or a string containing everything
|
||||
/// the program printed out.
|
||||
///
|
||||
/// The print outs will be newline separated, with one print out per line.
|
||||
pub fn eval(&self) -> Result<String, EvalError> {
|
||||
let mut env = EvalEnvironment::empty();
|
||||
let mut stdout = String::new();
|
||||
@@ -39,6 +43,9 @@ impl Expression {
|
||||
Expression::Primitive(_, op, args) => {
|
||||
let mut arg_values = Vec::with_capacity(args.len());
|
||||
|
||||
// we implement primitive operations by first evaluating each of the
|
||||
// arguments to the function, and then gathering up all the values
|
||||
// produced.
|
||||
for arg in args.iter() {
|
||||
match arg {
|
||||
ValueOrRef::Ref(_, n) => arg_values.push(env.lookup(n.clone())?),
|
||||
@@ -48,6 +55,8 @@ impl Expression {
|
||||
}
|
||||
}
|
||||
|
||||
// and then finally we call `calculate` to run them. trust me, it's nice
|
||||
// to not have to deal with all the nonsense hidden under `calculate`.
|
||||
match op {
|
||||
Primitive::Plus => Ok(Value::calculate("+", arg_values)?),
|
||||
Primitive::Minus => Ok(Value::calculate("-", arg_values)?),
|
||||
@@ -62,7 +71,7 @@ impl Expression {
|
||||
#[test]
|
||||
fn two_plus_three() {
|
||||
let input = crate::syntax::Program::parse(0, "x = 2 + 3; print x;").expect("parse works");
|
||||
let ir = Program::from(input.simplify());
|
||||
let ir = Program::from(input);
|
||||
let output = ir.eval().expect("runs successfully");
|
||||
assert_eq!("x = 5i64\n", &output);
|
||||
}
|
||||
@@ -71,7 +80,7 @@ fn two_plus_three() {
|
||||
fn lotsa_math() {
|
||||
let input =
|
||||
crate::syntax::Program::parse(0, "x = 2 + 3 * 10 / 5 - 1; print x;").expect("parse works");
|
||||
let ir = Program::from(input.simplify());
|
||||
let ir = Program::from(input);
|
||||
let output = ir.eval().expect("runs successfully");
|
||||
assert_eq!("x = 7i64\n", &output);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user