Implement print keyword

This commit is contained in:
Daniel M 2022-02-02 14:05:58 +01:00
parent 02993142df
commit 8c9756b6d2
4 changed files with 36 additions and 4 deletions

View File

@ -45,7 +45,7 @@
- [x] Line comments `//`
- [ ] Strings
- [ ] IO Intrinsics
- [ ] Print
- [x] Print
- [ ] ReadLine
## Grammar

View File

@ -1,4 +1,4 @@
use std::collections::HashMap;
use std::{collections::HashMap, fmt::Display};
use crate::{parser::{Expression, BinOpType, UnOpType, Ast, Statement, parse}, lexer::lex};
@ -37,8 +37,7 @@ impl Interpreter {
for stmt in prog.prog {
match stmt {
Statement::Expr(expr) => {
let result = self.resolve_expr(expr);
println!("Result = {:?}", result);
self.resolve_expr(expr);
}
Statement::Loop(lop) => {
@ -55,6 +54,11 @@ impl Interpreter {
}
}
}
Statement::Print(expr) => {
let result = self.resolve_expr(expr);
println!("{}", result);
}
}
}
@ -132,6 +136,15 @@ impl Interpreter {
}
}
impl Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Value::I64(val) => write!(f, "{}", val),
}
}
}
#[cfg(test)]
mod test {
use super::{Interpreter, Value};

View File

@ -10,8 +10,12 @@ pub enum Token {
/// Identifier (name for variables, functions, ...)
Ident(String),
/// Loop keyword (loop)
Loop,
/// Print keyword (print)
Print,
/// Left Parenthesis ('(')
LParen,
@ -199,6 +203,7 @@ impl<'a> Lexer<'a> {
let token = match ident.as_str() {
"loop" => Token::Loop,
"print" => Token::Print,
_ => Token::Ident(ident),
};

View File

@ -95,6 +95,7 @@ pub struct Loop {
pub enum Statement {
Expr(Expression),
Loop(Loop),
Print(Expression),
}
#[derive(Debug, PartialEq, Eq, Clone)]
@ -142,6 +143,19 @@ impl<T: Iterator<Item = Token>> Parser<T> {
match self.peek() {
Token::Loop => Statement::Loop(self.parse_loop()),
Token::Print => {
self.next();
let expr = self.parse_expr();
// After a statement, there must be a semicolon
if !matches!(self.next(), Token::Semicolon) {
panic!("Expected semicolon after statement");
}
Statement::Print(expr)
}
// If it is not a loop, try to lex as an expression
_ => {
let stmt = Statement::Expr(self.parse_expr());