Implement print keyword

This commit is contained in:
Daniel M 2022-02-02 14:05:58 +01:00
parent 4357a1eb55
commit 99e462f4b5
4 changed files with 36 additions and 4 deletions

View File

@ -45,7 +45,7 @@
- [x] Line comments `//` - [x] Line comments `//`
- [ ] Strings - [ ] Strings
- [ ] IO Intrinsics - [ ] IO Intrinsics
- [ ] Print - [x] Print
- [ ] ReadLine - [ ] ReadLine
## Grammar ## 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}; use crate::{parser::{Expression, BinOpType, UnOpType, Ast, Statement, parse}, lexer::lex};
@ -37,8 +37,7 @@ impl Interpreter {
for stmt in prog.prog { for stmt in prog.prog {
match stmt { match stmt {
Statement::Expr(expr) => { Statement::Expr(expr) => {
let result = self.resolve_expr(expr); self.resolve_expr(expr);
println!("Result = {:?}", result);
} }
Statement::Loop(lop) => { 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)] #[cfg(test)]
mod test { mod test {
use super::{Interpreter, Value}; use super::{Interpreter, Value};

View File

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

View File

@ -95,6 +95,7 @@ pub struct Loop {
pub enum Statement { pub enum Statement {
Expr(Expression), Expr(Expression),
Loop(Loop), Loop(Loop),
Print(Expression),
} }
#[derive(Debug, PartialEq, Eq, Clone)] #[derive(Debug, PartialEq, Eq, Clone)]
@ -142,6 +143,19 @@ impl<T: Iterator<Item = Token>> Parser<T> {
match self.peek() { match self.peek() {
Token::Loop => Statement::Loop(self.parse_loop()), 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 // If it is not a loop, try to lex as an expression
_ => { _ => {
let stmt = Statement::Expr(self.parse_expr()); let stmt = Statement::Expr(self.parse_expr());