Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions core/ast/src/expression/literal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,27 @@ pub enum LiteralKind {
Undefined,
}

/// Represents a numeric value.
#[derive(Debug, Clone, Copy)]
pub enum Number {
/// An integer.
Int(i32),
/// A floating point number.
Num(f64),
}

impl LiteralKind {
/// Returns [`Number::Int`] for [`LiteralKind::Int`], [`Number::Num`] for [`LiteralKind::Num`], and [`None`] otherwise.
#[must_use]
pub fn as_number(&self) -> Option<Number> {
Some(match self {
Self::Int(int) => Number::Int(*int),
Self::Num(num) => Number::Num(*num),
_ => return None,
})
}
}

/// Manual implementation, because `Undefined` is never constructed during parsing.
#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for LiteralKind {
Expand Down
16 changes: 14 additions & 2 deletions core/engine/src/bytecompiler/expression/unary.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::bytecompiler::{Access, BindingAccessOpcode, ByteCompiler, Register, ToJsString};
use boa_ast::Expression;
use boa_ast::expression::literal::Number;
use boa_ast::expression::operator::{Unary, unary::UnaryOp};

impl ByteCompiler<'_> {
Expand All @@ -18,8 +19,19 @@ impl ByteCompiler<'_> {
}
}
UnaryOp::Minus => {
self.compile_expr(unary.target(), dst);
self.bytecode.emit_neg(dst.variable());
if let Expression::Literal(literal) = unary.target().flatten()
&& let Some(number) = literal.kind().as_number()
{
match number {
// Handles special case -0
Number::Int(0) => self.emit_store_rational(-0.0, dst),
Number::Int(value) => self.emit_store_integer(-value, dst),
Number::Num(value) => self.emit_store_rational(-value, dst),
Comment on lines +27 to +29
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about BigInt?

}
} else {
self.compile_expr(unary.target(), dst);
self.bytecode.emit_neg(dst.variable());
}
}
UnaryOp::Plus => {
self.compile_expr(unary.target(), dst);
Expand Down
Loading