Implement print keyword
This commit is contained in:
parent
4357a1eb55
commit
99e462f4b5
@ -45,7 +45,7 @@
|
||||
- [x] Line comments `//`
|
||||
- [ ] Strings
|
||||
- [ ] IO Intrinsics
|
||||
- [ ] Print
|
||||
- [x] Print
|
||||
- [ ] ReadLine
|
||||
|
||||
## Grammar
|
||||
|
||||
@ -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};
|
||||
|
||||
@ -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),
|
||||
};
|
||||
|
||||
|
||||
@ -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());
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user