Skip to content

Commit

Permalink
Add support for Modulus operator
Browse files Browse the repository at this point in the history
  • Loading branch information
AmrDeveloper committed Jul 3, 2023
1 parent b51653a commit 664fd72
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 6 deletions.
1 change: 1 addition & 0 deletions docs/expression/binary.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions src/expression.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ pub enum ArithmeticOperator {
Minus,
Star,
Slash,
Modulus,
}

pub struct ArithmeticExpression {
Expand All @@ -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();
}
Expand Down
12 changes: 7 additions & 5 deletions src/parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
21 changes: 20 additions & 1 deletion src/tokenizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ pub enum TokenKind {
Minus,
Star,
Slash,
Percentage,

Comma,
Dot,
Expand Down Expand Up @@ -206,7 +207,7 @@ pub fn tokenize(script: String) -> Result<Vec<Token>, GQLError> {
continue;
}

// Plus
// Slash
if char == '/' {
let location = Location {
start: column_start,
Expand All @@ -224,6 +225,24 @@ pub fn tokenize(script: String) -> Result<Vec<Token>, 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 {
Expand Down

0 comments on commit 664fd72

Please sign in to comment.