-
-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathproperty_get.rs
More file actions
1828 lines (1796 loc) · 101 KB
/
Copy pathproperty_get.rs
File metadata and controls
1828 lines (1796 loc) · 101 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! PropertyGet — guarded specializations + general catchall.
//!
//! Extracted from `expr/mod.rs` to keep that file under the 2000-line cap.
//! Pure mechanical move — match arm bodies are verbatim copies, called from
//! `lower_expr`'s outer dispatch.
//!
//! # Rooting (Layer 1, slice 4)
//!
//! Listed in `crate::rooting`'s `MIGRATED_MODULES`, and the listing is
//! **vacuous on the committed source**: this module has never named an
//! `expr::temp_root` symbol, so only the sabotage arm makes the line an
//! assertion. Say what it is rather than banking the count.
//!
//! The audit that earned it. A dotted `obj.k` has exactly ONE user expression
//! to lower — the receiver — and the property name is a compile-time string
//! interned into the pool, not an operand. So the sibling-window shape that
//! `index_get.rs` has (base lowered, then key lowered, then base used) cannot
//! arise: the receiver is lowered LAST and nothing follows it.
//!
//! The three `.call(I64, "js_*")` sites the campaign map counts —
//! `js_error_get_errors`, `js_process_version`, `js_closure_alloc_singleton` —
//! each hand their raw pointer straight to a `nanbox_*_inline` in the same
//! block, with no emission in between. `call_rooted` has no site here: rooting
//! them would add temp-root traffic to close a window that does not exist.
use anyhow::Result;
use perry_hir::types::Type as HirType;
use perry_hir::Expr;
use crate::nanbox::{double_literal, POINTER_MASK_I64};
use crate::native_value::{
BoundsState, BufferAccessMode, LoweredValue, MaterializationReason, NativeRep, SemanticKind,
};
use crate::type_analysis::{
is_array_expr, is_map_expr, is_numeric_typed_array_class, is_set_expr, is_string_expr,
is_url_search_params_expr, is_url_search_params_subclass_expr, receiver_class_name,
receiver_is_error_type,
};
use crate::types::{DOUBLE, I1, I32, I64, I8, PTR};
use super::property_get_names::{
is_headers_method_name, is_http_agent_method_name, is_http_client_request_method_name,
is_net_native_method_value, is_url_pattern_data_property,
};
pub(crate) mod generic_dispatch;
mod globalget;
mod helpers;
#[cfg(test)]
mod tests;
pub(crate) use generic_dispatch::lower_generic_property_get;
pub(crate) use globalget::lower_globalget_property;
pub(crate) use helpers::{
builtin_prototype_method_read, class_has_computed_runtime_members,
is_global_builtin_value_expr, lower_class_method_bind, lower_global_builtin_static_value,
lower_raw_f64_class_field_get_for_number_context, lower_runtime_property_get_by_name,
promise_static_function_length_expr,
};
use super::{
emit_string_literal_global, emit_typed_feedback_register_site, import_origin_suffix,
import_origin_suffix_ns, is_global_this_builtin_name, lower_expr, nanbox_pointer_inline,
nanbox_string_inline, raw_f64_layout_fact, try_lower_pod_field_get, unbox_to_i64, FnCtx,
TypedFeedbackContract, TypedFeedbackKind,
};
pub(crate) fn lower(ctx: &mut FnCtx<'_>, expr: &Expr) -> Result<String> {
// #7219: reading `.buffer` on a tracked typed-array view HANDS OUT ITS
// STORAGE, so the local's inline-storage proof stops holding from here on.
//
// `js_typed_array_backing_buffer` materializes a backing `ArrayBuffer` for
// a typed array that owned its bytes and rebinds the array to alias it —
// element 0 no longer follows the header. The proven-view tiers
// (`proven_view_access`, `buffer_access`, `range_facts`, `i32_fast_path`)
// all read `header + 16 + idx*width` directly, so after
//
// const words = new Uint32Array(1); // storage_inline_proven
// const bytes = new Uint8Array(words.buffer);
// words[0] = 0x01020304; // <- wrote the ORPHANED bytes
//
// the write landed in the pre-materialization storage while `bytes` read
// the buffer, and neither direction aliased: the repro summed 0 instead of
// 10, and writing through `bytes` was equally invisible to `words`.
//
// The runtime side already guards its own inline reader with
// `PERRY_TA_VIEW_GUARD`, which `register_view_meta` bumps. These tiers are
// the compile-time proof that skips that check entirely, so the hazard has
// to be recorded where the alias is created rather than where it is used.
// `MutableAlias` is exactly what this is.
if let Expr::PropertyGet {
object, property, ..
} = expr
{
if property == "buffer" {
if let Expr::LocalGet(id) = object.as_ref() {
if ctx.buffer_view_slots.contains_key(id) {
super::invalidate_buffer_view_pointer(
ctx,
*id,
crate::native_value::MaterializationReason::MutableAlias,
);
}
}
}
}
// `split("literal")[constant].length` on a scalar-replaced split can
// read the precomputed numeric length directly. The split part itself was
// never observable as a string, so materializing a StringHeader would only
// create short-lived garbage.
if let Expr::PropertyGet {
object, property, ..
} = expr
{
if property == "length" {
if let Expr::IndexGet { object, index } = object.as_ref() {
if let (Expr::LocalGet(id), Some(index)) =
(object.as_ref(), crate::collectors::const_index(index))
{
if let Some(slot) = ctx
.scalar_replaced_split_part_lengths
.get(id)
.and_then(|lengths| lengths.get(&index))
.cloned()
{
return Ok(ctx.block().load(DOUBLE, &slot));
}
}
}
}
}
match expr {
Expr::PropertyGet {
object, property, ..
} if matches!(object.as_ref(), Expr::LocalGet(id)
if ctx.pod_records.get(id).is_some_and(|local| local
.layout
.fields
.iter()
.any(|field| field.name == *property))) =>
{
if let Expr::LocalGet(id) = object.as_ref() {
if let Some(value) = try_lower_pod_field_get(ctx, *id, property)? {
return Ok(value);
}
}
unreachable!("POD field guard should imply a lowered field")
}
Expr::PropertyGet {
object, property, ..
} if property == "length"
&& matches!(
object.as_ref(),
Expr::PropertyGet { property: p, .. } if p == "errors"
) =>
{
let recv_box = lower_expr(ctx, object)?;
let blk = ctx.block();
let recv_bits = blk.bitcast_double_to_i64(&recv_box);
let recv_handle = blk.and(I64, &recv_bits, POINTER_MASK_I64);
let len_i32 = blk.safe_load_i32_from_ptr(&recv_handle);
Ok(blk.uitofp(I32, &len_i32, DOUBLE))
}
// Phase H err: `agg.errors` — AggregateError.errors field.
// Routes through js_error_get_errors which pulls the raw
// ArrayHeader pointer from the ErrorHeader struct. Returns a
// NaN-boxed pointer so downstream length / index operations
// see an array.
//
// Gated on a statically-known Error receiver (#6588): the helper's
// `ArrayHeader*` return can't represent a stored `null`, so applying
// it to a function/plain-object `.errors` expando that holds `null`
// produced a bogus pointer sentinel (`f.errors === null` → false,
// `String(f.errors)` → "[object Object]"). Non-error receivers fall
// through to the generic property read below, which returns the
// stored value — including `null` — correctly.
Expr::PropertyGet {
object, property, ..
} if property == "errors" && receiver_is_error_type(ctx, object) => {
let recv_box = lower_expr(ctx, object)?;
let blk = ctx.block();
let recv_handle = unbox_to_i64(blk, &recv_box);
let arr_handle = blk.call(I64, "js_error_get_errors", &[(I64, &recv_handle)]);
Ok(nanbox_pointer_inline(blk, &arr_handle))
}
Expr::PropertyGet {
object, property, ..
} if is_global_builtin_value_expr(object, "Promise")
&& matches!(
property.as_str(),
"resolve"
| "reject"
| "all"
| "race"
| "allSettled"
| "any"
| "withResolvers"
| "try"
) =>
{
Ok(lower_global_builtin_static_value(ctx, "Promise", property))
}
Expr::PropertyGet {
object, property, ..
} if property == "length" && promise_static_function_length_expr(object).is_some() => {
let len = promise_static_function_length_expr(object).unwrap();
Ok(double_literal(len as f64))
}
Expr::PropertyGet {
object, property, ..
} if property == "length"
&& matches!(object.as_ref(), Expr::LocalGet(id)
if ctx.buffer_data_slots.contains_key(id)) =>
{
let arr_id = match object.as_ref() {
Expr::LocalGet(id) => *id,
_ => unreachable!(),
};
let (ptr_slot, _scope) = ctx.buffer_data_slots.get(&arr_id).cloned().unwrap();
// The length field's byte offset relative to `data_ptr` differs by
// header layout: an 8-byte `BufferHeader` keeps it at `data-8`, but
// a 16-byte `TypedArrayHeader` (Int32Array/Float64Array/... numeric
// -length constructors) keeps it at `data-16`. #1862 began
// registering multi-byte typed arrays in `buffer_data_slots` with a
// data_ptr 16 bytes past the header, so the hardcoded `-8` here read
// the packed `kind|elem_size` bytes (Int32→0x404=1028,
// Float64→0x807=2055) instead of `.length`. Prefer the co-registered
// `buffer_view_slots` entry, which carries the correct
// `length_offset_from_data` (and a `length_slot` for native views).
let view = ctx.buffer_view_slots.get(&arr_id).cloned();
let length_slot = view.as_ref().and_then(|v| v.length_slot.clone());
let length_offset = view
.as_ref()
.map(|v| v.length_offset_from_data)
.unwrap_or(-8);
let blk = ctx.block();
let len_i32 = if let Some(length_slot) = length_slot.as_ref() {
blk.load(I32, length_slot)
} else {
let data_ptr = blk.load(PTR, &ptr_slot);
let header_ptr = blk.gep(I8, &data_ptr, &[(I32, &length_offset.to_string())]);
blk.load_invariant(I32, &header_ptr)
};
let lowered = LoweredValue::buffer_len(len_i32);
ctx.record_lowered_value(
"Buffer.length",
Some(arr_id),
"Buffer.length.native_buffer_len",
&lowered,
None,
None,
None,
false,
false,
Vec::new(),
);
Ok(crate::native_value::materialize_js_value(
ctx,
lowered,
MaterializationReason::FunctionAbi,
))
}
// TypedArray `.length` can be shadowed by an own property, so use
// the runtime length helper only when lowering has not already
// registered the receiver as a native Buffer/TypedArray view above.
Expr::PropertyGet {
object, property, ..
} if property == "length"
&& receiver_class_name(ctx, object)
.as_deref()
.is_some_and(is_numeric_typed_array_class) =>
{
let recv_box = lower_expr(ctx, object)?;
Ok(ctx
.block()
.call(DOUBLE, "js_value_length_f64", &[(DOUBLE, &recv_box)]))
}
// `arr.length` / `str.length` — INLINE. Both ArrayHeader and
// StringHeader start with `length: u32` (`crates/perry-runtime/src
// /array.rs` and `string.rs`). Same pattern: unbox pointer, load
// u32 from offset 0, uitofp to double.
// `.length` — INLINE for array, string, and interface-typed
// receivers. Named types (interfaces, class instances) often
// wrap strings or arrays at runtime, where length is at offset 0.
Expr::PropertyGet {
object, property, ..
} if property == "length"
&& (is_array_expr(ctx, object)
|| is_string_expr(ctx, object)
|| match crate::type_analysis::static_type_of(ctx, object) {
// A `Function`-typed receiver is a closure, not a
// String/Array — its `.length` is the spec param
// count, served by the runtime reflection path
// (`closure_length` table). Loading a u32 from
// payload offset 0 here would read 0. Let it fall
// through to the generic property path.
Some(HirType::Named(n)) => n != "Function",
Some(HirType::Tuple(_)) => true,
_ => false,
}) =>
{
// Scalar-replaced array literal: length is a compile-time
// constant — no header to load from (the heap array doesn't
// exist). Must be checked before the cached-length path
// because scalar-replaced arrays aren't registered there.
if let Expr::LocalGet(arr_id) = object.as_ref() {
if let Some(&len) = ctx.non_escaping_arrays.get(arr_id) {
return Ok(double_literal(len as f64));
}
}
// Cached-length fast path: when the surrounding for-loop
// header has hoisted `arr.length` into a stack slot
// (because it spotted `for (...; i < arr.length; ...)` and
// proved the body doesn't change `arr.length`), reuse the
// cached double directly. Without this, the loop body
// would reload `arr.length` from the array header on every
// iteration — LLVM's LICM declines to hoist it because the
// IndexSet's slow path is an opaque external call.
if let Expr::LocalGet(arr_id) = object.as_ref() {
if let Some(slot) = ctx.cached_lengths.get(arr_id).cloned() {
return Ok(ctx.block().load(DOUBLE, &slot));
}
}
// `.length` on a statically-string receiver (`string`-typed local,
// `string[]` element, string-returning expression). #7128: this
// arrived in Phase 3a but keys on `is_string_expr` — the receiver's
// static TYPE — and never on a canonical-`Str` selection, so it is
// on `PERRY_STATIC_STRING_LOWERING`, not on the `Str` knob.
// The receiver bits are freshly
// produced with no safepoint before the header read (no
// forwarding hazard — evacuation rewrites slots/returns before
// the mutator resumes), so the ~18-op generic tower below
// (GC-type byte, forwarding flag, handle-band checks) collapses
// to a 3-arm tag dispatch: SSO → inline length-byte extract
// (`lshr 40; and 0xFF`, matching `js_value_length_f64`'s SSO
// branch), heap STRING_TAG → `load i32` of `utf16_len` at
// offset 0, anything else (annotation lie, nullable-union
// receiver) → the same `js_value_length_f64` slow call the
// generic tower's slow arm uses.
{
if crate::expr::static_string_lowering_enabled()
&& is_string_expr(ctx, object)
&& !is_array_expr(ctx, object)
{
let recv_box = lower_expr(ctx, object)?;
let bits = ctx.block().bitcast_double_to_i64(&recv_box);
let tag = ctx.block().lshr(I64, &bits, "48");
let is_sso =
ctx.block()
.icmp_eq(I64, &tag, crate::nanbox::SHORT_STRING_TAG_TOP16_I64);
let sso_idx = ctx.new_block("strlen.sso");
let chk_idx = ctx.new_block("strlen.chk");
let heap_idx = ctx.new_block("strlen.heap");
let slow_idx = ctx.new_block("strlen.slow");
let merge_idx = ctx.new_block("strlen.merge");
let sso_label = ctx.block_label(sso_idx);
let chk_label = ctx.block_label(chk_idx);
let heap_label = ctx.block_label(heap_idx);
let slow_label = ctx.block_label(slow_idx);
let merge_label = ctx.block_label(merge_idx);
ctx.block().cond_br(&is_sso, &sso_label, &chk_label);
ctx.current_block = sso_idx;
let len_shifted = ctx.block().lshr(I64, &bits, "40");
let len_byte = ctx.block().and(I64, &len_shifted, "255");
let sso_len = ctx.block().uitofp(I64, &len_byte, DOUBLE);
let sso_pred = ctx.block().label.clone();
ctx.block().br(&merge_label);
ctx.current_block = chk_idx;
let is_heap =
ctx.block()
.icmp_eq(I64, &tag, crate::nanbox::STRING_TAG_TOP16_I64);
ctx.block().cond_br(&is_heap, &heap_label, &slow_label);
ctx.current_block = heap_idx;
let handle = ctx.block().and(I64, &bits, POINTER_MASK_I64);
let len_i32 = ctx.block().safe_load_i32_from_ptr(&handle);
let heap_len = ctx.block().uitofp(I32, &len_i32, DOUBLE);
let heap_pred = ctx.block().label.clone();
ctx.block().br(&merge_label);
ctx.current_block = slow_idx;
let slow_len =
ctx.block()
.call(DOUBLE, "js_value_length_f64", &[(DOUBLE, &recv_box)]);
let slow_pred = ctx.block().label.clone();
ctx.block().br(&merge_label);
ctx.current_block = merge_idx;
return Ok(ctx.block().phi(
DOUBLE,
&[
(&sso_len, &sso_pred),
(&heap_len, &heap_pred),
(&slow_len, &slow_pred),
],
));
}
}
// Issue #73: validate the receiver before the inline load.
// The compile-time condition above fires for Array / String /
// Named / Tuple, but TypeScript type erasure (a `Named`-typed
// binding that ends up holding a plain double; an `unknown[]`
// whose static analysis resolves back to `Array` at a caller
// that's actually passing a Buffer/Closure/number) lets
// non-length-bearing receivers flow in. The existing
// `safe_load_i32_from_ptr` only catches `handle < 4096`; a
// denormal double like `0x000000ff_00000000` masks to a
// ~1TB handle that clears the floor and segfaults the
// `ldr s0, [handle]`. Two-step guard:
//
// 1. Handle must be above the macOS __PAGEZERO region
// (4GB). Real mimalloc + arena allocations always
// land above this.
// 2. GC header byte at `handle-8` must indicate
// GC_TYPE_ARRAY (1) or GC_TYPE_STRING (3) — the only
// two layouts with `length: u32` at payload offset 0.
// Buffer / TypedArray don't have GC headers
// (they're `std::alloc`'d) so they route through the
// runtime slow path, which consults the side-table
// registries.
//
// Mirrors the v0.5.82 IC-receiver type-validation fix.
let recv_box = lower_expr(ctx, object)?;
let blk = ctx.block();
let recv_bits = blk.bitcast_double_to_i64(&recv_box);
let recv_handle = blk.and(I64, &recv_bits, POINTER_MASK_I64);
// Tag-based guard: real heap references carry NaN-box tag
// POINTER_TAG (0x7FFD) or STRING_TAG (0x7FFF) in the top
// 16 bits. `AND 0xFFFD` collapses both to 0x7FFD; every
// other NaN-box / plain double / corrupt bit-pattern
// (e.g. a `BufferHeader { length: 0, capacity: 255 }`
// read as u64 → 0x00FF_0000_0000) fails the compare and
// routes through the slow runtime path.
//
// Previously a Darwin mimalloc heap-window check
// (`> 2 TB && < 128 TB`); aarch64-linux-android Scudo
// allocations live below 2 TB, so every real array/string
// was forced through `js_value_length_f64` (issue #128
// follow-up — correctness-safe, but ~10x slower on the
// `.length` hot path). Tag check is platform-independent.
let recv_tag = blk.lshr(I64, &recv_bits, "48");
let recv_tag_masked = blk.and(I64, &recv_tag, "65533"); // 0xFFFD
let tag_ok = blk.icmp_eq(I64, &recv_tag_masked, "32765"); // 0x7FFD
// The tag check alone admits POINTER_TAG-boxed *handle-band*
// values — Web Fetch handles (Headers/Request/Response/Blob, id
// in [0x40000, 0xE0000)), net/http small handles, revocable-proxy
// ids — which are NaN-boxed registry ids, NOT heap pointers. A
// value statically typed Array/String/Named that actually holds
// such a handle at runtime (e.g. a `Response`/`Headers` reaching a
// `.length` site) would then `inttoptr` the bare id and load the
// GC-type byte at `id-8` and the length u32 at `id` — both
// unmapped low addresses → SIGSEGV (observed: doctor / mcp list
// crashing at the exact fetch-handle address). The IC-miss path
// (`js_object_get_field_ic_miss`) and the inline class-field guard
// already gate on `> HANDLE_BAND_TOP`; mirror that here so any
// handle-band receiver routes to the `js_value_length_f64` slow
// path, which classifies it by registry without dereferencing the
// raw id. `HANDLE_BAND_TOP` = 0xFFFFF (addr_class::HANDLE_BAND_MAX
// - 1).
let above_band = blk.icmp_ugt(I64, &recv_handle, "1048575"); // 0xFFFFF
let handle_ok = blk.and(I1, &tag_ok, &above_band);
// SSO receivers fail this guard → route to slow path
// `js_value_length_f64` which has an SSO branch (reads
// length from the tag byte, no heap access). Accepting
// SSO here is safe because the fast path's
// `safe_load_i32_from_ptr(&recv_handle)` would read
// arbitrary bytes at the SSO "pointer" address, but
// the subsequent phi feeds the slow-path result when
// handle_ok is false — so SSO flow is correct via the
// slow path already, no widening needed.
let check_gc_idx = ctx.new_block("plen.check_gc");
let fast_idx = ctx.new_block("plen.fast");
let slow_idx = ctx.new_block("plen.slow");
let merge_idx = ctx.new_block("plen.merge");
let check_gc_label = ctx.block_label(check_gc_idx);
let fast_label = ctx.block_label(fast_idx);
let slow_label = ctx.block_label(slow_idx);
let merge_label = ctx.block_label(merge_idx);
ctx.block()
.cond_br(&handle_ok, &check_gc_label, &slow_label);
ctx.current_block = check_gc_idx;
let gc_type_addr = ctx.block().sub(I64, &recv_handle, "8");
let gc_type_ptr = ctx.block().inttoptr(I64, &gc_type_addr);
let gc_type = ctx.block().load(I8, &gc_type_ptr);
let is_array = ctx.block().icmp_eq(I8, &gc_type, "1"); // GC_TYPE_ARRAY
let is_string = ctx.block().icmp_eq(I8, &gc_type, "3"); // GC_TYPE_STRING
let has_length = ctx.block().or(I1, &is_array, &is_string);
// Issue #233: a FORWARDED array's first 4 bytes are no
// longer length but the lower 32 bits of the forwarding
// pointer. Route those to the slow path
// (`js_value_length_f64`) which recognizes the flag and
// follows the chain. GcHeader layout: byte 0 = obj_type,
// byte 1 = gc_flags. Read the flags byte at handle-7
// (handle-8 is obj_type) and reject if FORWARDED (0x80).
let gc_flags_addr = ctx.block().sub(I64, &recv_handle, "7");
let gc_flags_ptr = ctx.block().inttoptr(I64, &gc_flags_addr);
let gc_flags = ctx.block().load(I8, &gc_flags_ptr);
let fwd_bits = ctx.block().and(I8, &gc_flags, "128"); // GC_FLAG_FORWARDED = 0x80
let not_forwarded = ctx.block().icmp_eq(I8, &fwd_bits, "0");
let take_fast = ctx.block().and(I1, &has_length, ¬_forwarded);
ctx.block().cond_br(&take_fast, &fast_label, &slow_label);
ctx.current_block = fast_idx;
let fast_len_i32 = ctx.block().safe_load_i32_from_ptr(&recv_handle);
let fast_len = ctx.block().uitofp(I32, &fast_len_i32, DOUBLE);
let fast_pred_label = ctx.block().label.clone();
ctx.block().br(&merge_label);
// Runtime slow path: handles Buffer / TypedArray via side-
// table registries, returns 0 for non-length-bearing
// receivers (Closure / BigInt / Promise / Error / plain
// Object) and for non-pointer NaN-boxes.
ctx.current_block = slow_idx;
let slow_len = ctx
.block()
.call(DOUBLE, "js_value_length_f64", &[(DOUBLE, &recv_box)]);
let slow_pred_label = ctx.block().label.clone();
ctx.block().br(&merge_label);
ctx.current_block = merge_idx;
Ok(ctx.block().phi(
DOUBLE,
&[(&fast_len, &fast_pred_label), (&slow_len, &slow_pred_label)],
))
}
// `set.size` / `map.size` — route to runtime helpers. The HIR
// doesn't synthesize SetSize/MapSize expressions for the
// property-access form, so we recognize the pattern here.
Expr::PropertyGet {
object, property, ..
} if property == "size" && is_set_expr(ctx, object) => {
let recv_box = lower_expr(ctx, object)?;
let blk = ctx.block();
let recv_handle = unbox_to_i64(blk, &recv_box);
let i32_v = blk.call(I32, "js_set_size", &[(I64, &recv_handle)]);
Ok(blk.sitofp(I32, &i32_v, DOUBLE))
}
Expr::PropertyGet {
object, property, ..
} if property == "size" && is_map_expr(ctx, object) => {
let recv_box = lower_expr(ctx, object)?;
let blk = ctx.block();
let recv_handle = unbox_to_i64(blk, &recv_box);
let i32_v = blk.call(I32, "js_map_size", &[(I64, &recv_handle)]);
Ok(blk.sitofp(I32, &i32_v, DOUBLE))
}
// Issue #650: `urlSearchParams.size` property — runtime returns
// i32 length of the internal _entries array. Pre-fix the access
// fell through to the generic object-field lookup which returned
// undefined (URLSearchParams stores entries under "_entries", not
// "size"). Routed via `is_url_search_params_expr` so it only
// fires on receivers we can prove are URLSearchParams (immediate
// ctor, typed locals, `url.searchParams` accessor).
Expr::PropertyGet {
object, property, ..
} if property == "size" && is_url_search_params_expr(ctx, object) => {
let recv_box = lower_expr(ctx, object)?;
let blk = ctx.block();
let recv_handle = unbox_to_i64(blk, &recv_box);
let i32_v = blk.call(I32, "js_url_search_params_size", &[(I64, &recv_handle)]);
Ok(blk.sitofp(I32, &i32_v, DOUBLE))
}
// #6710: `class X extends URLSearchParams` instance `.size` — the
// generic object-field lookup returns undefined (the entries live on the
// hidden native backing, not a `size` field). `js_url_search_params_size`
// resolves the backing internally, so pass the subclass instance.
Expr::PropertyGet {
object, property, ..
} if property == "size" && is_url_search_params_subclass_expr(ctx, object) => {
let recv_box = lower_expr(ctx, object)?;
let blk = ctx.block();
let recv_handle = unbox_to_i64(blk, &recv_box);
let i32_v = blk.call(I32, "js_url_search_params_size", &[(I64, &recv_handle)]);
Ok(blk.sitofp(I32, &i32_v, DOUBLE))
}
Expr::PropertyGet {
object,
property,
byte_offset,
} => {
if property == "prototype"
&& matches!(object.as_ref(), Expr::FuncRef(_) | Expr::Closure { .. })
{
let func_value = lower_expr(ctx, object)?;
return Ok(ctx.block().call(
DOUBLE,
"js_function_prototype_value_for_read",
&[(DOUBLE, &func_value)],
));
}
if let Some((builtin_name, method_name)) =
builtin_prototype_method_read(object, property)
{
let builtin_idx = ctx.strings.intern(builtin_name);
let builtin_bytes_global =
format!("@{}", ctx.strings.entry(builtin_idx).bytes_global);
let builtin_len = builtin_name.len().to_string();
let method_idx = ctx.strings.intern(method_name);
let method_bytes_global =
format!("@{}", ctx.strings.entry(method_idx).bytes_global);
let method_len = method_name.len().to_string();
return Ok(ctx.block().call(
DOUBLE,
"js_builtin_prototype_method_value",
&[
(PTR, &builtin_bytes_global),
(I64, &builtin_len),
(PTR, &method_bytes_global),
(I64, &method_len),
],
));
}
// date-fns `constructFrom(date, value)` reads `date.constructor`
// to clone Dates without naming Date directly. Perry stores
// Date as a raw f64 timestamp (no ObjectHeader), so the
// generic `js_object_get_field_by_name_f64` path would treat
// the bit pattern as an invalid pointer and return undefined.
// For statically-Date-typed receivers, short-circuit
// `.constructor` to the global Date constructor closure —
// same value as the bare `Date` identifier resolves to via
// `js_get_global_this_builtin_value`.
if property == "constructor" {
if let Expr::LocalGet(id) = object.as_ref() {
let is_date = matches!(
ctx.local_types.get(id),
Some(HirType::Named(name)) if name == "Date"
);
if is_date {
let name = "Date";
let idx = ctx.strings.intern(name);
let bytes_global = format!("@{}", ctx.strings.entry(idx).bytes_global);
let len_str = name.len().to_string();
return Ok(ctx.block().call(
DOUBLE,
"js_get_global_this_builtin_value",
&[(PTR, &bytes_global), (I64, &len_str)],
));
}
}
}
// Issue #649: PropertyGet on a native-module reference (`fs`,
// `os`, `crypto`, `path`, ...). `NativeModuleRef` lowers to a
// literal `0.0`, so the generic PropertyGet path can't see the
// namespace. Short-circuit to `js_native_module_property_by_name`
// which consults the constants dispatcher directly. For chained
// access like `fs.constants.F_OK` only the inner read fires
// here — `constants` returns a real NATIVE_MODULE_CLASS_ID
// ObjectHeader, and the outer PropertyGet routes through
// `js_object_get_field_by_name`'s NATIVE_MODULE_CLASS_ID arm.
if let Expr::NativeModuleRef(module_name) = object.as_ref() {
// Devirt: register this module's runtime dispatch bucket before
// the namespace value is produced, so later method calls on it
// route to the real handlers. The CJS-`require` shim lowers
// `require("path")` to `PropertyGet { NativeModuleRef("path"),
// "default" }` (NOT a bare NativeModuleRef), so the bare-ref
// install in `static_field_meta` never fired for the
// require-then-`.default.join()` shape (Next.js' `_path.default
// .join(...)` returned undefined — the dispatcher was unregistered
// and `nm_dispatch_lookup` fell to the `None`/undefined arm).
// Emitting it here mirrors the bare-ref path and keeps the
// handlers alive against the auto-optimize dead-strip.
if let Some(install_sym) = crate::nm_install::nm_install_symbol(module_name) {
ctx.block().call_void(install_sym, &[]);
}
// `fs.promises` is backed by the `fs_promises` submodule
// registry, not the parent fs dispatch bucket. Direct
// `node:fs/promises` imports emit their submodule installer at
// the import site, but a parent-property read has no such
// site. Install the precise submodule here before
// `js_native_module_property_by_name` asks the runtime for its
// namespace; otherwise it receives the unresolved empty-object
// stub and destructuring yields `undefined` for every method.
//
// Keeping this in codegen (rather than making the runtime
// parent module unconditionally retain fs/promises) preserves
// auto-optimize dead stripping for programs that only use
// synchronous `node:fs`.
if module_name == "fs" && property == "promises" {
ctx.block()
.call_void("js_node_submod_install_fs_promises", &[]);
}
if module_name == "process" && property == "version" {
let blk = ctx.block();
let handle = blk.call(I64, "js_process_version", &[]);
return Ok(nanbox_string_inline(blk, &handle));
}
let mod_idx = ctx.strings.intern(module_name);
let mod_bytes_global = format!("@{}", ctx.strings.entry(mod_idx).bytes_global);
let mod_len_str = module_name.len().to_string();
let prop_idx = ctx.strings.intern(property);
let prop_bytes_global = format!("@{}", ctx.strings.entry(prop_idx).bytes_global);
let prop_len_str = property.len().to_string();
// The value read of a native-module callable export (`const f =
// util.inherits`) mints a BOUND_METHOD closure that, when invoked
// indirectly, dispatches through the per-module `NM_DISPATCH_REGISTRY`
// populated by `js_nm_install_<module>()`. The *direct* call form
// (`util.inherits(a, b)`) is statically lowered to the runtime extern
// and never touches the registry, so a module reached ONLY via this
// value-read path would leave the registry empty and the indirect call
// would resolve to `undefined` (winston/readable-stream's
// `require('inherits')` → `util.inherits` value → `inherits(Sub, Base)`
// silently skipped, breaking the ES5 super-chain). Emit the install
// here so the value-read path's later dispatch finds the module fn.
if let Some(install_sym) = crate::nm_install::nm_install_symbol(module_name) {
ctx.block().call_void(install_sym, &[]);
}
return Ok(ctx.block().call(
DOUBLE,
"js_native_module_property_by_name",
&[
(PTR, &mod_bytes_global),
(I64, &mod_len_str),
(PTR, &prop_bytes_global),
(I64, &prop_len_str),
],
));
}
// Cross-module static field access. When `Base` is an imported
// class, HIR lowering emits `PropertyGet { ExternFuncRef("Base"),
// property }` instead of `StaticFieldGet` because the lowering
// ctx's `class_statics` registry only sees same-module classes.
// Route through the static-field global map populated from
// `opts.imported_classes` at codegen entry. Refs #420.
if let Expr::ExternFuncRef { name, .. } = object.as_ref() {
let key = (name.clone(), property.clone());
if let Some(global_name) = ctx.static_field_globals.get(&key).cloned() {
let g_ref = format!("@{}", global_name);
return Ok(ctx.block().load(DOUBLE, &g_ref));
}
}
// Issue #618-followup: dynamic property access on a local class
// ref (`SQL.Aliased` after `((SQL2) => { SQL2.Aliased = ...; })(SQL)`).
// Look up CLASS_DYNAMIC_PROPS via the runtime get-by-name fn,
// which now detects INT32-tagged class refs at entry. Pass
// `obj_bits` unmasked so the tag survives.
//
// v0.5.757: also handle `Expr::ExternFuncRef` for IMPORTED classes
// (drizzle's `import { SQL } from "drizzle-orm"`) so
// `SQL.Aliased` reads via the same dynamic-props path. Without
// this, the read fell through to the PIC fast path, which
// discards the INT32 tag during the unbox and ends up returning
// undefined.
let is_class_ref_object = matches!(object.as_ref(), Expr::ClassRef(_))
|| matches!(object.as_ref(), Expr::ExternFuncRef { name, .. } if ctx.class_ids.contains_key(name));
if is_class_ref_object {
let obj_box = lower_expr(ctx, object)?;
let key_idx = ctx.strings.intern(property);
let key_handle_global = format!("@{}", ctx.strings.entry(key_idx).handle_global);
let blk = ctx.block();
let obj_bits = blk.bitcast_double_to_i64(&obj_box);
let key_box = blk.load(DOUBLE, &key_handle_global);
let key_bits = blk.bitcast_double_to_i64(&key_box);
let key_raw = blk.and(I64, &key_bits, POINTER_MASK_I64);
return Ok(blk.call(
DOUBLE,
"js_object_get_field_by_name_f64",
&[(I64, &obj_bits), (I64, &key_raw)],
));
}
// Scalar replacement fast path: if the receiver is a scalar-replaced
// local, load directly from the field's alloca — no heap access.
if let Expr::LocalGet(id) = object.as_ref() {
if let Some(slot) = ctx
.scalar_replaced
.get(id)
.and_then(|fs| fs.get(property.as_str()))
.cloned()
{
let value = ctx.block().load(DOUBLE, &slot);
let declared_raw_f64 = crate::type_analysis::scalar_replaced_field_is_raw_f64(
ctx,
object.as_ref(),
property,
);
let raw_f64_field =
crate::type_analysis::scalar_replaced_field_raw_f64_store_state(
ctx,
Some(*id),
property,
declared_raw_f64,
);
let lowered_js = LoweredValue {
semantic: SemanticKind::JsValue,
rep: NativeRep::JsValue,
llvm_ty: DOUBLE,
value: value.clone(),
};
ctx.record_lowered_value_with_access_mode(
"ScalarObjectFieldGet",
Some(*id),
"scalar_object_field_load",
&lowered_js,
None,
None,
None,
None,
false,
false,
vec![
format!("field={}", property),
format!("raw_f64_field={}", raw_f64_field as u8),
],
);
if raw_f64_field {
let lowered_f64 = LoweredValue::f64(value.clone());
ctx.record_lowered_value_with_access_mode(
"ScalarObjectFieldGet",
Some(*id),
"scalar_object_field_load.raw_f64",
&lowered_f64,
None,
None,
None,
None,
false,
false,
vec![format!("field={}", property), "raw_f64_field=1".to_string()],
);
}
return Ok(value);
}
// Issue #613: when the local is scalar-replaced but the
// property doesn't match any of its known fields, return
// `undefined` directly. The local's `dummy_slot` doesn't
// hold a real ObjectHeader pointer (the heap allocation
// was elided), so falling through to either the
// runtime helper or the PIC fast path would dereference
// garbage and SIGTRAP. This matches JS semantics —
// reading a missing field on a closed-shape object
// literal must produce `undefined`. The check fires
// BEFORE the receiver-class fast path because for an
// any-typed local `const obj: any = { host: "S" }`,
// `local_types[obj]` is overwritten to the synthetic
// `__AnonShape_*` class by `Stmt::Let`'s scalar-
// replacement arm, which would otherwise route the
// missing-field access through `class_field_global_index`
// (None for "port") → method-bind check (None) → the
// generic runtime helper that crashes on the dummy slot.
if ctx.scalar_replaced.contains_key(id) {
return Ok(double_literal(f64::from_bits(crate::nanbox::TAG_UNDEFINED)));
}
// Scalar-replaced array literal: `.length` folds to a
// compile-time constant. No heap access, no runtime call.
if property == "length" {
if let Some(&len) = ctx.non_escaping_arrays.get(id) {
return Ok(double_literal(len as f64));
}
}
}
// Also handle `this` during scalar-replaced ctor inlining
if let Expr::This = object.as_ref() {
if let Some(target_id) = ctx.scalar_ctor_target.last().copied() {
let slot = ctx
.scalar_replaced
.get(&target_id)
.and_then(|fs| fs.get(property.as_str()).cloned());
if let Some(slot) = slot {
let value = ctx.block().load(DOUBLE, &slot);
let declared_raw_f64 =
crate::type_analysis::scalar_replaced_field_is_raw_f64(
ctx,
object.as_ref(),
property,
);
let raw_f64_field =
crate::type_analysis::scalar_replaced_field_raw_f64_store_state(
ctx,
Some(target_id),
property,
declared_raw_f64,
);
let lowered_js = LoweredValue {
semantic: SemanticKind::JsValue,
rep: NativeRep::JsValue,
llvm_ty: DOUBLE,
value: value.clone(),
};
ctx.record_lowered_value_with_access_mode(
"ScalarThisFieldGet",
Some(target_id),
"scalar_object_field_load",
&lowered_js,
None,
None,
None,
None,
false,
false,
vec![
format!("field={}", property),
format!("raw_f64_field={}", raw_f64_field as u8),
],
);
if raw_f64_field {
let lowered_f64 = LoweredValue::f64(value.clone());
ctx.record_lowered_value_with_access_mode(
"ScalarThisFieldGet",
Some(target_id),
"scalar_object_field_load.raw_f64",
&lowered_f64,
None,
None,
None,
None,
false,
false,
vec![format!("field={}", property), "raw_f64_field=1".to_string()],
);
}
return Ok(value);
}
return Ok(double_literal(f64::from_bits(crate::nanbox::TAG_UNDEFINED)));
}
}
// GlobalGet receivers (`console.X`, `Math.PI`, `JSON.parse`,
// `process.env`, …) used as expression VALUES (not in a
// call) — there's no real value to materialize for most
// shapes; the call dispatch in lower_call handles the same
// receivers correctly when they're invoked. The HIR uses
// `Expr::GlobalGet(0)` as a sentinel for ALL builtin
// globals (see lower.rs:5037), so the original receiver
// name is no longer recoverable here — codegen has to
// route by the property string alone.
//
// Special-case `console.log` (the canonical pattern from
// #236): return a runtime-allocated singleton closure that
// thunks into `js_console_log_dynamic` so
// `.then(console.log)` actually prints. Caveat: this also
// catches the rare `let f = Math.log; f(x)` shape and
// dispatches through console.log's thunk — but that
// pattern previously lowered to the `0.0` sentinel
// (silently broken either way) so this is not a regression
// for the only realistic alternative caller. The full fix
// would side-channel the original global name through
// lowering; deferred until a second-callable-builtin
// arrives. Other unrecognized property shapes fall through
// to the `undefined` sentinel (a spec-correct property miss).
if matches!(object.as_ref(), Expr::GlobalGet(_)) {
return lower_globalget_property(ctx, property);
}
// Namespace-import member access: `import * as O from './oids';
// O.OID_INT2`. The HIR lowers `O` itself to `ExternFuncRef { name:
// "O" }` but `O` isn't a real exported value — it's the namespace
// binding, so there's no `perry_fn_<src>__O` getter to call. The
// CLI driver already registers every export of the source module
// into `import_function_prefixes` under its own name (compile.rs's
// namespace-import walk), so `O.OID_INT2` just needs to resolve
// `property` ("OID_INT2") through that map directly and call the
// same getter a `{ OID_INT2 } from './oids'` named import would
// have used. Without this, the PropertyGet falls through to the
// generic path below which lowers the ExternFuncRef "O" to
// `TAG_TRUE` (the sentinel for unresolved imports) and hands that
// to `js_object_get_field_by_name_f64` — every namespaced lookup
// silently returns `undefined`, which is the second half of GH #32
// (the registry duplication bug was the first).
if let Expr::ExternFuncRef { name, .. } = object.as_ref() {
if ctx.namespace_imports.contains(name) {
// #7189: `B.deep` where the imported module says
// `export * as deep from "./m.ts"`. The member's value is
// another module's namespace OBJECT, so there is no
// `perry_fn_<mod>__deep` symbol to call — every arm below
// resolves to a symbol, and this member does not have one.
//
// The object it should produce is the one
// `@__perry_ns_<prefix>` already holds, built by the same
// populator a dynamic `import()` of that module would use.
// Reusing it means nested re-exports (a namespace whose own
// exports include another `export * as`) come out right
// without a second implementation, because the populator
// already recurses.
//
// First, ahead of the class and member-prefix arms: a
// namespace alias can collide with a class or function name
// exported elsewhere, and the alias is what the source said.
if ctx
.namespace_member_nested
.contains(&(name.clone(), property.to_string()))
{
if let Some(prefix) = ctx
.namespace_member_prefixes
.get(&(name.clone(), property.to_string()))
.cloned()
{
return Ok(crate::expr::dyn_extern_i18n::namespace_value_for_prefix(
ctx, &prefix,
));
}
}