From 899c1cebd583cbece46f9fe64ab2c2c5064d5622 Mon Sep 17 00:00:00 2001 From: trivernis Date: Sun, 21 Jul 2024 15:10:46 +0200 Subject: [PATCH] Add function call support --- src/grammar.pest | 5 ++- .../{infix_expressions.rs => expressions.rs} | 33 +++++++++++++++++++ src/test/mod.rs | 2 +- src/test/statements.rs | 25 +++++++++++++- 4 files changed, 62 insertions(+), 3 deletions(-) rename src/test/{infix_expressions.rs => expressions.rs} (69%) diff --git a/src/grammar.pest b/src/grammar.pest index 21ceb0f..2adcb19 100644 --- a/src/grammar.pest +++ b/src/grammar.pest @@ -3,8 +3,11 @@ file = { "hello world" } statement = { decl } decl = { "let" ~ #name = ident ~ #args = (ident)* ~ "=" ~ expr } -expr = { infix_expr | term } +expr = { infix_expr | call_expr | term } term = _{ ident | literal | "(" ~ expr ~ ")" } +call_expr = { + #name = ident ~ #args = (term)+ +} infix_expr = { #lhs = term ~ operator ~ #rhs = expr } diff --git a/src/test/infix_expressions.rs b/src/test/expressions.rs similarity index 69% rename from src/test/infix_expressions.rs rename to src/test/expressions.rs index 853d67c..dc67956 100644 --- a/src/test/infix_expressions.rs +++ b/src/test/expressions.rs @@ -81,3 +81,36 @@ fn it_parses_multiple_operations() { ]) ]); } + +#[test] +fn it_parses_calls() { + parses_to!(parser: SnekParser, input: "print a", rule: Rule::expr, tokens: [ + expr(0, 7, [ + call_expr(0, 7, [ + ident(0, 5), + ident(6, 7), + ]) + ]) + ]); + parses_to!(parser: SnekParser, input: "print (1 + 1) a", rule: Rule::expr, tokens: [ + expr(0, 15, [ + call_expr(0, 15, [ + ident(0, 5), + expr(7, 12, [ + infix_expr(7, 12, [ + literal(7, 8, [ + integer(7, 8) + ]), + operator(9, 10), + expr(11, 12, [ + literal(11, 12, [ + integer(11, 12) + ]), + ]) + ]) + ]), + ident(14, 15) + ]) + ]) + ]); +} diff --git a/src/test/mod.rs b/src/test/mod.rs index 2d409a1..255b9e3 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -1,4 +1,4 @@ -mod infix_expressions; +mod expressions; mod literals; mod statements; diff --git a/src/test/statements.rs b/src/test/statements.rs index 6b9dde1..8ca3469 100644 --- a/src/test/statements.rs +++ b/src/test/statements.rs @@ -3,7 +3,7 @@ use pest::{consumes_to, parses_to}; use crate::{Rule, SnekParser}; #[test] -fn it_parses_assignments() { +fn it_parses_plain_assignments() { parses_to!(parser: SnekParser, input: "let a = 1", rule: Rule::statement, tokens: [ statement(0, 9, [ decl(0, 9, [ @@ -17,3 +17,26 @@ fn it_parses_assignments() { ]) ]); } + +#[test] +fn it_parses_assignments_with_args() { + parses_to!(parser: SnekParser, input: "let add a = a + 1", rule: Rule::statement, tokens: [ + statement(0, 17, [ + decl(0, 17, [ + ident(4, 7), + ident(8, 9), + expr(12, 17, [ + infix_expr(12, 17, [ + ident(12, 13), + operator(14, 15), + expr(16, 17, [ + literal(16, 17, [ + integer(16, 17) + ]) + ]) + ]) + ]) + ]) + ]) + ]); +}