fix: 负零字面量折叠保符号不丢负号

This commit is contained in:
2026-10-12 13:56:07 +00:00
parent 01b47c030a
commit 737931b3e7
4 changed files with 60 additions and 21 deletions
@@ -34,10 +34,17 @@ use crate::shared::string_pool::{pool_key_marker, pool_key_plain};
///
/// 一元负号只沿 `UnaryNegation` 链剥(含嵌套负号与括号),其余一元运算符
/// (`!`/`typeof`/`void`/`~`/`+`/`delete`)终止剥壳不折。
///
/// 负零字面量(`-0`/`-0.0`)定值 `Number(-0.0)` 保符号:`is_int_literal(-0.0)`
/// 为真,走 i32 臂会在 `as i32` 处丢符号。
pub(crate) fn literal_constant(expr: &Expression) -> Option<Constant> {
let (inner, negated) = peel_negation(expr);
match inner {
Expression::NumericLiteral(n) => {
// 负零直接定值 `Number(-0.0)`,镜像运行时 `NEG` 对零的产物。
if negated && n.value == 0.0 {
return Some(Constant::Number(-0.0));
}
let value = if negated { -n.value } else { n.value };
if is_int_literal(value) {
Some(Constant::Int(value as i32))
+32
View File
@@ -243,3 +243,35 @@ fn fold_deterministic() {
}
}
}
/// 负零字面量符号保真:折叠后常量池须含 `Number(-0.0)`(符号位置位),
/// 不得走 i32 臂(`-0.0 as i32` 丢符号成 `Int(0)`)。符号位经 `to_bits`
/// 比对——`Number(-0.0)` 与 `Number(0.0)` 的 `PartialEq` 相等,不能用
/// `pool_contains` 判别。
#[test]
fn fold_negative_zero_sign() {
let cases: &[(&str, OpCode)] = &[
("-0 - 0", OpCode::SUB),
("-0 * 1", OpCode::MUL),
("-0 / 1", OpCode::DIV),
("-0 % 1", OpCode::MOD),
("(-0) ** 3", OpCode::EXP),
];
let neg_zero_bits = (-0.0f64).to_bits();
for (src, op) in cases {
let ir = emit_ir(src);
assert_eq!(
count_op(&ir.insts, *op),
0,
"{src:?} 应折叠,目标操作码 {op:?} 计数应为 0"
);
let has_neg_zero = ir
.constants
.iter()
.any(|c| matches!(c, Constant::Number(d) if d.to_bits() == neg_zero_bits));
assert!(
has_neg_zero,
"{src:?} 常量池应含折值 Number(-0.0)(符号位置位)"
);
}
}