From 664fd72dcbd6abf8a7d01728b3be05de0faefaea Mon Sep 17 00:00:00 2001 From: AmrDeveloper Date: Mon, 3 Jul 2023 16:39:12 +0200 Subject: [PATCH] Add support for Modulus operator --- docs/expression/binary.md | 1 + src/expression.rs | 2 ++ src/parser.rs | 12 +++++++----- src/tokenizer.rs | 21 ++++++++++++++++++++- 4 files changed, 30 insertions(+), 6 deletions(-) diff --git a/docs/expression/binary.md b/docs/expression/binary.md index 76f3e43e..d4124baa 100644 --- a/docs/expression/binary.md +++ b/docs/expression/binary.md @@ -8,6 +8,7 @@ Used to perform arithmetic operators on number types. - `-` Subtraction. - `*` Multiplication. - `/` Division. +- `%` Modulus. ### Comparison Expression - `=` used to check if field equal to expected value. diff --git a/src/expression.rs b/src/expression.rs index d53926ef..166d270d 100644 --- a/src/expression.rs +++ b/src/expression.rs @@ -92,6 +92,7 @@ pub enum ArithmeticOperator { Minus, Star, Slash, + Modulus, } pub struct ArithmeticExpression { @@ -109,6 +110,7 @@ impl Expression for ArithmeticExpression { ArithmeticOperator::Minus => lhs - rhs, ArithmeticOperator::Star => lhs * rhs, ArithmeticOperator::Slash => lhs / rhs, + ArithmeticOperator::Modulus => lhs % rhs, } .to_string(); } diff --git a/src/parser.rs b/src/parser.rs index 65582310..83ad952e 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -875,14 +875,16 @@ fn parse_factor_expression( while *position < tokens.len() && (&tokens[*position].kind == &TokenKind::Star - || &tokens[*position].kind == &TokenKind::Slash) + || &tokens[*position].kind == &TokenKind::Slash + || &tokens[*position].kind == &TokenKind::Percentage) { let operator = &tokens[*position]; *position += 1; - let factor_operator = if operator.kind == TokenKind::Star { - ArithmeticOperator::Star - } else { - ArithmeticOperator::Slash + + let factor_operator = match operator.kind { + TokenKind::Star => ArithmeticOperator::Star, + TokenKind::Slash => ArithmeticOperator::Slash, + _ => ArithmeticOperator::Modulus, }; let right_expr = parse_check_expression(tokens, position); diff --git a/src/tokenizer.rs b/src/tokenizer.rs index 7bba0d35..5d6eb788 100644 --- a/src/tokenizer.rs +++ b/src/tokenizer.rs @@ -45,6 +45,7 @@ pub enum TokenKind { Minus, Star, Slash, + Percentage, Comma, Dot, @@ -206,7 +207,7 @@ pub fn tokenize(script: String) -> Result, GQLError> { continue; } - // Plus + // Slash if char == '/' { let location = Location { start: column_start, @@ -224,6 +225,24 @@ pub fn tokenize(script: String) -> Result, GQLError> { continue; } + // Percentage + if char == '%' { + let location = Location { + start: column_start, + end: position, + }; + + let token = Token { + location: location, + kind: TokenKind::Percentage, + literal: "%".to_owned(), + }; + + tokens.push(token); + position += 1; + continue; + } + // Or if char == '|' { let location = Location {