Interpreter - Run programs.
This commit is contained in:
parent
bf11a2b63a
commit
14aef73d93
2 changed files with 39 additions and 0 deletions
|
@ -42,6 +42,43 @@ pub fn evaluate(err_hdl: &mut ErrorHandler, ast: &dyn Interpretable) -> Option<V
|
|||
}
|
||||
}
|
||||
|
||||
/* ----------------------------- *
|
||||
* INTERPRETER FOR PROGRAM NODES *
|
||||
* ----------------------------- */
|
||||
|
||||
impl Interpretable for ast::ProgramNode {
|
||||
fn interprete(&self) -> Result<Value, InterpreterError> {
|
||||
for stmt in self.0.iter() {
|
||||
stmt.interprete()?;
|
||||
}
|
||||
Ok(Value::Nil)
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------- *
|
||||
* INTERPRETER FOR STATEMENT NODES *
|
||||
* ------------------------------- */
|
||||
|
||||
impl Interpretable for ast::StmtNode {
|
||||
fn interprete(&self) -> Result<Value, InterpreterError> {
|
||||
match self {
|
||||
ast::StmtNode::Expression(expr) => expr.interprete(),
|
||||
ast::StmtNode::Print(expr) => {
|
||||
let value = expr.interprete()?;
|
||||
let output = match value {
|
||||
Value::Nil => String::from("nil"),
|
||||
Value::Boolean(true) => String::from("true"),
|
||||
Value::Boolean(false) => String::from("false"),
|
||||
Value::Number(n) => n.to_string(),
|
||||
Value::String(s) => s,
|
||||
};
|
||||
println!("{}", output);
|
||||
Ok(Value::Nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------- *
|
||||
* INTERPRETER FOR EXPRESSION NODES *
|
||||
* -------------------------------- */
|
||||
|
|
|
@ -75,9 +75,11 @@ impl Parser {
|
|||
fn parse_statement(&mut self) -> Result<ast::StmtNode, ParserError> {
|
||||
if self.expect(&[TokenType::Print]).is_some() {
|
||||
let expression = self.parse_expression()?;
|
||||
self.consume(&TokenType::Semicolon, "expected ';' after value")?;
|
||||
Ok(ast::StmtNode::Print(expression))
|
||||
} else {
|
||||
let expression = self.parse_expression()?;
|
||||
self.consume(&TokenType::Semicolon, "expected ';' after expression")?;
|
||||
Ok(ast::StmtNode::Expression(expression))
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue