From 2d6d8b6e51bd6ef79034209d4e1af42013a724a1 Mon Sep 17 00:00:00 2001 From: trivernis Date: Sun, 21 Jul 2024 12:19:18 +0200 Subject: [PATCH] Add infix expressions --- src/grammar.pest | 10 ++++++ src/test/infix_expressions.rs | 68 +++++++++++++++++++++++++++++++++++ src/test/mod.rs | 1 + 3 files changed, 79 insertions(+) create mode 100644 src/test/infix_expressions.rs diff --git a/src/grammar.pest b/src/grammar.pest index 9422476..ead9bee 100644 --- a/src/grammar.pest +++ b/src/grammar.pest @@ -1,5 +1,15 @@ file = { "hello world" } +expr = { infix_expr | term } + +term = _{ literal | "(" ~ expr ~ ")" } + +infix_expr = { + #lhs = term ~ operator ~ #rhs = expr +} + +operator = { "+" | "-" | "*" | "/" | "&&" | "||" } + literal = { string | number | boolean } string = { "\"" ~ (!"\"" ~ ANY)* ~ "\"" } diff --git a/src/test/infix_expressions.rs b/src/test/infix_expressions.rs new file mode 100644 index 0000000..c96e9dc --- /dev/null +++ b/src/test/infix_expressions.rs @@ -0,0 +1,68 @@ +use pest::{consumes_to, parses_to}; + +use crate::{Rule, SnekParser}; + +#[test] +fn it_parses_addition() { + parses_to!(parser: SnekParser, input: "1 + 1", rule: Rule::expr, tokens: [ + expr(0, 5, [ + infix_expr(0, 5, [ + literal(0, 1, [ + integer(0, 1) + ]), + operator(2, 3), + expr(4, 5, [ + literal(4, 5, [ + integer(4, 5) + ]) + ]) + ]) + ]) + ]); +} + +#[test] +fn it_parses_subtraction() { + parses_to!(parser: SnekParser, input: "1.0 - 1.1", rule: Rule::expr, tokens: [ + expr(0, 9, [ + infix_expr(0, 9, [ + literal(0, 3, [ + float(0, 3) + ]), + operator(4, 5), + expr(6, 9, [ + literal(6, 9, [ + float(6, 9) + ]) + ]) + ]) + ]) + ]); +} + +#[test] +fn it_parses_multiple_operations() { + parses_to!(parser: SnekParser, input: "1 + 2 + 3", rule: Rule::expr, tokens: [ + expr(0, 9, [ + infix_expr(0, 9, [ + literal(0, 1, [ + integer(0, 1) + ]), + operator(2, 3), + expr(4, 9, [ + infix_expr(4, 9, [ + literal(4, 5, [ + integer(4, 5) + ]), + operator(6, 7), + expr(8, 9, [ + literal(8, 9, [ + integer(8, 9) + ]) + ]) + ]) + ]) + ]) + ]) + ]); +} diff --git a/src/test/mod.rs b/src/test/mod.rs index ede3f4b..c8c2ab2 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -1,4 +1,5 @@ use pest::iterators::Pair; +mod infix_expressions; mod literals; use crate::{parse, parse_rule, Rule};