Skip to content

Commit

Permalink
fix: implement unary NOT case for reduceExpr (#415)
Browse files Browse the repository at this point in the history
Fixes #414
  • Loading branch information
chrispcampbell authored Dec 5, 2023
1 parent 9269098 commit ce66990
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
4 changes: 4 additions & 0 deletions packages/parse/src/ast/reduce-expr.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ describe('reduceExpr', () => {
expect(reduceExpr(unaryOp('+', num(3)))).toEqual(num(3))
expect(reduceExpr(unaryOp('-', num(3)))).toEqual(num(-3))

expect(reduceExpr(unaryOp(':NOT:', num(2)))).toEqual(num(0))
expect(reduceExpr(unaryOp(':NOT:', num(1)))).toEqual(num(0))
expect(reduceExpr(unaryOp(':NOT:', num(0)))).toEqual(num(1))

expect(reduceExpr(binaryOp(num(3), '+', num(2)))).toEqual(num(5))
expect(reduceExpr(binaryOp(num(3), '-', num(2)))).toEqual(num(1))
expect(reduceExpr(binaryOp(num(3), '*', num(2)))).toEqual(num(6))
Expand Down
10 changes: 9 additions & 1 deletion packages/parse/src/ast/reduce-expr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,15 @@ export function reduceExpr(expr: Expr, opts?: ReduceExprOptions): Expr {
return unaryOp('-', child)
}
case ':NOT:':
throw new Error('not yet implemented')
if (child.kind === 'number') {
// Use the same behavior as C and negate the numeric value. ("The result of the
// logical negation operator ! is 0 if the value of its operand compares unequal
// to 0, 1 if the value of its operand compares equal to 0.")
return num(child.value === 0 ? 1 : 0)
} else {
// Cannot simplify further
return unaryOp(':NOT:', child)
}
default:
assertNever(expr)
}
Expand Down

0 comments on commit ce66990

Please sign in to comment.