Skip to content

Commit 9803de1

Browse files
authored
Support constant value expressions (#27)
1 parent 94438f0 commit 9803de1

File tree

4 files changed

+11
-2
lines changed

4 files changed

+11
-2
lines changed

book/src/01_calculator/grammar_lexer_parser.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ Don't let this overwhelm you - let's break it down line by line:
3333

3434
**`Expr = { UnaryExpr | BinaryExpr | Term }`** - An expression is either unary (`-1`), binary (`1 + 2`), or a simple term (just a number). The `|` means "or" - try each alternative in order.
3535

36-
**`Term = _{ Int | "(" ~ Expr ~ ")" }`** - A term is either a number or a parenthesized expression. This is how we handle `(1 + 2) * 3` - the parenthesized part becomes a single term.
36+
**`Term = { Int | "(" ~ Expr ~ ")" }`** - A term is either a number or a parenthesized expression. This is how we handle `(1 + 2) * 3` - the parenthesized part becomes a single term.
3737

3838
**`UnaryExpr = { Operator ~ Term }`** - A unary expression is an operator followed by a term, like `-1` or `+5`.
3939

calculator/src/compiler/interpreter.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ mod tests {
5757

5858
#[test]
5959
fn basics() {
60+
assert_eq!(Interpreter::from_source("1").unwrap() as i32, 1);
6061
assert_eq!(Interpreter::from_source("1 + 2").unwrap() as i32, 3);
6162
// assert_eq!(Interpreter::source("(1 + 2)").unwrap() as i32, 3);
6263
assert_eq!(Interpreter::from_source("2 + (2 - 1)").unwrap() as i32, 3);

calculator/src/grammar.pest

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ Program = _{ SOI ~ Expr ~ EOF }
22

33
Expr = { BinaryExpr | UnaryExpr | Term }
44

5-
Term = _{ Int | "(" ~ Expr ~ ")" }
5+
Term = { Int | "(" ~ Expr ~ ")" }
66

77
UnaryExpr = { Operator ~ Term }
88

calculator/src/parser.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,15 @@ fn build_ast_from_expr(pair: pest::iterators::Pair<Rule>) -> Node {
6262
}
6363
}
6464
}
65+
Rule::Term => build_ast_from_term(pair),
6566
unknown => panic!("Unknown expr: {:?}", unknown),
6667
}
6768
}
6869

6970
fn build_ast_from_term(pair: pest::iterators::Pair<Rule>) -> Node {
71+
assert_eq!(pair.as_rule(), Rule::Term);
72+
73+
let pair = pair.into_inner().next().unwrap();
7074
match pair.as_rule() {
7175
Rule::Int => {
7276
let int: i32 = pair.as_str().parse().unwrap();
@@ -106,6 +110,10 @@ mod tests {
106110
#[test]
107111
fn basics() {
108112
assert!(parse("b").is_err());
113+
114+
let one = parse("1");
115+
assert!(one.is_ok());
116+
assert_eq!(one.unwrap()[0], Node::Int(1));
109117
}
110118

111119
#[test]

0 commit comments

Comments
 (0)