hermes-sema 0.1.2

A Rust port of the Hermes semantic analysis (scope resolution and validation) pass by Tzvetan Mikov, the architect of Hermes. Not an official Meta project.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

//! S1 T5: declarations — hoisting, validation, blocks. A second `impl<'bt,
//! 'sc, 'sm, 'ad> SemanticResolver<'bt, 'sc, 'sm, 'ad>` block, split out of
//! `resolver/mod.rs` the same way `identifiers.rs` was (S1 T4) — see that
//! file's module doc for why a child module sees `mod.rs`'s private fields.
//!
//! Ports `SemanticResolver::extractIdentsFromDecl` (SemanticResolver.cpp:
//! 2276-2366), `extractDeclaredIdentsFromID` (cpp:2383-2435),
//! `processDeclarations` (cpp:2125-2157, replacing `mod.rs`'s S0 guard in
//! `process_collected_declarations`), `validateAndDeclareIdentifier`
//! (cpp:2437-2669), `validateDeclarationName` (cpp:2671-2707),
//! `visit(VariableDeclarationNode *)` (cpp:325-403) and
//! `visit(BlockStatementNode *, Node *)` (cpp:502-518).
//!
//! ## What's dormant
//!
//! - **`typed_`** is always `false` in this port. Typed mode is the
//!   **FlowChecker component**, which is out of Sema's scope entirely — not
//!   a later Sema phase (parent spec §1 "Out of scope", §6 "Not a Sema
//!   phase"); see `resolver/mod.rs`'s module doc. The `processDeclarations`
//!   builtin-skip branch `typed_` guards (cpp:2138-2151) additionally needs
//!   `hasBuiltinDirective`/`hasBuiltinDecoration` (cpp:2846-2866), whose
//!   only caller is that branch and which therefore belong to the same
//!   component — so rather than fabricate stand-ins for methods another
//!   component owns, the branch is ported as a `const TYPED: bool = false`
//!   guard around an `unreachable!`, matching the `DEBUG_INFO_SETTING_ALL`
//!   precedent in `mod.rs`. (An earlier revision called both of these "S2
//!   scope"/"unported S2 helpers"; S2 is long done and shipped neither, and
//!   never could have — the capstone review corrected the tags.)
//! - **`promotedFuncDecls`** (`FunctionContext::promoted_func_decls`) was
//!   always empty until S3 T1, which lands `ScopedFunctionPromoter`
//!   (`resolver/promoter.rs`) and the `processPromotedFuncDecls` that fills
//!   the map (`resolver/mod.rs`). Every branch that reads it here — the
//!   `Var, ScopedFunc` and `ES5Catch, ScopedFunc` redeclaration rows and the
//!   two-declarations-per-promoted-function block below — is live as of
//!   that task; `tests/sema_corpus/promotion-basic.js` and
//!   `promotion-blocked-by-let.js` exercise them end to end, on top of the
//!   hand-populated-map unit tests that covered them while the producer was
//!   still missing.
//! - **`ClassDeclaration`/`CatchClause`/`ImportDeclaration`** classification
//!   in `extract_idents_from_decl`/`extract_declared_idents_from_id` was
//!   ported in full before any of the three had a `visit_node` (`mod.rs`)
//!   dispatch arm, and was unit-tested directly (see the `tests` module
//!   below) by calling `extract_idents_from_decl` on a hand-built node,
//!   bypassing the full visitor walk. All three are dispatched and
//!   corpus-pinned now: classes since S1 T8+
//!   (`tests/sema_corpus/classes-shapes.js`), catch clauses likewise
//!   (`catch-block.js`), and `ImportDeclaration` since S4a T3's
//!   `resolver/modules.rs` — pinned by
//!   `tests/sema_corpus_parser/module-imports.js`, since only the
//!   `compile = false` tool pair can dump an import (the module-mode error
//!   is ungated, and `hermesc` never dumps after a `resolveAST` failure).
//!   The direct unit tests are kept: they still pin the classification in
//!   isolation from the walk.

use hermes_ast::context::{GCLock, NodeRc};
use hermes_ast::node::{builder, Node, NodeField};
use hermes_ast::visitor::TransformResult;
use hermes_support::diag::Subsystem;
use hermes_support::manager::SourceErrorManager;

use crate::ids::{DeclId, ScopeId};
use crate::sem_context::{Atom, Binding, DeclKind};

use super::SemanticResolver;

/// Port of the `typed_` member (SemanticResolver.h:84) as seen from
/// `processDeclarations` — always `false` in this port. See the module doc.
const TYPED: bool = false;

/// The text of `atom`, for error/warning messages. Same pattern as
/// `identifiers.rs`'s inline `String::from_utf8_lossy(gc.bytes(a))`, pulled
/// out here since this file needs it at several call sites.
pub(super) fn atom_str(gc: &GCLock, atom: Atom) -> String {
    String::from_utf8_lossy(gc.bytes(atom)).into_owned()
}

/// The body of `SemanticResolver::extractDeclaredIdentsFromID`
/// (SemanticResolver.cpp:2383-2435), as a free function over the only piece
/// of the resolver it touches. See the forwarding method of the same name
/// below for why it lives out here.
pub(super) fn extract_declared_idents_from_id<'gc>(
    sm: &mut SourceErrorManager,
    node: Option<&'gc Node<'gc>>,
    idents: &mut Vec<&'gc Node<'gc>>,
) -> bool {
    // The identifier is sometimes optional, in which case it is valid.
    let node = match node {
        Some(n) => n,
        None => return false,
    };

    if let Node::Identifier(_) = node {
        idents.push(node);
        return false;
    }

    if let Node::Empty(_) = node {
        return false;
    }

    if let Node::AssignmentPattern(ap) = node {
        extract_declared_idents_from_id(sm, Some(ap.left), idents);
        return true;
    }

    if let Node::ArrayPattern(arr) = node {
        let mut contains_expr = false;
        for elem in arr.elements.iter() {
            contains_expr |=
                extract_declared_idents_from_id(sm, Some(elem), idents);
        }
        return contains_expr;
    }

    if let Node::RestElement(re) = node {
        return extract_declared_idents_from_id(sm, Some(re.argument), idents);
    }

    if let Node::ObjectPattern(obj) = node {
        let mut contains_expr = false;
        for prop_node in obj.properties.iter() {
            match prop_node {
                Node::Property(p) => {
                    contains_expr |= extract_declared_idents_from_id(
                        sm,
                        Some(p.value),
                        idents,
                    );
                }
                Node::RestElement(re) => {
                    contains_expr |= extract_declared_idents_from_id(
                        sm,
                        Some(re.argument),
                        idents,
                    );
                }
                _ => panic!(
                    "cast<RestElementNode> failed: unexpected \
                     ObjectPattern property kind {}",
                    prop_node.node_type_str()
                ),
            }
        }
        return contains_expr;
    }

    if let Node::ComponentParameter(param) = node {
        return extract_declared_idents_from_id(sm, Some(param.local), idents);
    }

    sm.error_range(node.range(), "invalid destructuring target");
    false
}

impl<'bt, 'sc, 'sm, 'ad> SemanticResolver<'bt, 'sc, 'sm, 'ad> {
    // ---- Scope-shape helpers -----------------------------------------

    /// \return the function-body scope of the function owning `scope`. Port
    /// of the repeated `scope->parentFunction->getFunctionBodyScope()`
    /// idiom (cpp:354, 377, 2463).
    fn function_body_scope_of(&self, scope: ScopeId) -> ScopeId {
        let parent_function = self.sem_ctx.scope(scope).parent_function;
        self.sem_ctx
            .function(parent_function)
            .get_function_body_scope()
    }

    /// \return true if the current scope IS the current function's own
    /// body scope (as opposed to some scope nested inside it). Port of the
    /// repeated `curScope_ == curScope_->parentFunction->
    /// getFunctionBodyScope()` / `curScope_ == curFunctionInfo()->
    /// getFunctionBodyScope()` idiom (cpp:287, 353-354, 2463).
    fn cur_scope_is_function_body_scope(&self) -> bool {
        let cur = self.cur_scope.expect("no active scope");
        cur == self.function_body_scope_of(cur)
    }

    /// \p decl must be non-null (always true here: every `Decl` this port
    /// creates carries a real `scope`, so `.expect` never fires in
    /// practice — see the module doc on `Decl::scope`'s C++ nullability).
    /// \return whether the specified declaration is in the current
    /// function. Port of `declInCurFunction` (SemanticResolver.h:509-512).
    fn decl_in_cur_function(&self, decl: DeclId) -> bool {
        let scope = self
            .sem_ctx
            .decl(decl)
            .scope
            .expect("declInCurFunction requires a scoped decl");
        self.sem_ctx.scope(scope).parent_function == self.cur_function_info()
    }

    // ---- extractIdentsFromDecl / extractDeclaredIdentsFromID ----------

    /// Port of `SemanticResolver::extractIdentsFromDecl`
    /// (SemanticResolver.cpp:2292-2382). Appends every declared
    /// `Identifier` node reachable from `node`'s binding pattern(s) to
    /// `idents` and returns the `Decl::Kind` `node` as a whole should be
    /// declared with.
    ///
    /// The `ClassDeclaration`/`CatchClause`/`ImportDeclaration` arms are
    /// reached through `visit_node`'s dispatch and corpus-pinned, as well as
    /// unit-tested directly — see the module doc.
    pub(super) fn extract_idents_from_decl<'gc>(
        &mut self,
        node: &'gc Node<'gc>,
        idents: &mut Vec<&'gc Node<'gc>>,
    ) -> DeclKind {
        match node {
            Node::VariableDeclaration(vd) => {
                for decl in vd.declarations.iter() {
                    let vdecl = decl.as_variable_declarator().expect(
                        "VariableDeclaration child must be a \
                         VariableDeclarator",
                    );
                    self.extract_declared_idents_from_id(
                        Some(vdecl.id),
                        idents,
                    );
                }
                let kind_atom = vd.kind.get();
                if kind_atom == self.kw().ident_var {
                    if self.in_global_scope_context() {
                        DeclKind::GlobalProperty
                    } else {
                        DeclKind::Var
                    }
                } else if kind_atom == self.kw().ident_let {
                    DeclKind::Let
                } else {
                    DeclKind::Const
                }
            }

            Node::FunctionDeclaration(fd) => {
                self.extract_declared_idents_from_id(fd.id, idents);
                if self.cur_scope_is_function_body_scope() {
                    // It is possible to still have ScopedFunctions in the
                    // global function, for example if we have
                    // ```
                    // let foo;
                    // {
                    //   function foo() {}
                    // }
                    // ```
                    // then `foo` won't be promoted to functionScope of the
                    // global function.
                    //
                    // However, if `funcDecl` has been promoted to the
                    // functionScope of the global function, it should be
                    // declared as a GlobalProperty, just like `var` would
                    // be.
                    //
                    // See ScopedFunctionPromoter for rules on when function
                    // declarations are promoted out of the child scoped in
                    // which they are declared.
                    //
                    // If the FunctionDeclaration is not at global scope but
                    // it is a top-level declaration within a function, it's
                    // handled as Var. See ES10.0 13.2.7 for how scoped
                    // function declarations are treated specially in
                    // top-level.
                    if self.in_global_scope_context() {
                        DeclKind::GlobalProperty
                    } else {
                        DeclKind::Var
                    }
                } else {
                    DeclKind::ScopedFunction
                }
            }

            Node::ClassDeclaration(cd) => {
                self.extract_declared_idents_from_id(cd.id, idents);
                DeclKind::Class
            }

            Node::CatchClause(cc) => {
                self.extract_declared_idents_from_id(cc.param, idents);
                if matches!(cc.param, Some(Node::Identifier(_))) {
                    // For compatibility with ES5, we need to treat a single
                    // catch variable specially, see:
                    // B.3.5 VariableStatements in Catch Blocks
                    // https://www.ecma-international.org/ecma-262/10.0/index.html#sec-variablestatements-in-catch-blocks
                    DeclKind::ES5Catch
                } else {
                    DeclKind::Catch
                }
            }

            Node::ImportDeclaration(import_decl) => {
                for spec in import_decl.specifiers.iter() {
                    match spec {
                        Node::ImportSpecifier(s) => {
                            self.extract_declared_idents_from_id(
                                Some(s.local),
                                idents,
                            );
                        }
                        Node::ImportDefaultSpecifier(s) => {
                            self.extract_declared_idents_from_id(
                                Some(s.local),
                                idents,
                            );
                        }
                        Node::ImportNamespaceSpecifier(s) => {
                            self.extract_declared_idents_from_id(
                                Some(s.local),
                                idents,
                            );
                        }
                        _ => {}
                    }
                }
                DeclKind::Import
            }

            _ => {
                self.sm
                    .error_range(node.range(), "unsuppported declaration kind");
                DeclKind::Var
            }
        }
    }

    /// Port of `SemanticResolver::extractDeclaredIdentsFromID`
    /// (SemanticResolver.cpp:2383-2435). Appends every `Identifier` in the
    /// binding pattern `node` to `idents`. \return whether `node` contains
    /// an expression that isn't purely a binding pattern (an
    /// `AssignmentPattern`'s default value) — the "invalid destructuring
    /// target" error case returns `false`, matching the C++'s implicit
    /// fallthrough.
    ///
    /// The body lives in the free function of the same name below, which
    /// takes only the `&mut SourceErrorManager` this code actually needs.
    /// S3 T1's `ScopedFunctionPromoter` (`promoter.rs`) calls it while
    /// holding a shared borrow of the resolver's `DeclCollector`, which a
    /// `&mut self` receiver would forbid — see that module's doc. Same code,
    /// one place, two borrow shapes.
    pub(super) fn extract_declared_idents_from_id<'gc>(
        &mut self,
        node: Option<&'gc Node<'gc>>,
        idents: &mut Vec<&'gc Node<'gc>>,
    ) -> bool {
        extract_declared_idents_from_id(self.sm, node, idents)
    }

    // ---- processCollectedDeclarations / processDeclarations -----------

    /// Port of `SemanticResolver::processDeclarations`
    /// (SemanticResolver.cpp:2125-2157).
    ///
    /// Takes an owned slice rather than borrowing straight from the
    /// `DeclCollector` (whose `ScopeDecls` lives behind
    /// `self.function_context()`): every declaration below needs `&mut
    /// self`, which a live borrow of `self.function_context()` would
    /// forbid. See `process_collected_declarations` (`mod.rs`), the sole
    /// caller, which clones the `NodeRc`s (cheap refcount bumps) up front
    /// for exactly this reason.
    pub(super) fn process_declarations(
        &mut self,
        gc: &GCLock,
        decls: &[NodeRc],
    ) {
        for decl_rc in decls {
            let decl_node = decl_rc.node(gc);

            // TypeAlias/TSTypeAliasDeclaration are type-only declarations;
            // they don't participate in value binding. Port of the `#if
            // HERMES_PARSE_FLOW`/`#if HERMES_PARSE_TS`-guarded `continue`s
            // (cpp:2127-2134) — this port's single node set always
            // includes both dialects (see the crate doc), so both checks
            // apply unconditionally.
            if matches!(
                decl_node,
                Node::TypeAlias(_) | Node::TSTypeAliasDeclaration(_)
            ) {
                continue;
            }

            let mut idents: Vec<&Node> = Vec::new();
            let kind = self.extract_idents_from_decl(decl_node, &mut idents);

            // In typed mode, ignore function declarations marked as
            // builtin (either via the "builtin" directive or a
            // Hermes.builtin decoration). They're going to be resolved by
            // the FlowChecker. `TYPED` is always `false` in this port —
            // see the module doc for why this is stubbed rather than
            // transcribed.
            if TYPED {
                unreachable!(
                    "typed-mode builtin-function skip is S2 scope \
                     (cpp:2138-2151)"
                );
            }

            for ident in idents {
                self.validate_and_declare_identifier(gc, kind, ident);
            }
        }
    }

    // ---- validateAndDeclareIdentifier ----------------------------------

    /// Port of `SemanticResolver::validateAndDeclareIdentifier`
    /// (SemanticResolver.cpp:2437-2669).
    pub(super) fn validate_and_declare_identifier<'gc>(
        &mut self,
        gc: &'gc GCLock,
        kind: DeclKind,
        ident_node: &'gc Node<'gc>,
    ) {
        let identifier = ident_node
            .as_identifier()
            .expect("validate_and_declare_identifier: not an Identifier");

        if !self.validate_declaration_name(gc, kind, ident_node) {
            return;
        }

        let mut prev_name: Option<Binding> =
            self.binding_table.lookup(&identifier.name.get());

        // IMPORTANT: this is not spec compliant!
        // For now, treat "var" declarations of "arguments" simply as a new
        // variable instead of as an alias for the Arguments object. It is
        // simpler and makes a difference only in the following obscure
        // case:
        // - non-strict mode
        // - "var arguments" without an initializer.
        // I am willing to live with this sacrifice.
        // Aliasing of "arguments" becomes especially iffy when type
        // annotations are added.
        //
        // C++ spells the guard `if ((false))` (cpp:2454-2461) — doubled
        // parentheses marking the constant as deliberate. It was briefly an
        // `#if 0` for a Windows clang17 `-Wunreachable-code` warning, backed
        // out in `8f9e357fd`; dead in every spelling, and this mirror's
        // nesting matches it exactly.
        #[allow(clippy::overly_complex_bool_expr, clippy::needless_bool)]
        if false {
            // Redeclaration of `arguments` in non-strict mode is allowed at
            // the function level, so we don't need to declare a new
            // variable.
            if !self.sem_ctx.function(self.cur_function_info()).strict
                && identifier.name.get() == self.kw().ident_arguments
                && kind == DeclKind::Var
            {
                return;
            }
        }

        // Ignore declarations in enclosing functions.
        if let Some(pn) = &prev_name {
            if !self.decl_in_cur_function(pn.decl) {
                prev_name = None;
            }
        }

        let mut decl: Option<DeclId> = None;

        // Whether to reuse the decl (above) for a new binding when it's not
        // `None`.
        let mut reuse_decl_for_new_binding = false;

        // Handle re-declarations, ignoring ambient properties.
        if let Some(pn) = &prev_name {
            if self.sem_ctx.decl(pn.decl).kind
                != DeclKind::UndeclaredGlobalProperty
            {
                let prev_kind = self.sem_ctx.decl(pn.decl).kind;
                let cur_scope = self.cur_scope.expect("no active scope");
                let same_scope =
                    self.sem_ctx.decl(pn.decl).scope == Some(cur_scope);
                let top_level = self.cur_scope_is_function_body_scope();
                let prev_in_prev_scope = self.sem_ctx.decl(pn.decl).scope
                    == self.sem_ctx.scope(cur_scope).parent_scope;

                // Check whether the redeclaration is invalid.
                // Note that since "var" declarations have been hoisted to
                // the function scope, we cannot catch cases where "var"
                // follows something declared in a surrounding lexical
                // scope. See visit(VariableDeclarationNode *) for when
                // those are handled.
                //
                // The two rules in the spec ES10.0 (e.g. B.3.3.4) are:
                // * LexicallyDeclaredNames (in the same scope) can't
                //   conflict.
                // * LexicallyDeclaredNames can't conflict with
                //   VarDeclarationNames in their own scope or any of their
                //   child scopes (recursively).
                //
                // Parameter names must also not conflict with lexically
                // scoped names in the top-level of the function
                // (ES10.0 14.1.2):
                // * It is a Syntax Error if any element of the BoundNames
                //   of FormalParameters also occurs in the
                //   LexicallyDeclaredNames of FunctionBody.
                //
                // Catch (non-ES5) clause variables must not conflict with
                // the lexically scoped names or var-declared names in
                // their block:
                // * It is a Syntax Error if BoundNames of CatchParameter
                //   contains any duplicate elements.
                // * It is a Syntax Error if any element of the BoundNames
                //   of CatchParameter also occurs in the
                //   LexicallyDeclaredNames of Block.
                //   NOTE: It's possible that a function in the body of the
                //   catch has been promoted to a Var at function scope, so
                //   it has to be accounted for.
                // * It is a Syntax Error if any element of the BoundNames
                //   of CatchParameter also occurs in the VarDeclaredNames
                //   of Block unless CatchParameter is CatchParameter :
                //   BindingIdentifier.
                //   visit(VariableDeclarationNode *) will handle this final
                //   case.
                //
                // Case by case explanations for our representation:
                //
                // ES5Catch, var
                //          -> valid, special case ES10 B.3.5, but we can't
                //             catch it here. See
                //             visit(VariableDeclarationNode *)
                // var, var
                //          -> always valid
                // scopedFunction, var
                //          -> can't happen because var is at top-level only
                // var, scopedFunction
                //          -> valid because scopedFunction is not at
                //             top-level
                // scopedFunction, scopedFunction
                //          -> strict mode: valid if not in the same scope
                //             loose mode: always valid
                //             See ES10.0 13.2.7
                //             scoped function declarations are treated
                //             specially if they're at the top-level of the
                //             function/script/module.
                //             'var' case is handled in
                //             visit(VariableDeclarationNode *).
                // let, var
                //          -> always invalid
                // let, scopedFunction
                //          -> invalid if same scope
                // var|scopedFunction|let, let
                //          -> invalid if the same scope
                // parameter, let
                //          -> invalid if let is top-level

                assert!(
                    !(prev_kind == DeclKind::ScopedFunction
                        && kind == DeclKind::Var),
                    "invalid state, scopedFunctions are not at top-level"
                );

                if (prev_kind.is_let_like() && kind.is_var_like())
                    || (prev_kind.is_var_like()
                        && kind.is_let_like()
                        && same_scope)
                    || (prev_kind.is_let_like()
                        && kind.is_let_like()
                        && same_scope
                        // ES10.0 B.3.3.4
                        // Annex B exception: non-strict mode ScopedFunctions
                        // are OK.
                        && !(!self
                            .sem_ctx
                            .function(self.cur_function_info())
                            .strict
                            && prev_kind == DeclKind::ScopedFunction
                            && kind == DeclKind::ScopedFunction))
                    || (prev_kind == DeclKind::Parameter
                        && kind.is_let_like()
                        && top_level)
                    // LexicallyDeclaredNames of CatchBlock are only in the
                    // block scope itself, so check prevInPrevScope (it's
                    // like checking topLevel for parameters).
                    // This is an error regardless of if it's an ES5 or ES6
                    // catch.
                    || ((prev_kind == DeclKind::Catch
                        || prev_kind == DeclKind::ES5Catch)
                        && kind.is_let_like()
                        && prev_in_prev_scope)
                {
                    self.sm.error_range(
                        ident_node.range(),
                        format!(
                            "Identifier '{}' is already declared",
                            atom_str(gc, identifier.name.get())
                        ),
                    );
                    if let Some(prev_ident) = &pn.ident {
                        self.sm.note_range(
                            prev_ident.node(gc).range(),
                            "previous declaration",
                            Subsystem::Unspecified,
                        );
                    }
                    return;
                }

                // When to create a new declaration?
                //
                // Var, Var -> use prev
                if prev_kind.is_var_like() && kind.is_var_like() {
                    decl = Some(pn.decl);
                }
                // Var, ScopedFunc -> if non-param non-strict or same scope,
                //                    then use prev, else declare new
                else if prev_kind.is_var_like()
                    && kind == DeclKind::ScopedFunction
                {
                    decl = None;
                    if same_scope {
                        decl = Some(pn.decl);
                    } else if let Some(&d) = self
                        .function_context()
                        .promoted_func_decls
                        .get(&identifier.name.get())
                    {
                        // We've already promoted this function, so add a
                        // new binding and point it to the original Decl.
                        reuse_decl_for_new_binding = true;
                        decl = Some(d);
                    }
                }
                // ES5Catch, ScopedFunc ->
                //   if promoted, use promoted function, else declare new
                //   ES5Catch doesn't prevent promotion, so we have to check
                //   it specially.
                else if prev_kind == DeclKind::ES5Catch
                    && kind == DeclKind::ScopedFunction
                {
                    if let Some(&d) = self
                        .function_context()
                        .promoted_func_decls
                        .get(&identifier.name.get())
                    {
                        reuse_decl_for_new_binding = true;
                        decl = Some(d);
                    } else {
                        decl = None;
                    }
                }
                // ScopedFunc, ScopedFunc same scope -> error
                // ScopedFunc, ScopedFunc new scope -> declare new
                else if prev_kind == DeclKind::ScopedFunction
                    && kind == DeclKind::ScopedFunction
                {
                    decl = None;
                }
            }
        }

        // Special case: this is a lexically-scoped declaration in global
        // scope which is a restricted global.
        // ES14.0 16.1.7 GlobalDeclarationInstantiation
        // For each element name of lexNames, do
        //  a. If env.HasVarDeclaration(name) is true,
        //    throw a SyntaxError exception.
        //  b. If env.HasLexicalDeclaration(name) is true,
        //    throw a SyntaxError exception.
        //  c. Let hasRestrictedGlobal be ?
        //    env.HasRestrictedGlobalProperty(name).
        //  d. If hasRestrictedGlobal is true,
        //    throw a SyntaxError exception.
        //  (a-b) are handled by the checks above, so just do (c-d) here.
        if self.cur_scope == Some(self.sem_ctx.get_global_scope())
            && kind.is_let_like()
            && self.is_restricted_global_property(identifier.name.get())
        {
            self.sm.error_range(
                ident_node.range(),
                format!(
                    "Can't create duplicate variable that shadows a global \
                     property: '{}'",
                    atom_str(gc, identifier.name.get())
                ),
            );
        }

        // A promoted function involves two declarations: one for the
        // global scope and one for the block scope. This statement handles
        // the scenario where an identifier already has an associated
        // declaration and focuses on creating the promoted declaration
        // instead.
        //  1. A block-scoped declaration is created and linked with the
        //     identifier.
        //  2. The binding table is updated to associate the identifier
        //     name with the correct declaration. It is necessary to use
        //     `put` instead of `try_emplace` as there could be multiple
        //     identifiers with the same name, requiring replacement of the
        //     previous binding.
        if self.sem_ctx.get_declaration_decl(identifier).is_some()
            && self
                .function_context()
                .promoted_func_decls
                .contains_key(&identifier.name.get())
        {
            let cur_scope = self.cur_scope.expect("no active scope");
            let new_decl = self.sem_ctx.new_decl_in_scope_default(
                identifier.name.get(),
                kind,
                cur_scope,
            );
            self.binding_table.put(
                identifier.name.get(),
                Binding::new(new_decl, Some(NodeRc::from_node(gc, ident_node))),
            );
            self.sem_ctx
                .set_promoted_decl(ident_node.node_id(), new_decl);
            return;
        }

        // Create new decl.
        if let Some(d) = decl {
            if reuse_decl_for_new_binding {
                self.binding_table.try_emplace(
                    identifier.name.get(),
                    Binding::new(d, Some(NodeRc::from_node(gc, ident_node))),
                );
            }
        } else {
            let new_decl = if kind.is_global() {
                self.sem_ctx.new_global(identifier.name.get(), kind)
            } else {
                let cur_scope = self.cur_scope.expect("no active scope");
                self.sem_ctx.new_decl_in_scope_default(
                    identifier.name.get(),
                    kind,
                    cur_scope,
                )
            };
            self.binding_table.try_emplace(
                identifier.name.get(),
                Binding::new(new_decl, Some(NodeRc::from_node(gc, ident_node))),
            );
            decl = Some(new_decl);
        }

        self.sem_ctx.set_declaration_decl(
            ident_node.node_id(),
            identifier,
            decl,
        );
    }

    /// Port of `SemanticResolver::validateDeclarationName`
    /// (SemanticResolver.cpp:2671-2707).
    pub(super) fn validate_declaration_name(
        &mut self,
        gc: &GCLock,
        decl_kind: DeclKind,
        id_node: &Node,
    ) -> bool {
        let identifier = id_node
            .as_identifier()
            .expect("validate_declaration_name: not an Identifier");

        if self.sem_ctx.function(self.cur_function_info()).strict {
            // - 'arguments' cannot be redeclared in strict mode.
            // - 'eval' cannot be redeclared in strict mode.
            if identifier.name.get() == self.kw().ident_arguments
                || identifier.name.get() == self.kw().ident_eval
            {
                self.sm.error_range(
                    id_node.range(),
                    format!(
                        "cannot declare '{}' in strict mode",
                        atom_str(gc, identifier.name.get())
                    ),
                );
                return false;
            }

            // Parameter cannot be named "let".
            if decl_kind == DeclKind::Parameter
                && identifier.name.get() == self.kw().ident_let
            {
                self.sm.error_range(
                    id_node.range(),
                    "invalid parameter name 'let' in strict mode",
                );
                return false;
            }
        }

        if (decl_kind == DeclKind::Let || decl_kind == DeclKind::Const)
            && identifier.name.get() == self.kw().ident_let
        {
            // ES9.0 13.3.1.1
            // LexicalDeclaration : LetOrConst BindingList
            // It is a Syntax Error if the BoundNames of BindingList
            // contains "let".
            self.sm.error_range(
                id_node.range(),
                "'let' is disallowed as a lexically bound name",
            );
            return false;
        }

        true
    }

    // ---- visit(VariableDeclarationNode *) ------------------------------

    /// Port of `SemanticResolver::visit(ESTree::VariableDeclarationNode
    /// *node)` (SemanticResolver.cpp:325-403).
    pub(super) fn visit_variable_declaration<'gc>(
        &mut self,
        gc: &'gc GCLock,
        node: &'gc Node<'gc>,
    ) -> TransformResult<&'gc Node<'gc>> {
        let vd = match node {
            Node::VariableDeclaration(vd) => vd,
            _ => unreachable!(
                "visit_variable_declaration: not a VariableDeclaration"
            ),
        };

        if self.compile()
            && (vd.kind.get() == self.kw().ident_using
                || vd.kind.get() == self.kw().ident_await_using)
        {
            // 'using' declarations are not supported in compiled code.
            self.sm.error_range(
                node.range(),
                "using declarations are not yet supported",
            );
            return TransformResult::Unchanged;
        }

        let result = node.visit_children_mut(gc, self);

        // ES5Catch, var
        //          -> valid, special case ES10 B.3.5
        // let, var
        //          -> always invalid
        // Ordinarily, we check this in validateAndDeclareIdentifier, but if
        // the declarations are in a nested scope like x or y here:
        //
        // function f() {
        //   { let x; var x; }
        //   { let y; { var y; } }
        // }
        //
        // then the var has been hoisted to the function-level scope by
        // DeclCollector and we aren't able to detect that both
        // declarations are actually in the same scope and conflict.
        // Only perform this check for nested scopes, because the var will
        // have been hoisted into a different scope.
        if vd.kind.get() == self.kw().ident_var
            && !self.cur_scope_is_function_body_scope()
        {
            let mut idents: Vec<&Node> = Vec::new();
            self.extract_idents_from_decl(node, &mut idents);
            // Check every identifier declared as a 'var'.
            for ident_node in idents {
                let identifier = ident_node.as_identifier().expect(
                    "extract_idents_from_decl only ever pushes Identifiers",
                );
                let name = identifier.name.get();
                let Some((prev_binding, prev_depth)) =
                    self.binding_table.find_with_depth(&name)
                else {
                    // No existing declaration, move on.
                    continue;
                };

                // Whether the prevName is the lexical binding for a
                // promoted function which reuses the same Decl.
                // If it is a lexical binding of a promoted function,
                // that's an error due to a lexically-scoped and
                // var-scoped naming conflict.
                let prev_is_lexical_binding_of_promoted_func = self
                    .function_context()
                    .promoted_func_decls
                    .contains_key(&name)
                    && prev_depth
                        != self.function_context().binding_table_scope_depth;

                let prev_scope = self
                    .sem_ctx
                    .decl(prev_binding.decl)
                    .scope
                    .expect("decl must be scoped");

                if prev_scope == self.function_body_scope_of(prev_scope)
                    && !prev_is_lexical_binding_of_promoted_func
                {
                    // If the previous declaration is in the function
                    // scope, the error would have been reported when
                    // validating declarations in the function scope.
                    continue;
                }

                // Report an error if the var is trying to override a
                // let-like declaration.
                //
                // ES10.0 B.3.4: ES5Catch (only used for simple binding
                // ident in catch block) is not an error if it conflicts
                // with VarDeclaredNames in its body.
                let prev_kind = self.sem_ctx.decl(prev_binding.decl).kind;
                if (prev_kind.is_let_like() && prev_kind != DeclKind::ES5Catch)
                    || prev_is_lexical_binding_of_promoted_func
                {
                    self.sm.error_range(
                        ident_node.range(),
                        format!(
                            "Identifier '{}' is already declared",
                            atom_str(gc, name)
                        ),
                    );
                    if let Some(prev_ident) = &prev_binding.ident {
                        self.sm.note_range(
                            prev_ident.node(gc).range(),
                            "previous declaration",
                            Subsystem::Unspecified,
                        );
                    }
                }
            }
        }

        result
    }

    // ---- visit(BlockStatementNode *, Node *) ---------------------------

    /// Port of `SemanticResolver::visit(ESTree::BlockStatementNode *node,
    /// ESTree::Node *parent)` (SemanticResolver.cpp:502-518).
    pub(super) fn visit_block_statement<'gc>(
        &mut self,
        gc: &'gc GCLock,
        node: &'gc Node<'gc>,
        path: Option<hermes_ast::visitor::Path<'gc>>,
    ) -> TransformResult<&'gc Node<'gc>> {
        // Some nodes with attached BlockStatement have already dealt with
        // the scope.
        if let Some(p) = path {
            if matches!(
                p.parent,
                Node::FunctionDeclaration(_)
                    | Node::FunctionExpression(_)
                    | Node::ArrowFunctionExpression(_)
            ) {
                return node.visit_children_mut(gc, self);
            }
        }

        let scope_state = self.enter_scope(Some(node), false);
        self.process_collected_declarations(gc, node);
        let result = node.visit_children_mut(gc, self);
        self.exit_scope(scope_state);
        result
    }

    // ---- visit(ObjectPatternNode *) / visit(ArrayPatternNode *) ---------

    /// Port of `SemanticResolver::visit(ESTree::ObjectPatternNode *node,
    /// ESTree::Node *parent)` (SemanticResolver.h:209-211), an inline
    /// one-liner in the header:
    ///
    /// ```text
    /// void visit(ESTree::ObjectPatternNode *node, ESTree::Node *parent) {
    ///   visitESTreeNodeList(*this, node->_properties, node);
    /// }
    /// ```
    ///
    /// The point of the override is what it does NOT do: `ObjectPattern` has
    /// two children in the AST — `properties` and `typeAnnotation`
    /// (ESTree.def:646-650) — and this visits only the first, so sema never
    /// descends into the Flow/TS type annotation of an annotated
    /// destructuring pattern (`var {a}: Obj = ...`,
    /// `function g({a}: Obj) {}`). The generic children walk WOULD descend
    /// into it, which is exactly the divergence the whole-Sema capstone
    /// review found (finding F1): under untyped `-parse-flow` those shapes
    /// are reachable and hermesc resolves them, while this port panicked at
    /// `mod.rs`'s catch-all. Pinned by `sema_corpus/flow-pattern-annot.js`.
    ///
    /// Note that C++ takes (and ignores) a `parent` — this port's dispatcher
    /// only passes a `Path` to the visits that read it, so it is omitted.
    pub(super) fn visit_object_pattern<'gc>(
        &mut self,
        gc: &'gc GCLock,
        node: &'gc Node<'gc>,
    ) -> TransformResult<&'gc Node<'gc>> {
        let n = node
            .as_object_pattern()
            .expect("visit_object_pattern: not an ObjectPattern");
        let mut b = builder::ObjectPattern::from_node(n);
        if let Some(properties) =
            self.visit_node_list(gc, n.properties, node, NodeField::properties)
        {
            b.properties(properties);
        }
        b.build(gc)
    }

    /// Port of `SemanticResolver::visit(ESTree::ArrayPatternNode *node,
    /// ESTree::Node *parent)` (SemanticResolver.h:212-214) — the same
    /// header one-liner for `_elements`, and the same skip of
    /// `typeAnnotation` (ESTree.def:652-656). See
    /// [`Self::visit_object_pattern`] for the full argument.
    pub(super) fn visit_array_pattern<'gc>(
        &mut self,
        gc: &'gc GCLock,
        node: &'gc Node<'gc>,
    ) -> TransformResult<&'gc Node<'gc>> {
        let n = node
            .as_array_pattern()
            .expect("visit_array_pattern: not an ArrayPattern");
        let mut b = builder::ArrayPattern::from_node(n);
        if let Some(elements) =
            self.visit_node_list(gc, n.elements, node, NodeField::elements)
        {
            b.elements(elements);
        }
        b.build(gc)
    }
}

#[cfg(test)]
mod tests {
    use hermes_ast::context::Context;
    use hermes_ast::node::{
        Identifier, NumericLiteral, VariableDeclaration, VariableDeclarator,
    };
    use hermes_ast::node_child::NodeList;
    use hermes_ast::node_child::NodeMetadata;
    use hermes_parser::js::JSParserImpl;
    use hermes_parser::lexer::{GrammarContext, JSLexer};
    use hermes_support::location::{SMLoc, SMRange};
    use hermes_support::manager::SourceErrorManager;
    use hermes_support::persistent_scoped_map::Scope;

    use super::*;
    use crate::keywords::Keywords;
    use crate::resolver::FunctionContext;
    use crate::sem_context::{
        ConstructorKind, CustomDirectives, FuncIsArrow, SemContext,
    };

    /// Parse `src` as a `Program` and return its root node, panicking on any
    /// parse error. Mirrors `tests/resolver.rs`'s `parse` helper.
    fn parse<'gc>(
        gc: &'gc GCLock,
        sm: &mut SourceErrorManager,
        src: &str,
    ) -> &'gc Node<'gc> {
        let buf_id = sm.add_buffer_bytes("input", src.as_bytes());
        let result: Option<&Node> = {
            let atoms = &gc.ctx().atom_table;
            let lexer =
                JSLexer::new(buf_id, sm, atoms, GrammarContext::AllowRegExp);
            let mut parser = JSParserImpl::new(gc, lexer);
            parser.parse()
        };
        assert_eq!(sm.error_count(), 0, "unexpected parse errors in: {src}");
        result.expect("parser returned no Program")
    }

    /// \return the first top-level statement of a parsed `Program`.
    fn first_statement<'gc>(program_node: &'gc Node<'gc>) -> &'gc Node<'gc> {
        match program_node {
            Node::Program(p) => p.body.iter().next().expect("empty program"),
            _ => unreachable!("first_statement: not a Program"),
        }
    }

    /// Allocate an `Identifier` node named `name` at `loc`. Same shape as
    /// `identifiers.rs`'s private helper of the same name (not reusable
    /// across the sibling test modules, so duplicated here).
    fn alloc_identifier<'gc>(
        gc: &'gc GCLock,
        name: &str,
        loc: SMLoc,
    ) -> &'gc Node<'gc> {
        let atom = gc.atom_bytes(name);
        gc.alloc(Node::Identifier(Identifier::new(
            NodeMetadata::new(SMRange {
                start: loc,
                end: loc,
            }),
            atom,
            None,
            false,
        )))
    }

    /// Allocate a `var <name>;` `VariableDeclaration` node whose single
    /// declarator's `id` is `ident_node` (no initializer).
    fn alloc_var_decl<'gc>(
        gc: &'gc GCLock,
        kw_var: Atom,
        ident_node: &'gc Node<'gc>,
        range: SMRange,
    ) -> &'gc Node<'gc> {
        let declarator = gc.alloc(Node::VariableDeclarator(
            VariableDeclarator::new(NodeMetadata::new(range), None, ident_node),
        ));
        gc.alloc(Node::VariableDeclaration(VariableDeclaration::new(
            NodeMetadata::new(range),
            kw_var,
            NodeList::from_iter(gc, [declarator]),
        )))
    }

    // ==== extractIdentsFromDecl classification (cpp:2292-2382) =========
    //
    // `FunctionDeclaration`/`ClassDeclaration`/`CatchClause`/
    // `ImportDeclaration` all have `visit_node` dispatch arms and corpus
    // pins today (see the module doc); these tests still exercise the
    // classification in isolation, by calling `extract_idents_from_decl`
    // directly on a hand-parsed node and bypassing that dispatch entirely.

    /// A `FunctionDeclaration` at the top level of the (installed-as-global)
    /// function is a `GlobalProperty`, exactly like `var` would be.
    #[test]
    fn function_declaration_at_global_top_level_is_global_property() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let root = parse(&gc, &mut sm, "function f() {}\n");
        let func_decl = first_statement(root);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let binding_table = sem_ctx.binding_table_rc();
        let mut resolver = SemanticResolver::new(
            &binding_table,
            &mut sem_ctx,
            &mut sm,
            &[],
            true,
        );
        // `root` (a `Program`) stands in for the function-like node
        // `enter_function` decorates — see `identifiers.rs`'s
        // `resolve_identifier_typeof_creates_ambient_global_without_warning`
        // for the same placeholder trick.
        let func_state = resolver.enter_function(
            &gc,
            root,
            None,
            false,
            ConstructorKind::None,
            CustomDirectives::default(),
            /* install_as_global_context */ true,
        );
        let scope_state =
            resolver.enter_scope(None, /* functionScope */ true);

        let mut idents: Vec<&Node> = Vec::new();
        let kind = resolver.extract_idents_from_decl(func_decl, &mut idents);
        assert_eq!(kind, DeclKind::GlobalProperty);
        assert_eq!(idents.len(), 1);
        assert!(matches!(idents[0], Node::Identifier(_)));

        resolver.exit_scope(scope_state);
        resolver.exit_function(func_state);
    }

    /// The same top-level shape, but the enclosing function is NOT the
    /// global context: a `FunctionDeclaration` there is a `Var`.
    #[test]
    fn function_declaration_at_non_global_top_level_is_var() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let root = parse(&gc, &mut sm, "function f() {}\n");
        let func_decl = first_statement(root);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let binding_table = sem_ctx.binding_table_rc();
        let mut resolver = SemanticResolver::new(
            &binding_table,
            &mut sem_ctx,
            &mut sm,
            &[],
            true,
        );
        let func_state = resolver.enter_function(
            &gc,
            root,
            None,
            false,
            ConstructorKind::None,
            CustomDirectives::default(),
            /* install_as_global_context */ false,
        );
        let scope_state = resolver.enter_scope(None, true);

        let mut idents: Vec<&Node> = Vec::new();
        let kind = resolver.extract_idents_from_decl(func_decl, &mut idents);
        assert_eq!(kind, DeclKind::Var);

        resolver.exit_scope(scope_state);
        resolver.exit_function(func_state);
    }

    /// A `FunctionDeclaration` NOT at the top level of its function (i.e.
    /// nested one scope deeper) is a `ScopedFunction`, regardless of
    /// whether the function is the global one.
    #[test]
    fn function_declaration_in_nested_scope_is_scoped_function() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let root = parse(&gc, &mut sm, "function f() {}\n");
        let func_decl = first_statement(root);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let binding_table = sem_ctx.binding_table_rc();
        let mut resolver = SemanticResolver::new(
            &binding_table,
            &mut sem_ctx,
            &mut sm,
            &[],
            true,
        );
        let func_state = resolver.enter_function(
            &gc,
            root,
            None,
            false,
            ConstructorKind::None,
            CustomDirectives::default(),
            true,
        );
        let body_scope_state = resolver.enter_scope(None, true);
        let block_scope_state = resolver.enter_scope(None, false);

        let mut idents: Vec<&Node> = Vec::new();
        let kind = resolver.extract_idents_from_decl(func_decl, &mut idents);
        assert_eq!(kind, DeclKind::ScopedFunction);

        resolver.exit_scope(block_scope_state);
        resolver.exit_scope(body_scope_state);
        resolver.exit_function(func_state);
    }

    /// `ClassDeclaration` classification doesn't consult scope at all, so
    /// no function/scope setup is needed — a bare resolver suffices.
    #[test]
    fn class_declaration_is_class() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let root = parse(&gc, &mut sm, "class C {}\n");
        let class_decl = first_statement(root);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let binding_table = sem_ctx.binding_table_rc();
        let mut resolver = SemanticResolver::new(
            &binding_table,
            &mut sem_ctx,
            &mut sm,
            &[],
            true,
        );

        let mut idents: Vec<&Node> = Vec::new();
        let kind = resolver.extract_idents_from_decl(class_decl, &mut idents);
        assert_eq!(kind, DeclKind::Class);
        assert_eq!(idents.len(), 1);
    }

    /// A single-`Identifier` catch parameter (`catch (e)`) is the special
    /// `ES5Catch` kind (ES10 B.3.5).
    #[test]
    fn catch_with_identifier_param_is_es5catch() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let root = parse(&gc, &mut sm, "try {} catch (e) {}\n");
        let try_stmt = first_statement(root);
        let handler = match try_stmt {
            Node::TryStatement(t) => t.handler.expect("try has a handler"),
            _ => unreachable!(),
        };

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let binding_table = sem_ctx.binding_table_rc();
        let mut resolver = SemanticResolver::new(
            &binding_table,
            &mut sem_ctx,
            &mut sm,
            &[],
            true,
        );

        let mut idents: Vec<&Node> = Vec::new();
        let kind = resolver.extract_idents_from_decl(handler, &mut idents);
        assert_eq!(kind, DeclKind::ES5Catch);
        assert_eq!(idents.len(), 1);
    }

    /// A destructuring catch parameter (`catch ({a, b})`) is the plain
    /// `Catch` kind — the ES5Catch special-case only applies to a bare
    /// identifier.
    #[test]
    fn catch_with_destructuring_param_is_catch() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let root = parse(&gc, &mut sm, "try {} catch ({a, b}) {}\n");
        let try_stmt = first_statement(root);
        let handler = match try_stmt {
            Node::TryStatement(t) => t.handler.expect("try has a handler"),
            _ => unreachable!(),
        };

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let binding_table = sem_ctx.binding_table_rc();
        let mut resolver = SemanticResolver::new(
            &binding_table,
            &mut sem_ctx,
            &mut sm,
            &[],
            true,
        );

        let mut idents: Vec<&Node> = Vec::new();
        let kind = resolver.extract_idents_from_decl(handler, &mut idents);
        assert_eq!(kind, DeclKind::Catch);
        assert_eq!(idents.len(), 2);
    }

    /// A parameterless catch (`catch {}`, ES2019 optional catch binding) is
    /// also plain `Catch` — `cc.param` is `None`, so the `dyn_cast_or_null`
    /// in the C++ is `nullptr`, which is NOT an `IdentifierNode`.
    #[test]
    fn catch_with_no_param_is_catch() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let root = parse(&gc, &mut sm, "try {} catch {}\n");
        let try_stmt = first_statement(root);
        let handler = match try_stmt {
            Node::TryStatement(t) => t.handler.expect("try has a handler"),
            _ => unreachable!(),
        };

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let binding_table = sem_ctx.binding_table_rc();
        let mut resolver = SemanticResolver::new(
            &binding_table,
            &mut sem_ctx,
            &mut sm,
            &[],
            true,
        );

        let mut idents: Vec<&Node> = Vec::new();
        let kind = resolver.extract_idents_from_decl(handler, &mut idents);
        assert_eq!(kind, DeclKind::Catch);
        assert_eq!(idents.len(), 0);
    }

    /// `ImportDeclaration` collects the `local` identifier of every
    /// specifier kind (`ImportSpecifier`/`ImportDefaultSpecifier`/
    /// `ImportNamespaceSpecifier`) and is always the `Import` kind.
    /// (Module-mode validation — `visit(ImportDeclarationNode *)`,
    /// cpp:874-891 — is a separate, unported code path; calling
    /// `extract_idents_from_decl` directly bypasses it entirely, same as
    /// the other dormant classifications above.)
    #[test]
    fn import_declaration_collects_default_and_named_locals() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let root = parse(&gc, &mut sm, "import def, {a, b as c} from \"m\";\n");
        let import_decl = first_statement(root);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let binding_table = sem_ctx.binding_table_rc();
        let mut resolver = SemanticResolver::new(
            &binding_table,
            &mut sem_ctx,
            &mut sm,
            &[],
            true,
        );

        let mut idents: Vec<&Node> = Vec::new();
        let kind = resolver.extract_idents_from_decl(import_decl, &mut idents);
        assert_eq!(kind, DeclKind::Import);
        let names: Vec<String> = idents
            .iter()
            .map(|n| {
                let id = n.as_identifier().unwrap();
                String::from_utf8_lossy(gc.bytes(id.name.get())).into_owned()
            })
            .collect();
        // `def` (the default specifier's local), `a` (the shorthand
        // specifier's local — `import {a}` means imported name "a", local
        // name "a", a full `ImportSpecifier` in its own right), then `c`
        // (`b as c`'s local, NOT the imported name `b`).
        assert_eq!(names, vec!["def", "a", "c"]);
    }

    /// A namespace import (`import * as ns from "m"`) collects `ns`.
    #[test]
    fn import_declaration_collects_namespace_local() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let root = parse(&gc, &mut sm, "import * as ns from \"m\";\n");
        let import_decl = first_statement(root);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let binding_table = sem_ctx.binding_table_rc();
        let mut resolver = SemanticResolver::new(
            &binding_table,
            &mut sem_ctx,
            &mut sm,
            &[],
            true,
        );

        let mut idents: Vec<&Node> = Vec::new();
        let kind = resolver.extract_idents_from_decl(import_decl, &mut idents);
        assert_eq!(kind, DeclKind::Import);
        assert_eq!(idents.len(), 1);
        let id = idents[0].as_identifier().unwrap();
        assert_eq!(String::from_utf8_lossy(gc.bytes(id.name.get())), "ns");
    }

    /// A node that isn't one of the five recognized declaration kinds
    /// reports "unsuppported declaration kind" (verbatim C++ typo,
    /// cpp:2379) and returns the dummy `Decl::Kind::Var`.
    #[test]
    fn unsupported_declaration_kind_reports_error() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let buf = sm.add_buffer_bytes("d.js", b"1");
        let loc = SMLoc {
            source: buf,
            offset: 0,
        };
        let range = SMRange {
            start: loc,
            end: loc,
        };
        let node = gc.alloc(Node::NumericLiteral(NumericLiteral::new(
            NodeMetadata::new(range),
            1.0,
        )));

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let binding_table = sem_ctx.binding_table_rc();
        {
            let mut resolver = SemanticResolver::new(
                &binding_table,
                &mut sem_ctx,
                &mut sm,
                &[],
                true,
            );

            let mut idents: Vec<&Node> = Vec::new();
            let kind = resolver.extract_idents_from_decl(node, &mut idents);
            assert_eq!(kind, DeclKind::Var);
            assert!(idents.is_empty());
        }
        assert_eq!(sm.error_count(), 1);
    }

    // ==== extractDeclaredIdentsFromID (cpp:2383-2435) ===================

    /// A pattern-position node that isn't `Identifier`/`Empty`/
    /// `AssignmentPattern`/`ArrayPattern`/`RestElement`/`ObjectPattern`/
    /// `ComponentParameter` reports "invalid destructuring target"
    /// (cpp:2433) and returns `false` (no `containsExpr`).
    #[test]
    fn invalid_destructuring_target_reports_error() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let buf = sm.add_buffer_bytes("d.js", b"1");
        let loc = SMLoc {
            source: buf,
            offset: 0,
        };
        let range = SMRange {
            start: loc,
            end: loc,
        };
        let node = gc.alloc(Node::NumericLiteral(NumericLiteral::new(
            NodeMetadata::new(range),
            1.0,
        )));

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let binding_table = sem_ctx.binding_table_rc();
        {
            let mut resolver = SemanticResolver::new(
                &binding_table,
                &mut sem_ctx,
                &mut sm,
                &[],
                true,
            );

            let mut idents: Vec<&Node> = Vec::new();
            let contains_expr = resolver
                .extract_declared_idents_from_id(Some(node), &mut idents);
            assert!(!contains_expr);
            assert!(idents.is_empty());
        }
        assert_eq!(sm.error_count(), 1);
    }

    // ==== validateDeclarationName (cpp:2671-2707) =======================

    /// Strict mode: `arguments`/`eval` can never be declared, regardless of
    /// `Decl::Kind`.
    #[test]
    fn validate_declaration_name_rejects_strict_arguments_and_eval() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let buf = sm.add_buffer_bytes("d.js", b"arguments eval");
        let loc_a = SMLoc {
            source: buf,
            offset: 0,
        };
        let loc_e = SMLoc {
            source: buf,
            offset: 10,
        };
        let arguments_node = alloc_identifier(&gc, "arguments", loc_a);
        let eval_node = alloc_identifier(&gc, "eval", loc_e);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let func = sem_ctx.new_function(
            FuncIsArrow::No,
            ConstructorKind::None,
            None,
            None,
            /* strict */ true,
            CustomDirectives::default(),
        );
        let binding_table = sem_ctx.binding_table_rc();
        {
            let mut resolver = SemanticResolver::new(
                &binding_table,
                &mut sem_ctx,
                &mut sm,
                &[],
                true,
            );
            resolver.function_stack.push(FunctionContext {
                sem_info: func,
                node: None,
                label_map: Default::default(),
                current_loop: None,
                current_loop_or_switch: None,
                is_formal_params: false,
                decls: None,
                promoted_func_decls: Default::default(),
                binding_table_scope_depth: 0,
            });

            assert!(!resolver.validate_declaration_name(
                &gc,
                DeclKind::Var,
                arguments_node
            ));
            assert!(!resolver.validate_declaration_name(
                &gc,
                DeclKind::Let,
                eval_node
            ));
            // `resolver` (and its `&mut sm` borrow) must drop before `sm` can
            // be read again — see `identifiers.rs`'s tests for the same
            // pattern.
        }
        assert_eq!(sm.error_count(), 2);
    }

    /// Strict mode: a `Parameter` literally named `let` is rejected.
    #[test]
    fn validate_declaration_name_rejects_strict_parameter_named_let() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let buf = sm.add_buffer_bytes("d.js", b"let");
        let loc = SMLoc {
            source: buf,
            offset: 0,
        };
        let let_node = alloc_identifier(&gc, "let", loc);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let func = sem_ctx.new_function(
            FuncIsArrow::No,
            ConstructorKind::None,
            None,
            None,
            true,
            CustomDirectives::default(),
        );
        let binding_table = sem_ctx.binding_table_rc();
        {
            let mut resolver = SemanticResolver::new(
                &binding_table,
                &mut sem_ctx,
                &mut sm,
                &[],
                true,
            );
            resolver.function_stack.push(FunctionContext {
                sem_info: func,
                node: None,
                label_map: Default::default(),
                current_loop: None,
                current_loop_or_switch: None,
                is_formal_params: false,
                decls: None,
                promoted_func_decls: Default::default(),
                binding_table_scope_depth: 0,
            });

            assert!(!resolver.validate_declaration_name(
                &gc,
                DeclKind::Parameter,
                let_node
            ));
        }
        assert_eq!(sm.error_count(), 1);
    }

    /// `let`/`const` can never bind the name `let`, in strict OR loose
    /// mode (ES9.0 13.3.1.1) — unlike the two checks above, which are
    /// strict-only.
    #[test]
    fn validate_declaration_name_rejects_let_named_let_in_loose_mode() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let buf = sm.add_buffer_bytes("d.js", b"let");
        let loc = SMLoc {
            source: buf,
            offset: 0,
        };
        let let_node = alloc_identifier(&gc, "let", loc);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let func = sem_ctx.new_function(
            FuncIsArrow::No,
            ConstructorKind::None,
            None,
            None,
            /* strict */ false,
            CustomDirectives::default(),
        );
        let binding_table = sem_ctx.binding_table_rc();
        {
            let mut resolver = SemanticResolver::new(
                &binding_table,
                &mut sem_ctx,
                &mut sm,
                &[],
                true,
            );
            resolver.function_stack.push(FunctionContext {
                sem_info: func,
                node: None,
                label_map: Default::default(),
                current_loop: None,
                current_loop_or_switch: None,
                is_formal_params: false,
                decls: None,
                promoted_func_decls: Default::default(),
                binding_table_scope_depth: 0,
            });

            assert!(!resolver.validate_declaration_name(
                &gc,
                DeclKind::Let,
                let_node
            ));
            assert!(!resolver.validate_declaration_name(
                &gc,
                DeclKind::Const,
                let_node
            ));
            // `Var`/`ScopedFunction` etc. are unaffected by the `let`-name
            // rule.
            assert!(resolver.validate_declaration_name(
                &gc,
                DeclKind::Var,
                let_node
            ));
        }
        assert_eq!(sm.error_count(), 2);
    }

    // ==== validateAndDeclareIdentifier (cpp:2437-2669) ==================
    //
    // These build the "previous declaration" state by hand (a `Decl` plus
    // a `binding_table` entry) rather than by parsing+declaring real source,
    // so each redeclaration-matrix row can be exercised in isolation without
    // needing the (later-task) machinery — function visiting, catch-clause
    // visiting, `ScopedFunctionPromoter` — that would otherwise be needed to
    // reach it through the full resolver.

    /// `Decl::Kind::Parameter` followed by a top-level `let` of the same
    /// name is invalid (ES10.0 14.1.2) — dormant until parameter
    /// declarations exist (S1 T7), so exercised here by hand-declaring a
    /// `Parameter` decl. The parameter lives in its own (parameter) scope,
    /// distinct from but a parent of the function's body scope — the
    /// `has_parameter_expressions` shape (SemContext.h's `FunctionInfo`
    /// doc) — which isolates the `Parameter`-specific row from the
    /// `var-like, let-like, same-scope` row (both would otherwise fire).
    #[test]
    fn parameter_then_toplevel_let_is_invalid() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let buf = sm.add_buffer_bytes("d.js", b"x x");
        let loc_param = SMLoc {
            source: buf,
            offset: 0,
        };
        let loc_let = SMLoc {
            source: buf,
            offset: 2,
        };
        let param_ident = alloc_identifier(&gc, "x", loc_param);
        let let_ident = alloc_identifier(&gc, "x", loc_let);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let name = gc.atom_bytes("x");
        let func = sem_ctx.new_function(
            FuncIsArrow::No,
            ConstructorKind::None,
            None,
            None,
            false,
            CustomDirectives::default(),
        );
        let param_scope = sem_ctx.new_scope(func, None);
        let body_scope = sem_ctx.new_scope(func, Some(param_scope));
        // `getFunctionBodyScope` reads `functionBodyScopeIdx`, which
        // `ScopeRAII` normally sets via `is_function_body_scope` — set
        // directly here since this test bypasses `enter_scope`.
        sem_ctx.function_mut(func).function_body_scope_idx = 1;
        let param_decl = sem_ctx.new_decl_in_scope_default(
            name,
            DeclKind::Parameter,
            param_scope,
        );

        let binding_table = sem_ctx.binding_table_rc();
        let _bscope = Scope::new(&binding_table);
        binding_table.try_emplace(
            name,
            Binding::new(param_decl, Some(NodeRc::from_node(&gc, param_ident))),
        );

        {
            let mut resolver = SemanticResolver::new(
                &binding_table,
                &mut sem_ctx,
                &mut sm,
                &[],
                true,
            );
            resolver.function_stack.push(FunctionContext {
                sem_info: func,
                node: None,
                label_map: Default::default(),
                current_loop: None,
                current_loop_or_switch: None,
                is_formal_params: false,
                decls: None,
                promoted_func_decls: Default::default(),
                binding_table_scope_depth: 0,
            });
            resolver.cur_scope = Some(body_scope);

            resolver.validate_and_declare_identifier(
                &gc,
                DeclKind::Let,
                let_ident,
            );
        }
        assert_eq!(sm.error_count(), 1);
        assert_eq!(sm.note_count(), 1);
        // No new decl was created for a rejected redeclaration.
        assert!(sem_ctx.scope(body_scope).decls.is_empty());
    }

    /// A non-ES5 `Catch` decl conflicts with a `let` in the catch's OWN
    /// (parameter) scope's child (its body block) — the
    /// `prevInPrevScope`/`Catch`/`ES5Catch` row (cpp:2555-2560). The corpus
    /// reaches `visit_catch_clause`, but not this particular redeclaration
    /// row, so it is exercised directly on hand-built decls.
    #[test]
    fn catch_then_let_in_catch_body_is_invalid() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let buf = sm.add_buffer_bytes("d.js", b"e e");
        let loc_catch = SMLoc {
            source: buf,
            offset: 0,
        };
        let loc_let = SMLoc {
            source: buf,
            offset: 2,
        };
        let catch_ident = alloc_identifier(&gc, "e", loc_catch);
        let let_ident = alloc_identifier(&gc, "e", loc_let);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let name = gc.atom_bytes("e");
        let func = sem_ctx.new_function(
            FuncIsArrow::No,
            ConstructorKind::None,
            None,
            None,
            false,
            CustomDirectives::default(),
        );
        let top_scope = sem_ctx.new_scope(func, None);
        sem_ctx.function_mut(func).function_body_scope_idx = 0;
        let catch_param_scope = sem_ctx.new_scope(func, Some(top_scope));
        let catch_body_scope = sem_ctx.new_scope(func, Some(catch_param_scope));
        let catch_decl = sem_ctx.new_decl_in_scope_default(
            name,
            DeclKind::Catch,
            catch_param_scope,
        );

        let binding_table = sem_ctx.binding_table_rc();
        let _bscope = Scope::new(&binding_table);
        binding_table.try_emplace(
            name,
            Binding::new(catch_decl, Some(NodeRc::from_node(&gc, catch_ident))),
        );

        {
            let mut resolver = SemanticResolver::new(
                &binding_table,
                &mut sem_ctx,
                &mut sm,
                &[],
                true,
            );
            resolver.function_stack.push(FunctionContext {
                sem_info: func,
                node: None,
                label_map: Default::default(),
                current_loop: None,
                current_loop_or_switch: None,
                is_formal_params: false,
                decls: None,
                promoted_func_decls: Default::default(),
                binding_table_scope_depth: 0,
            });
            resolver.cur_scope = Some(catch_body_scope);

            resolver.validate_and_declare_identifier(
                &gc,
                DeclKind::Let,
                let_ident,
            );
        }
        assert_eq!(sm.error_count(), 1);
        assert_eq!(sm.note_count(), 1);
    }

    /// The `ES5Catch`-vs-`var` exception (ES10 B.3.5) does NOT live in
    /// `validateAndDeclareIdentifier` — it lives in the nested-scope `var`
    /// check inside `visit(VariableDeclarationNode *)` (cpp:336-352, the
    /// `prevKind != Decl::Kind::ES5Catch` exclusion). Proven directly by
    /// calling `visit_variable_declaration` on a hand-built `var e;` node
    /// with an `ES5Catch` decl for `e` already bound in an enclosing
    /// (non-function-body) scope: no error, even though `curScope_` is
    /// nested (which is exactly the condition that activates the check).
    #[test]
    fn es5catch_then_var_is_valid() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let buf = sm.add_buffer_bytes("d.js", b"e");
        let loc = SMLoc {
            source: buf,
            offset: 0,
        };
        let range = SMRange {
            start: loc,
            end: loc,
        };
        let catch_ident = alloc_identifier(&gc, "e", loc);
        let var_ident = alloc_identifier(&gc, "e", loc);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let name = gc.atom_bytes("e");
        let kw_var = sem_ctx.kw.ident_var;
        let func = sem_ctx.new_function(
            FuncIsArrow::No,
            ConstructorKind::None,
            None,
            None,
            false,
            CustomDirectives::default(),
        );
        let body_scope = sem_ctx.new_scope(func, None);
        sem_ctx.function_mut(func).function_body_scope_idx = 0;
        let nested_scope = sem_ctx.new_scope(func, Some(body_scope));
        let es5catch_decl = sem_ctx.new_decl_in_scope_default(
            name,
            DeclKind::ES5Catch,
            nested_scope,
        );

        let binding_table = sem_ctx.binding_table_rc();
        let _bscope = Scope::new(&binding_table);
        binding_table.try_emplace(
            name,
            Binding::new(
                es5catch_decl,
                Some(NodeRc::from_node(&gc, catch_ident)),
            ),
        );

        {
            let mut resolver = SemanticResolver::new(
                &binding_table,
                &mut sem_ctx,
                &mut sm,
                &[],
                true,
            );
            resolver.function_stack.push(FunctionContext {
                sem_info: func,
                node: None,
                label_map: Default::default(),
                current_loop: None,
                current_loop_or_switch: None,
                is_formal_params: false,
                decls: None,
                promoted_func_decls: Default::default(),
                binding_table_scope_depth: 0,
            });
            resolver.cur_scope = Some(nested_scope);

            let var_decl = alloc_var_decl(&gc, kw_var, var_ident, range);
            resolver.visit_variable_declaration(&gc, var_decl);
        }
        assert_eq!(sm.error_count(), 0);
        assert_eq!(sm.note_count(), 0);
    }

    /// The lexically-scoped-in-global-scope restricted-globals check
    /// (`let NaN;` at the top level) — a direct API-level counterpart to
    /// the `error-restricted-global.js` corpus file.
    #[test]
    fn restricted_global_property_rejects_lexical_shadow() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let buf = sm.add_buffer_bytes("d.js", b"NaN");
        let loc = SMLoc {
            source: buf,
            offset: 0,
        };
        let nan_node = alloc_identifier(&gc, "NaN", loc);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let func = sem_ctx.new_function(
            FuncIsArrow::No,
            ConstructorKind::None,
            None,
            None,
            false,
            CustomDirectives::default(),
        );
        // The FIRST scope created is `ScopeId(0)` == `get_global_scope()`.
        let global_scope = sem_ctx.new_scope(func, None);
        assert_eq!(global_scope, sem_ctx.get_global_scope());

        let binding_table = sem_ctx.binding_table_rc();
        let _bscope = Scope::new(&binding_table);

        {
            let mut resolver = SemanticResolver::new(
                &binding_table,
                &mut sem_ctx,
                &mut sm,
                &[],
                true,
            );
            resolver.function_stack.push(FunctionContext {
                sem_info: func,
                node: None,
                label_map: Default::default(),
                current_loop: None,
                current_loop_or_switch: None,
                is_formal_params: false,
                decls: None,
                promoted_func_decls: Default::default(),
                binding_table_scope_depth: 0,
            });
            resolver.cur_scope = Some(global_scope);

            resolver.validate_and_declare_identifier(
                &gc,
                DeclKind::Let,
                nan_node,
            );
        }
        assert_eq!(sm.error_count(), 1);
    }

    /// `Var, ScopedFunc` in DIFFERENT scopes, with the name already present
    /// in `promotedFuncDecls` (S3, always empty until `ScopedFunctionPromoter`
    /// lands — see the module doc): the redeclaration matrix's "reuse the
    /// promoted decl" branch (cpp:2578-2592) fires instead of declaring a
    /// fresh one, and the new binding points at the REUSED decl.
    #[test]
    fn var_then_scoped_function_reuses_promoted_decl_in_different_scope() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let buf = sm.add_buffer_bytes("d.js", b"foo foo");
        let loc_var = SMLoc {
            source: buf,
            offset: 0,
        };
        let loc_func = SMLoc {
            source: buf,
            offset: 4,
        };
        let func_ident = alloc_identifier(&gc, "foo", loc_func);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let name = gc.atom_bytes("foo");
        let func = sem_ctx.new_function(
            FuncIsArrow::No,
            ConstructorKind::None,
            None,
            None,
            false,
            CustomDirectives::default(),
        );
        let top_scope = sem_ctx.new_scope(func, None);
        // `validateAndDeclareIdentifier` unconditionally reads `topLevel`
        // (`curScope_->parentFunction->getFunctionBodyScope() == curScope_`)
        // even though this row doesn't key off it — set it so that read
        // doesn't hit the `functionScopeIdx not set` debug_assert.
        sem_ctx.function_mut(func).function_body_scope_idx = 0;
        let var_decl =
            sem_ctx.new_decl_in_scope_default(name, DeclKind::Var, top_scope);
        let nested_scope = sem_ctx.new_scope(func, Some(top_scope));
        // The promoted decl: a distinct `Decl` standing in for the one
        // `processPromotedFuncDecls` (S3) would have already created at
        // function scope.
        let promoted_decl =
            sem_ctx.new_decl_in_scope_default(name, DeclKind::Var, top_scope);

        let binding_table = sem_ctx.binding_table_rc();
        let _bscope_top = Scope::new(&binding_table);
        binding_table.try_emplace(
            name,
            Binding::new(var_decl, Some(NodeRc::from_node(&gc, func_ident))),
        );
        // A SEPARATE binding-table scope for `nested_scope`: `try_emplace`
        // refuses a second insertion of the same key into the SAME
        // binding-table scope, so without this, the reused-decl binding
        // below would silently no-op against the still-active `top_scope`
        // entry instead of creating a fresh, shadowing one — the
        // binding-table's own notion of "current scope" is independent of
        // (but must be kept in step with) `resolver.cur_scope`'s `ScopeId`.
        let _bscope_nested = Scope::new(&binding_table);

        {
            let mut resolver = SemanticResolver::new(
                &binding_table,
                &mut sem_ctx,
                &mut sm,
                &[],
                true,
            );
            resolver.function_stack.push(FunctionContext {
                sem_info: func,
                node: None,
                label_map: Default::default(),
                current_loop: None,
                current_loop_or_switch: None,
                is_formal_params: false,
                decls: None,
                promoted_func_decls: [(name, promoted_decl)]
                    .into_iter()
                    .collect(),
                binding_table_scope_depth: 0,
            });
            resolver.cur_scope = Some(nested_scope);

            resolver.validate_and_declare_identifier(
                &gc,
                DeclKind::ScopedFunction,
                func_ident,
            );
        }
        assert_eq!(sm.error_count(), 0);
        let new_binding = binding_table.lookup(&name).expect("binding present");
        assert_eq!(new_binding.decl, promoted_decl);
        assert_ne!(new_binding.decl, var_decl);
        let identifier = func_ident.as_identifier().unwrap();
        assert_eq!(
            sem_ctx.get_declaration_decl(identifier),
            Some(promoted_decl)
        );
        let _ = loc_var; // documents the "var foo;" the promoted decl models
    }

    /// The standalone "promoted function involves two declarations"
    /// side-table branch (cpp:2639-2655): when the SAME identifier node
    /// already carries a "declaration decl" (as it would after
    /// `processPromotedFuncDecls` ran on it, S3) AND its name is in
    /// `promotedFuncDecls`, a NEW decl is created in the current
    /// (block) scope, the binding table is `put` (not `try_emplace`) to
    /// point at it, and `setPromotedDecl` records it in the side table —
    /// crucially, the identifier's ORIGINAL "declaration decl" is left
    /// untouched (this branch never calls `setDeclarationDecl`).
    #[test]
    fn promoted_decl_side_table_branch_creates_a_new_block_scoped_decl() {
        let mut ctx = Context::new();
        let gc = ctx.lock();
        let mut sm = SourceErrorManager::new();
        let buf = sm.add_buffer_bytes("d.js", b"foo");
        let loc = SMLoc {
            source: buf,
            offset: 0,
        };
        let ident_node = alloc_identifier(&gc, "foo", loc);

        let mut sem_ctx = SemContext::new(Keywords::new(&gc));
        let name = gc.atom_bytes("foo");
        let func = sem_ctx.new_function(
            FuncIsArrow::No,
            ConstructorKind::None,
            None,
            None,
            false,
            CustomDirectives::default(),
        );
        let top_scope = sem_ctx.new_scope(func, None);
        let original_decl = sem_ctx.new_decl_in_scope_default(
            name,
            DeclKind::GlobalProperty,
            top_scope,
        );
        // Simulate `processPromotedFuncDecls` having already run on this
        // exact node: it set a "declaration decl" and recorded the name.
        let identifier = ident_node.as_identifier().unwrap();
        sem_ctx.set_declaration_decl(
            ident_node.node_id(),
            identifier,
            Some(original_decl),
        );
        let block_scope = sem_ctx.new_scope(func, Some(top_scope));

        let binding_table = sem_ctx.binding_table_rc();
        let _bscope = Scope::new(&binding_table);

        {
            let mut resolver = SemanticResolver::new(
                &binding_table,
                &mut sem_ctx,
                &mut sm,
                &[],
                true,
            );
            resolver.function_stack.push(FunctionContext {
                sem_info: func,
                node: None,
                label_map: Default::default(),
                current_loop: None,
                current_loop_or_switch: None,
                is_formal_params: false,
                decls: None,
                promoted_func_decls: [(name, original_decl)]
                    .into_iter()
                    .collect(),
                binding_table_scope_depth: 0,
            });
            resolver.cur_scope = Some(block_scope);

            resolver.validate_and_declare_identifier(
                &gc,
                DeclKind::ScopedFunction,
                ident_node,
            );
        }

        assert_eq!(sm.error_count(), 0);
        let promoted = sem_ctx
            .get_promoted_decl(ident_node.node_id())
            .expect("promoted decl side table populated");
        assert_ne!(promoted, original_decl);
        assert_eq!(sem_ctx.decl(promoted).scope, Some(block_scope));
        let new_binding = binding_table.lookup(&name).expect("binding present");
        assert_eq!(new_binding.decl, promoted);
        // The ORIGINAL "declaration decl" is untouched — this branch never
        // calls `setDeclarationDecl`.
        assert_eq!(
            sem_ctx.get_declaration_decl(identifier),
            Some(original_decl)
        );
    }

    /// `ScopedFunction, ScopedFunction` in the SAME scope: an error in
    /// strict mode, but the ES10.0 B.3.3.4 Annex B exception makes it
    /// valid (a fresh decl shadowing the first) in loose mode.
    #[test]
    fn scoped_function_redeclaration_same_scope_strict_vs_loose() {
        for strict in [true, false] {
            let mut ctx = Context::new();
            let gc = ctx.lock();
            let mut sm = SourceErrorManager::new();
            let buf = sm.add_buffer_bytes("d.js", b"foo foo");
            let loc_first = SMLoc {
                source: buf,
                offset: 0,
            };
            let loc_second = SMLoc {
                source: buf,
                offset: 4,
            };
            let first_ident = alloc_identifier(&gc, "foo", loc_first);
            let second_ident = alloc_identifier(&gc, "foo", loc_second);

            let mut sem_ctx = SemContext::new(Keywords::new(&gc));
            let name = gc.atom_bytes("foo");
            let func = sem_ctx.new_function(
                FuncIsArrow::No,
                ConstructorKind::None,
                None,
                None,
                strict,
                CustomDirectives::default(),
            );
            let scope = sem_ctx.new_scope(func, None);
            // See the sibling promoted-decl test for why this is set even
            // though this row doesn't key off `topLevel`.
            sem_ctx.function_mut(func).function_body_scope_idx = 0;
            let first_decl = sem_ctx.new_decl_in_scope_default(
                name,
                DeclKind::ScopedFunction,
                scope,
            );

            let binding_table = sem_ctx.binding_table_rc();
            let _bscope = Scope::new(&binding_table);
            binding_table.try_emplace(
                name,
                Binding::new(
                    first_decl,
                    Some(NodeRc::from_node(&gc, first_ident)),
                ),
            );

            {
                let mut resolver = SemanticResolver::new(
                    &binding_table,
                    &mut sem_ctx,
                    &mut sm,
                    &[],
                    true,
                );
                resolver.function_stack.push(FunctionContext {
                    sem_info: func,
                    node: None,
                    label_map: Default::default(),
                    current_loop: None,
                    current_loop_or_switch: None,
                    is_formal_params: false,
                    decls: None,
                    promoted_func_decls: Default::default(),
                    binding_table_scope_depth: 0,
                });
                resolver.cur_scope = Some(scope);

                resolver.validate_and_declare_identifier(
                    &gc,
                    DeclKind::ScopedFunction,
                    second_ident,
                );
            }

            if strict {
                assert_eq!(sm.error_count(), 1, "strict mode must reject it");
                assert_eq!(sm.note_count(), 1);
            } else {
                assert_eq!(sm.error_count(), 0, "loose mode must allow it");
                let identifier = second_ident.as_identifier().unwrap();
                let second_decl = sem_ctx
                    .get_declaration_decl(identifier)
                    .expect("a fresh decl was declared");
                assert_ne!(
                    second_decl, first_decl,
                    "loose mode declares a NEW decl, it doesn't reuse the first"
                );
            }
        }
    }
}