Skip to content

Commit 375d00a

Browse files
authored
fix(codegen): stop typing a symbol-keyed element read as a number (#7796) (#7810)
Reading a[Symbol.iterator] off a number[] is a property read on the array object and answers with a function, but both element-type inference sites took the array's element type without ever looking at the index. The local was then recorded as a number, and a value believed numeric is tested for truthiness with a floating-point compare against zero — which is false for every NaN-boxed pointer, so if (f) took the false branch on a function. Both sites now require the index to be provably numeric.
1 parent 2304290 commit 375d00a

4 files changed

Lines changed: 204 additions & 12 deletions

File tree

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
Fixed a wrong branch on a symbol-keyed property read.
2+
3+
Reading a symbol-keyed property off an array gave a value that every other
4+
test agreed was a function — `typeof` said `"function"`, `Boolean()` said
5+
`true`, `=== undefined` said `false` — but that an `if` treated as falsy:
6+
7+
```ts
8+
const a = [1];
9+
const f = (a as any)[Symbol.iterator];
10+
if (f) { /* never ran */ }
11+
```
12+
13+
The inline form `if ((a as any)[Symbol.iterator])` was correct; only storing
14+
the value in a local first went wrong, which is what made it look so strange.
15+
16+
The compiler types an element read of a `number[]` as a number, and it was
17+
doing that no matter what the index was. `a[Symbol.iterator]` is not an
18+
element read at all — it reads a property of the array object, and the answer
19+
is a function. So the local holding it was recorded as a number.
20+
21+
That mistake is expensive rather than merely imprecise. A value believed to be
22+
a number is tested for truthiness with a floating-point comparison against
23+
zero, and Perry stores objects, strings and functions as NaN-boxed doubles —
24+
which really are NaN. Every comparison against a NaN is false, so the test
25+
reported "falsy" for every function, object and string that reached it.
26+
27+
Both places that infer an element type now require the index to be a number
28+
first. Requiring proof rather than just the absence of contrary evidence is
29+
deliberate: an index the compiler cannot type may hold anything at runtime,
30+
and the cost of answering "not a number" is one missed fast path, while the
31+
cost of answering "number" is a branch that goes the wrong way.
32+
33+
Ordinary numeric indexing is untouched — `a[i]` in a loop keeps the same
34+
inline comparison it had before, which a companion test pins down.
35+
36+
Closes #7796.

‎crates/perry-codegen/src/type_analysis/numeric.rs‎

Lines changed: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -358,15 +358,6 @@ pub(crate) fn is_numeric_expr(ctx: &FnCtx<'_>, e: &Expr) -> bool {
358358
// load in `js_number_coerce` which blocks LLVM's vectorizer
359359
// and adds a function call per iteration.
360360
Expr::IndexGet { object, index } => {
361-
if receiver_class_name(ctx, object)
362-
.as_deref()
363-
.is_some_and(is_numeric_typed_array_class)
364-
{
365-
return true;
366-
}
367-
let Expr::LocalGet(arr_id) = object.as_ref() else {
368-
return false;
369-
};
370361
// #6750 follow-up: a masked-index read covered by an ACTIVE
371362
// masked-window fact (dense range-loop / straight-line-region
372363
// fast copy) is a guard-proven numeric element load, even when
@@ -375,10 +366,41 @@ pub(crate) fn is_numeric_expr(ctx: &FnCtx<'_>, e: &Expr) -> bool {
375366
// routed through the BigInt-aware dynamic helpers. Facts are
376367
// scope-managed by the versioned lowerings, so the answer is
377368
// only `true` while a fast copy that proved the window is being
378-
// lowered.
379-
if crate::expr::masked_window_fact_for_index(ctx, *arr_id, index).is_some() {
369+
// lowered. The fact itself proves the index is an integer, so it
370+
// stands ahead of the index check below.
371+
if let Expr::LocalGet(arr_id) = object.as_ref() {
372+
if crate::expr::masked_window_fact_for_index(ctx, *arr_id, index).is_some() {
373+
return true;
374+
}
375+
}
376+
// #7796: an element type only describes reads at a NUMERIC index.
377+
// `a[sym]` on a `number[]` is not an element read at all — it is a
378+
// property read on the array OBJECT, and `a[Symbol.iterator]`
379+
// answers with a function.
380+
//
381+
// Getting this wrong is not merely a missed optimization. The
382+
// caller acts on "this is a number" by testing the raw double with
383+
// `fcmp one %v, 0.0`, and every NaN-boxed pointer IS a NaN, so that
384+
// comparison is false for every object, string and function alive.
385+
// `if (a[Symbol.iterator])` therefore took the FALSE branch on a
386+
// value that `Boolean()` and `typeof` both agreed was a function.
387+
//
388+
// Proof is required rather than merely the absence of counter-
389+
// evidence: an index we cannot type may hold anything at runtime,
390+
// and answering `false` here costs a fast path while answering
391+
// `true` costs a wrong branch.
392+
if !is_numeric_expr(ctx, index) {
393+
return false;
394+
}
395+
if receiver_class_name(ctx, object)
396+
.as_deref()
397+
.is_some_and(is_numeric_typed_array_class)
398+
{
380399
return true;
381400
}
401+
let Expr::LocalGet(arr_id) = object.as_ref() else {
402+
return false;
403+
};
382404
match ctx.local_types.get(arr_id) {
383405
Some(HirType::Array(elem)) => {
384406
matches!(**elem, HirType::Number | HirType::Int32)

‎crates/perry-codegen/src/type_analysis/numeric/tests.rs‎

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,3 +544,125 @@ fn only_number_returning_string_methods_are_claimed_numeric() {
544544
);
545545
}
546546
}
547+
548+
/// #7796 — an element read at a NON-numeric index is not a numeric read.
549+
///
550+
/// `a[Symbol.iterator]` on a `number[]` is a property read on the array
551+
/// object, and it answers with a function. Typing the local that holds it as
552+
/// `number` made the truthiness test lower to `fcmp one %v, 0.0` — and every
553+
/// NaN-boxed pointer IS a NaN, so that comparison is false for every function,
554+
/// object and string alive. `if (f)` took the false branch on a value that
555+
/// `typeof` called a function and `Boolean()` called true.
556+
mod symbol_keyed_element_reads {
557+
use super::*;
558+
559+
/// Slice out the probe function so an assertion cannot be satisfied by
560+
/// some unrelated part of the module.
561+
fn probe_body(ir: &str) -> String {
562+
let start = ir
563+
.find("__probe(")
564+
.map(|i| ir[..i].rfind("define").expect("define before probe"))
565+
.expect("probe function must be emitted");
566+
let end = ir[start..].find("\n}").expect("probe must terminate") + start;
567+
ir[start..end].to_string()
568+
}
569+
570+
fn array_of_numbers(id: u32) -> Stmt {
571+
Stmt::Let {
572+
id,
573+
name: "a".to_string(),
574+
ty: Type::Array(Box::new(Type::Number)),
575+
mutable: false,
576+
init: Some(Expr::Array(vec![Expr::Integer(1)])),
577+
}
578+
}
579+
580+
fn truthy_return(local: u32) -> Stmt {
581+
Stmt::Return(Some(Expr::Conditional {
582+
condition: Box::new(Expr::LocalGet(local)),
583+
then_expr: Box::new(Expr::Integer(1)),
584+
else_expr: Box::new(Expr::Integer(0)),
585+
}))
586+
}
587+
588+
#[test]
589+
fn a_symbol_indexed_element_is_tested_with_js_is_truthy() {
590+
// const a: number[] = [1];
591+
// const sym = Symbol.iterator;
592+
// const f = a[sym];
593+
// return f ? 1 : 0;
594+
let ir = emitted_ir(probe_module(
595+
"symbol_keyed_element_read.ts",
596+
Vec::new(),
597+
vec![
598+
array_of_numbers(1),
599+
Stmt::Let {
600+
id: 2,
601+
name: "sym".to_string(),
602+
ty: Type::Any,
603+
mutable: false,
604+
init: Some(Expr::SymbolFor(Box::new(Expr::String(
605+
"@@__perry_wk_iterator".to_string(),
606+
)))),
607+
},
608+
Stmt::Let {
609+
id: 3,
610+
name: "f".to_string(),
611+
ty: Type::Any,
612+
mutable: false,
613+
init: Some(Expr::IndexGet {
614+
object: Box::new(Expr::LocalGet(1)),
615+
index: Box::new(Expr::LocalGet(2)),
616+
}),
617+
},
618+
truthy_return(3),
619+
],
620+
));
621+
let body = probe_body(&ir);
622+
assert!(
623+
body.contains("js_is_truthy"),
624+
"a symbol-keyed read must go through the general truthiness \
625+
helper, or a NaN-boxed function reads as false:\n{body}"
626+
);
627+
assert!(
628+
!body.contains("fcmp one"),
629+
"the numeric fast path must not fire for a non-numeric index:\n{body}"
630+
);
631+
}
632+
633+
#[test]
634+
fn a_numeric_index_keeps_the_inline_fast_path() {
635+
// The guard against over-correcting: requiring a numeric index must
636+
// not cost the ordinary `a[i]` element read its inline comparison.
637+
let ir = emitted_ir(probe_module(
638+
"numeric_element_read.ts",
639+
Vec::new(),
640+
vec![
641+
array_of_numbers(1),
642+
Stmt::Let {
643+
id: 2,
644+
name: "i".to_string(),
645+
ty: Type::Number,
646+
mutable: false,
647+
init: Some(Expr::Integer(0)),
648+
},
649+
Stmt::Let {
650+
id: 3,
651+
name: "v".to_string(),
652+
ty: Type::Any,
653+
mutable: false,
654+
init: Some(Expr::IndexGet {
655+
object: Box::new(Expr::LocalGet(1)),
656+
index: Box::new(Expr::LocalGet(2)),
657+
}),
658+
},
659+
truthy_return(3),
660+
],
661+
));
662+
let body = probe_body(&ir);
663+
assert!(
664+
body.contains("fcmp one"),
665+
"a numeric index must keep the inline truthiness comparison:\n{body}"
666+
);
667+
}
668+
}

‎crates/perry-codegen/src/type_analysis/refine.rs‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,11 +336,23 @@ pub(crate) fn refine_type_from_init(ctx: &FnCtx<'_>, init: &Expr) -> Option<HirT
336336
None
337337
}
338338
}
339-
Expr::IndexGet { object, .. } => {
339+
Expr::IndexGet { object, index } => {
340340
// arr[i] where arr is Array<T> → element type T.
341341
// Handles both LocalGet(arr) and PropertyGet(this, "field")
342342
// — the latter lets `this.parts[i]` get the right type
343343
// when `parts: string[]`.
344+
//
345+
// #7796: only at a NUMERIC index. `a[Symbol.iterator]` on a
346+
// `number[]` reads a property of the array OBJECT and answers with
347+
// a function, so typing the local as `number` is simply false — and
348+
// it is a costly kind of false, because a local believed numeric is
349+
// tested for truthiness with `fcmp one %v, 0.0`. Every NaN-boxed
350+
// pointer is a NaN, so that comparison says false for every
351+
// function, object and string, and `if (f)` took the wrong branch
352+
// on a value `typeof` and `Boolean()` both called a function.
353+
if !is_numeric_expr(ctx, index) {
354+
return None;
355+
}
344356
if let Expr::LocalGet(arr_id) = object.as_ref() {
345357
if let Some(HirType::Array(elem_ty)) = ctx.local_types.get(arr_id) {
346358
return Some((**elem_ty).clone());

0 commit comments

Comments
 (0)