Skip to content

Commit

Permalink
Merge pull request #5 from froth/parser
Browse files Browse the repository at this point in the history
Testing based on to_string, wrong but more readable
  • Loading branch information
froth authored Jan 11, 2024
2 parents b654848 + 59d161a commit ad64b45
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 20 deletions.
2 changes: 1 addition & 1 deletion src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl Expr {
impl Display for Expr {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Binary(left, token, right) => write!(f, "({} {} {})", token.lexeme, left, right),
Self::Binary(left, token, right) => write!(f, "({} {} {})", token.token_type, left, right),
Self::Grouping(expr) => write!(f, "(group {})", expr),
Self::Literal(literal) => write!(f, "({})", literal),
Self::Unary(token, right) => write!(f, "({} {})", token.lexeme, right),
Expand Down
21 changes: 2 additions & 19 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ mod parser_tests {
];
let mut parser = Parser::new(tokens);
let expr = parser.parse();
assert_matches!(expr, Expr::Literal(Literal::String(s)) if string == s);
assert_eq!(expr.to_string(), r#"("foo")"#);
}

#[test]
Expand All @@ -144,24 +144,7 @@ mod parser_tests {
];
let mut parser = Parser::new(tokens);
let expr = parser.parse();
match expr {
Expr::Binary(lhs, op, rhs) => {
assert_matches!(op.token_type, TokenType::EqualEqual);
assert_matches!(
*lhs,
Expr::Binary(
_,
Token {
token_type: TokenType::BangEqual,
..
},
_
)
);
assert_matches!(*rhs, Expr::Literal(Literal::String(_)));
}
_ => panic!("should be binary"),
}
assert_eq!(expr.to_string(), r#"(EqualEqual (BangEqual ("foo") ("foo")) ("foo"))"#);
}

fn token(token_type: TokenType) -> Token {
Expand Down
8 changes: 8 additions & 0 deletions src/token.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt::Display;

#[derive(Debug, Clone)]
pub enum TokenType {
//single character tokens.
Expand Down Expand Up @@ -49,6 +51,12 @@ pub enum TokenType {
Eof,
}

impl Display for TokenType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self) // Display in terms of debug. Antipattern?
}
}

#[derive(Debug, Clone)]
pub struct Token {
pub token_type: TokenType,
Expand Down

0 comments on commit ad64b45

Please sign in to comment.