Added non-newline print.

This commit is contained in:
Erin 2022-05-03 23:13:17 +02:00 committed by ondra05
parent fd97655e04
commit 6ad0ab5e29
3 changed files with 134 additions and 99 deletions

View file

@ -136,7 +136,10 @@ pub enum Stmt {
expr: Spanned<Expr>,
args: Vec<Spanned<Expr>>,
},
Print(Spanned<Expr>),
Print {
expr: Spanned<Expr>,
newline: bool,
},
Read(Assignable),
Melo(Spanned<String>),
Rlyeh,

View file

@ -214,8 +214,14 @@ impl ExecEnv {
/// Perform the action indicated by a statement.
fn eval_stmt(&mut self, stmt: &Spanned<Stmt>) -> Result<HaltStatus, Error> {
match &stmt.item {
Stmt::Print(expr) => {
println!("{}", self.eval_expr(expr)?);
Stmt::Print { expr, newline } => {
let value = self.eval_expr(expr)?;
if *newline {
println!("{value}");
} else {
print!("{value}");
stdout().lock().flush()?;
}
}
Stmt::Dim { ident, init } => {
let init = match init {

View file

@ -363,10 +363,24 @@ impl<'source> Parser<'source> {
match self.checked_next()? {
// Print to stdout
Token::Print => {
let stmt = Stmt::Print(buf.take().ok_or_else(|| {
break Stmt::Print {
expr: buf.take().ok_or_else(|| {
Error::new(ErrorKind::UnexpectedToken(Token::Print), self.lexer.span())
})?);
break self.semicolon_terminated(stmt)?;
})?,
newline: match self.checked_next()? {
Token::Semicolon => true,
Token::Minus => {
self.require(Token::Semicolon)?;
false
}
token => {
return Err(Error::new(
ErrorKind::UnexpectedToken(token),
self.lexer.span(),
));
}
},
};
}
// Functio call
@ -642,7 +656,8 @@ mod tests {
fn simple_math() {
let code = "1 * (num + 3) / 666 print;";
let expected = &[Spanned {
item: Stmt::Print(Spanned {
item: Stmt::Print {
expr: Spanned {
item: Expr::BinOp {
lhs: Box::new(Spanned {
item: Expr::BinOp {
@ -675,7 +690,9 @@ mod tests {
kind: BinOpKind::Divide,
},
span: 0..17,
}),
},
newline: true,
},
span: 0..24,
}];
@ -724,10 +741,13 @@ mod tests {
span: 8..21,
},
body: vec![Spanned {
item: Stmt::Print(Spanned {
item: Stmt::Print {
expr: Spanned {
item: Expr::Literal(Literal::Str("Buy Able products!".to_owned())),
span: 25..47,
}),
},
newline: true,
},
span: 25..54,
}],
},
@ -773,7 +793,8 @@ mod tests {
fn cart_construction() {
let code = "[/*able*/ <= 1, /*script*/ <= 3 - 1] print;";
let expected = &[Spanned {
item: Stmt::Print(Spanned {
item: Stmt::Print {
expr: Spanned {
item: Expr::Cart(vec![
(
Spanned {
@ -807,7 +828,9 @@ mod tests {
),
]),
span: 0..32,
}),
},
newline: true,
},
span: 0..39,
}];
@ -819,7 +842,8 @@ mod tests {
fn cart_index() {
let code = "[/*able*/ <= /*ablecorp*/][/*ablecorp*/] print;";
let expected = &[Spanned {
item: Stmt::Print(Spanned {
item: Stmt::Print {
expr: Spanned {
item: Expr::Index {
expr: Box::new(Spanned {
item: Expr::Cart(vec![(
@ -840,7 +864,9 @@ mod tests {
}),
},
span: 0..34,
}),
},
newline: true,
},
span: 0..41,
}];