Implement unary expressions

This commit is contained in:
Matt Sherman 2023-10-03 19:13:56 -04:00
parent 6237c8caea
commit d82737fb81
2 changed files with 41 additions and 1 deletions

View File

@ -5,6 +5,23 @@ import * as peggy from 'peggy';
const grammar = `
{{
function evaluateUnaryExpression( operator, operand ) {
switch ( operator ) {
case '!':
return !operand;
break;
case '-':
return -operand;
break;
case '+':
return +operand;
break;
default:
return undefined;
break;
}
}
function evaluateBinaryExpression( head, tail ) {
return tail.reduce( ( leftOperand, tailElement ) => {
const operator = tailElement[ 1 ];
@ -262,8 +279,19 @@ PrimaryExpression
return expression;
}
RelationalExpression
UnaryExpression
= PrimaryExpression
/ operator:UnaryOperator WhiteSpace* operand:UnaryExpression {
return evaluateUnaryExpression( operator, operand );
}
UnaryOperator
= "!"
/ "-"
/ "+"
RelationalExpression
= UnaryExpression
EqualityExpression
= head:RelationalExpression tail:( WhiteSpace* EqualityOperator WhiteSpace* RelationalExpression)* {

View File

@ -196,6 +196,18 @@ describe( 'parser', () => {
expect( result ).toEqual( true );
} );
it( 'should parse a negative number', () => {
const result = parser.parse( '-1' );
expect( result ).toEqual( -1 );
} );
it( 'should parse a positive number', () => {
const result = parser.parse( '+1' );
expect( result ).toEqual( 1 );
} );
it( 'should throw an error if the expression is invalid', () => {
expect( () => parser.parse( '= 1' ) ).toThrow();
} );