lanekeep-types 0.11.0

The type oracle: what a node's type is, answered from one parsed file.
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
//! The oracle, against real parse trees.
//!
//! Integration rather than unit tests because the oracle's whole job is reading a grammar's
//! output, and a hand-built tree would be a second opinion about node shapes rather than a
//! test of the first.
#![expect(
    clippy::expect_used,
    clippy::panic,
    reason = "the lint's grant covers `#[test]` functions and `#[cfg(test)]` modules, and a \
              helper in an integration-test crate is neither — see AGENTS.md"
)]

use lanekeep_lang::Language;
use lanekeep_lang_js::TypeScript;
use lanekeep_types::{Primitive, Type, TypeScriptOracle, TypeScriptSupport};
use tree_sitter::{Node, Tree};

/// Parse `source` with the TypeScript grammar.
fn parse(source: &str) -> Tree {
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&TypeScript.grammar())
        .expect("the TypeScript grammar loads");
    parser.parse(source, None).expect("the source parses")
}

/// Every node in the tree, in source order.
///
/// A cursor walk rather than indexing: `children` hands back every child in order with no
/// index loop, and it is right whatever type `child_count` answers in — it was `usize`
/// against a `u32` `child` until tree-sitter 0.27, and the cast between them tripped
/// `clippy::cast_possible_truncation`, which this workspace denies.
fn nodes(tree: &Tree) -> Vec<Node<'_>> {
    let mut out = Vec::new();
    let mut stack = vec![tree.root_node()];
    while let Some(node) = stack.pop() {
        out.push(node);
        let mut cursor = node.walk();
        let children: Vec<Node<'_>> = node.children(&mut cursor).collect();
        stack.extend(children.into_iter().rev());
    }
    out
}

/// The last node of `kind` in the tree, in source order.
///
/// The *last* one, because a test writes the interesting expression after whatever sets it
/// up — and because resolving a use rather than a declaration is what a rule does.
fn last_of<'t>(tree: &'t Tree, kind: &str) -> Node<'t> {
    nodes(tree)
        .into_iter()
        .rfind(|node| node.kind() == kind)
        .unwrap_or_else(|| panic!("no `{kind}` node in the tree"))
}

/// Type the last node of `kind` in `source`.
fn type_of_last(source: &str, kind: &str) -> Option<Type> {
    let tree = parse(source);
    let support = TypeScriptSupport::probe(&TypeScript).expect("TypeScript is supported");
    let oracle = TypeScriptOracle::new(&support, &tree, source);
    oracle.type_of(last_of(&tree, kind))
}

#[test]
fn a_number_literal_is_a_number() {
    assert_eq!(
        type_of_last("const x = 42;", "number"),
        Some(Type::Primitive(Primitive::Number))
    );
}

/// The pair that matters: `1n` parses as `(number)` too.
///
/// There is no distinct bigint literal node, so a trailing `n` in the source text is the
/// only thing separating the two. An oracle dispatching on kind alone types every bigint as
/// a number, silently — which is precisely the confusion a bigint rule exists to catch.
#[test]
fn a_bigint_literal_is_a_bigint_despite_parsing_as_a_number() {
    assert_eq!(
        type_of_last("const x = 42n;", "number"),
        Some(Type::Primitive(Primitive::BigInt))
    );
}

#[test]
fn a_string_literal_is_a_string() {
    assert_eq!(
        type_of_last("const x = 'a';", "string"),
        Some(Type::Primitive(Primitive::String))
    );
}

#[test]
fn a_template_string_is_a_string() {
    assert_eq!(
        type_of_last("const x = `a${b}`;", "template_string"),
        Some(Type::Primitive(Primitive::String))
    );
}

#[test]
fn the_boolean_literals_are_booleans() {
    assert_eq!(
        type_of_last("const x = true;", "true"),
        Some(Type::Primitive(Primitive::Boolean))
    );
    assert_eq!(
        type_of_last("const x = false;", "false"),
        Some(Type::Primitive(Primitive::Boolean))
    );
}

#[test]
fn null_and_undefined_are_their_own_primitives() {
    assert_eq!(
        type_of_last("const x = null;", "null"),
        Some(Type::Primitive(Primitive::Null))
    );
    assert_eq!(
        type_of_last("const x = undefined;", "undefined"),
        Some(Type::Primitive(Primitive::Undefined))
    );
}

#[test]
fn a_parenthesized_expression_is_its_inner_expression() {
    assert_eq!(
        type_of_last("const x = (42);", "parenthesized_expression"),
        Some(Type::Primitive(Primitive::Number))
    );
}

#[test]
fn a_grammar_that_speaks_typescript_yields_support() {
    assert!(TypeScriptSupport::probe(&TypeScript).is_some());
}

/// The guard PR 1 established, now living on the probe.
#[test]
fn a_grammar_that_does_not_speak_typescript_yields_no_support() {
    assert!(TypeScriptSupport::probe(&lanekeep_lang_python::Python).is_none());
}

/// One token serves many files, which is the entire point of the split.
#[test]
fn one_probe_serves_many_files() {
    let support = TypeScriptSupport::probe(&TypeScript).expect("TypeScript is supported");
    for (source, kind, expected) in [
        ("const a = 1;", "number", Type::Primitive(Primitive::Number)),
        (
            "const b = 'x';",
            "string",
            Type::Primitive(Primitive::String),
        ),
        (
            "const c = 1n;",
            "number",
            Type::Primitive(Primitive::BigInt),
        ),
    ] {
        let tree = parse(source);
        let oracle = TypeScriptOracle::new(&support, &tree, source);
        assert_eq!(
            oracle.type_of(last_of(&tree, kind)),
            Some(expected),
            "{source}"
        );
    }
}

#[test]
fn arithmetic_on_numbers_is_a_number() {
    assert_eq!(
        type_of_last("const x = 1 * 2;", "binary_expression"),
        Some(Type::Primitive(Primitive::Number))
    );
}

#[test]
fn arithmetic_on_bigints_is_a_bigint() {
    assert_eq!(
        type_of_last("const x = 2n * 3n;", "binary_expression"),
        Some(Type::Primitive(Primitive::BigInt))
    );
}

/// The half that denies the bug: `*` is not a number just because it is `*`.
///
/// This arm used to fall through to `number` whenever the pair was not two bigints, which
/// meant an operand nothing had established still produced a confident primitive. The
/// first case below is a bigint answered as a number — the very confusion a bigint rule
/// exists to catch — and the second is a `TypeError` answered as a value.
#[test]
fn arithmetic_with_an_operand_the_oracle_cannot_type_is_not_a_number() {
    assert_eq!(
        type_of_last(
            "import { total } from './m';\nconst z = total * 2n;",
            "binary_expression"
        ),
        None
    );
    assert_eq!(
        type_of_last(
            "class D {}\nconst z = new D() * new D();",
            "binary_expression"
        ),
        None
    );
}

#[test]
fn a_comparison_is_a_boolean() {
    assert_eq!(
        type_of_last("const x = 1 < 2;", "binary_expression"),
        Some(Type::Primitive(Primitive::Boolean))
    );
}

#[test]
fn concatenation_with_a_string_is_a_string() {
    assert_eq!(
        type_of_last("const x = 'a' + 1;", "binary_expression"),
        Some(Type::Primitive(Primitive::String))
    );
}

#[test]
fn mixing_a_number_and_a_bigint_is_not_typed() {
    assert_eq!(type_of_last("const x = 1 + 1n;", "binary_expression"), None);
}

/// A value-dependent operator is deliberately outside the table, asserted rather than incidental.
///
/// `&&` stands in for the group (`||`, the bitwise operators, `in`, `instanceof`): its result
/// depends on a run-time value, not on the operand types. `??` used to be asserted here and no
/// longer is — it reaches the table now, and the nullish-coalescing tests below are where it is
/// pinned.
#[test]
fn an_operator_outside_the_table_is_not_typed() {
    assert_eq!(
        type_of_expr(
            "function f(a: number, b: number) { return a && b; }",
            "a && b"
        ),
        None
    );
}

/// `count ?? 0` is `number` when the left is `number | undefined`.
///
/// This is the defaulting idiom the operator table exists to see through: the left is nullable
/// (that is why it is defaulted), its non-nullish arm is `number`, and the fallback is `number`,
/// so the whole expression is `number` under any reading. The oracle strips `null`/`undefined`
/// from the left before the table compares the two sides.
#[test]
fn a_nullish_default_over_a_nullable_left_is_the_shared_primitive() {
    assert_eq!(
        type_of_expr(
            "function f(count: number | undefined) { return count ?? 0; }",
            "count ?? 0"
        ),
        Some(Type::Primitive(Primitive::Number))
    );
}

/// The nullish arm dropped from the left is `null` as readily as `undefined`.
#[test]
fn a_nullish_default_drops_null_from_the_left() {
    assert_eq!(
        type_of_expr(
            "function f(s: string | null) { return s ?? ''; }",
            "s ?? ''"
        ),
        Some(Type::Primitive(Primitive::String))
    );
}

/// A non-nullable left agrees with a matching fallback, `??` redundant or not.
///
/// The left never strips anything here — it is already a plain `string` — so this pins the
/// path where both sides arrive as bare primitives, distinct from the union-stripping one above.
#[test]
fn a_nullish_default_over_a_non_nullable_left_is_that_primitive() {
    assert_eq!(
        type_of_expr(
            "function f(a: string, b: string) { return a ?? b; }",
            "a ?? b"
        ),
        Some(Type::Primitive(Primitive::String))
    );
}

/// The ticket's flagship: `tx.amount ?? 0n` is `bigint`, needing property access and `??` at once.
///
/// The property is required, so `tx.amount` is a bare `bigint`; the fallback is `bigint`; the
/// whole expression is `bigint`. Before property access (#249) and this arm together, it answered
/// nothing.
#[test]
fn a_nullish_default_over_a_typed_property_is_that_property_type() {
    assert_eq!(
        type_of_expr(
            "interface Tx { amount: bigint }\nfunction f(tx: Tx) { return tx.amount ?? 0n; }",
            "tx.amount ?? 0n"
        ),
        Some(Type::Primitive(Primitive::BigInt))
    );
}

/// An optional property is `T | undefined`, and the `??` strips the `undefined` to agree.
///
/// This is the idiom in full: `amount?: bigint` makes `tx.amount` nullable, which is exactly why
/// `?? 0n` is written, and the result is the `bigint` the fallback and the stripped left share.
#[test]
fn a_nullish_default_over_an_optional_property_is_that_property_type() {
    assert_eq!(
        type_of_expr(
            "interface Tx { amount?: bigint }\nfunction f(tx: Tx) { return tx.amount ?? 0n; }",
            "tx.amount ?? 0n"
        ),
        Some(Type::Primitive(Primitive::BigInt))
    );
}

/// Disagreeing sides answer nothing: `number | undefined ?? 0n` is `number | bigint`, not one type.
#[test]
fn a_nullish_default_with_a_disagreeing_fallback_is_not_typed() {
    assert_eq!(
        type_of_expr(
            "function f(count: number | undefined) { return count ?? 0n; }",
            "count ?? 0n"
        ),
        None
    );
}

/// A left that strips to more than one primitive is not a single primitive, so it answers nothing.
///
/// `number | string | undefined` loses its `undefined` and still holds two primitives; naming one
/// would be a guess, so the table stays silent. This guards the arm against collapsing to a single
/// side.
#[test]
fn a_nullish_default_over_a_multi_primitive_left_is_not_typed() {
    assert_eq!(
        type_of_expr(
            "function f(x: number | string | undefined) { return x ?? 0; }",
            "x ?? 0"
        ),
        None
    );
}

/// A left that reduces to a nominal is not a primitive the table can answer.
///
/// `number | Decimal` has no nullish arm to drop and still holds a nominal member, so the strip
/// leaves something the table has no row for. Answering `number` would be a confident wrong
/// answer — `x` may be a `Decimal` — so the oracle says nothing. This is the only fixture that
/// reaches the nominal arm of the strip.
#[test]
fn a_nullish_default_over_a_left_that_reduces_to_a_nominal_is_not_typed() {
    assert_eq!(
        type_of_expr(
            "interface Decimal { c: number }\n\
             function f(x: number | Decimal) { return x ?? 0; }",
            "x ?? 0"
        ),
        None
    );
}

/// A chain of defaults composes: `a ?? b ?? 0` is `number` when each link is a `number`.
///
/// The inner `a ?? b` is typed first — `number | undefined` on the left, a `number` fallback —
/// and the outer `??` reads that `number` result as its own non-nullish left. Nesting is only the
/// `binary_expression` arm reached recursively.
#[test]
fn a_chain_of_nullish_defaults_composes_to_the_shared_primitive() {
    assert_eq!(
        type_of_expr(
            "function f(a: number | undefined, b: number) { return a ?? b ?? 0; }",
            "a ?? b ?? 0"
        ),
        Some(Type::Primitive(Primitive::Number))
    );
}

/// A nullable fallback sinks the answer: the right is read as it stands, never stripped.
///
/// `a ?? b` with both `number | undefined` is itself `number | undefined`, because a nullish `b`
/// is kept — so the right is a union, and the table answers nothing rather than a bare `number`.
/// Only the left has its nullish arms removed.
#[test]
fn a_nullish_default_with_a_nullable_fallback_is_not_typed() {
    assert_eq!(
        type_of_expr(
            "function f(a: number | undefined, b: number | undefined) { return a ?? b; }",
            "a ?? b"
        ),
        None
    );
}

/// Two untyped sides answer nothing through the oracle, not only in the table.
///
/// The outside-table e2e assertion moved to `&&`; this keeps a `??` over operands the oracle
/// cannot type pinned end to end, the path where `non_nullish_primitive_of` and `primitive_of`
/// both come back `None`.
#[test]
fn a_nullish_default_over_two_untyped_sides_is_not_typed() {
    assert_eq!(type_of_expr("const x = a ?? b;", "a ?? b"), None);
}

#[test]
fn typeof_is_a_string() {
    assert_eq!(
        type_of_last("const x = typeof y;", "unary_expression"),
        Some(Type::Primitive(Primitive::String))
    );
}

#[test]
fn a_builtin_conversion_has_the_type_it_converts_to() {
    assert_eq!(
        type_of_last("const x = parseFloat(s);", "call_expression"),
        Some(Type::Primitive(Primitive::Number))
    );
    assert_eq!(
        type_of_last("const x = String(v);", "call_expression"),
        Some(Type::Primitive(Primitive::String))
    );
}

/// The other half of the pair, and the one that denies a real bug.
///
/// A file declaring its own `parseFloat` must not be typed by the builtin table. Matching
/// on the name alone would type this as a number, and the rule reading it would report
/// about a value that is a `Decimal`.
#[test]
fn a_shadowed_builtin_is_not_typed_by_the_builtin_table() {
    assert_eq!(
        type_of_last(
            "function parseFloat(s: string) { return s; }\nconst x = parseFloat('1');",
            "call_expression"
        ),
        None
    );
}

#[test]
fn a_call_to_an_ordinary_function_is_not_typed() {
    assert_eq!(
        type_of_last("const x = myHelper(1);", "call_expression"),
        None
    );
}

#[test]
fn each_predefined_type_annotation_is_its_primitive() {
    for (written, expected) in [
        ("number", Primitive::Number),
        ("string", Primitive::String),
        ("boolean", Primitive::Boolean),
        ("bigint", Primitive::BigInt),
        ("symbol", Primitive::Symbol),
    ] {
        assert_eq!(
            type_of_last(&format!("let x: {written};"), "type_annotation"),
            Some(Type::Primitive(expected)),
            "{written}"
        );
    }
}

/// `any` and `unknown` parse identically to `number`, and both must give nothing.
///
/// Asserted as *expected* rather than left to fall out. `any` is the absence of a claim,
/// and an oracle returning a type for it would assert something TypeScript does not.
#[test]
fn any_and_unknown_are_not_types_the_oracle_will_assert() {
    assert_eq!(type_of_last("let x: any;", "type_annotation"), None);
    assert_eq!(type_of_last("let x: unknown;", "type_annotation"), None);
}

#[test]
fn a_union_annotation_is_a_union_of_its_members() {
    let Some(Type::Union(members)) = type_of_last("let x: number | string;", "type_annotation")
    else {
        panic!("a two-member union");
    };
    assert_eq!(
        members,
        vec![
            Type::Primitive(Primitive::Number),
            Type::Primitive(Primitive::String),
        ]
    );
}

/// The canonical ordering, asserted through the grammar rather than only through `union`.
#[test]
fn a_union_annotation_does_not_depend_on_the_order_written() {
    assert_eq!(
        type_of_last("let x: number | string;", "type_annotation"),
        type_of_last("let x: string | number;", "type_annotation")
    );
}

/// The union's own denying half: a member that cannot be typed sinks the whole union.
///
/// Dropping it and keeping the rest returns a bare `Primitive(Number)` here — identical in
/// every byte to a declared `number`, with nothing left to say a member was lost. A rule
/// reporting "this is typed `number`" then fires on `amount: number | Decimal` and accuses
/// correct code, which is the failure the whole oracle is arranged against.
#[test]
fn a_union_with_a_member_the_oracle_cannot_type_is_not_typed_at_all() {
    assert_eq!(
        type_of_last("let x: number | Foo<T>;", "type_annotation"),
        None
    );
    assert_eq!(
        type_of_last("let x: number | (string | boolean);", "type_annotation"),
        None
    );
    assert_eq!(
        type_of_last("let x: number[] | string;", "type_annotation"),
        None
    );
}

/// And the guard against over-refusing it: a comment is not a member.
///
/// A `comment` is a *named* child of a `union_type`, so an all-or-nothing walk that only
/// filtered on `is_named` would see one as a member it could not type — and a comment
/// written inside an annotation would silence the union. The union still has to survive
/// being commented.
#[test]
fn a_comment_inside_a_union_is_not_a_member_of_it() {
    assert_eq!(
        type_of_last("let x: number /* which one */ | string;", "type_annotation"),
        type_of_last("let x: number | string;", "type_annotation")
    );
    assert!(matches!(
        type_of_last("let x: number /* which one */ | string;", "type_annotation"),
        Some(Type::Union(_))
    ));
}

#[test]
fn a_literal_type_takes_its_literal_primitive() {
    assert_eq!(
        type_of_last("let x: 42;", "type_annotation"),
        Some(Type::Primitive(Primitive::Number))
    );
    assert_eq!(
        type_of_last("let x: 'a';", "type_annotation"),
        Some(Type::Primitive(Primitive::String))
    );
}

#[test]
fn a_named_type_is_nominal() {
    assert_eq!(
        type_of_last(
            "import { Decimal } from 'decimal.js';\nlet x: Decimal;",
            "type_annotation"
        ),
        Some(Type::Nominal {
            name: "Decimal".to_owned(),
            symbol: Some(lanekeep_types::Symbol {
                name: "Decimal".to_owned(),
                exported: Some("Decimal".to_owned()),
                module: Some("decimal.js".to_owned()),
            }),
        })
    );
}

/// A renamed import's `Symbol.name` is the local alias, and `exported` is the name the
/// module uses.
///
/// `name` is filled from the reference's own text, deliberately: it is the spelling a
/// message quotes. What used to be dropped one line later — the resolver's
/// `ImportedName::Named("Decimal")` — is now the second field, and this is the fixture where
/// the two differ. `a_named_type_is_nominal` above cannot stand in for it: it imports
/// `Decimal` under its own name, so the use site and the export read identically and an
/// implementation that copied `name` into `exported` would pass it.
#[test]
fn a_renamed_import_s_symbol_name_is_the_local_alias() {
    assert_eq!(
        type_of_last(
            "import { Decimal as Money } from 'decimal.js';\nlet x: Money;",
            "type_annotation"
        ),
        Some(Type::Nominal {
            name: "Money".to_owned(),
            symbol: Some(lanekeep_types::Symbol {
                name: "Money".to_owned(),
                exported: Some("Decimal".to_owned()),
                module: Some("decimal.js".to_owned()),
            }),
        })
    );
}

/// The shadow pair for nominals: a local class shares the name and not the module.
#[test]
fn a_locally_declared_type_is_nominal_with_no_module() {
    assert_eq!(
        type_of_last("class Decimal {}\nlet x: Decimal;", "type_annotation"),
        Some(Type::Nominal {
            name: "Decimal".to_owned(),
            symbol: Some(lanekeep_types::Symbol {
                name: "Decimal".to_owned(),
                exported: None,
                module: None,
            }),
        })
    );
}

/// The third case, and the one nothing else here covers: a nominal type with **no** symbol.
///
/// `Date` is an ambient global — declared in a lib the oracle does not open, imported from
/// nowhere, shadowed by nothing — so the resolver has nothing to say and the symbol is absent.
/// Ordinary rather than a corner case: every global and every ambient declaration lands here.
///
/// The two tests above cannot stand in for it. Both assert `symbol: Some(..)`, so an oracle
/// that fabricated a symbol from the type's own name whenever the resolver came back empty
/// would leave them green — and a rule branching on `symbol` would then read an unattributed
/// global as a resolved local declaration, which is the wrong answer rather than no answer.
#[test]
fn an_ambient_type_is_nominal_with_no_symbol() {
    assert_eq!(
        type_of_last("let x: Date;", "type_annotation"),
        Some(Type::Nominal {
            name: "Date".to_owned(),
            symbol: None,
        })
    );
}

#[test]
fn a_function_type_annotation_is_not_typed() {
    assert_eq!(
        type_of_last("let x: () => number;", "type_annotation"),
        None
    );
}

/// The pair for `bigint`'s text-matched shortcut, same shape as
/// `a_shadowed_builtin_is_not_typed_by_the_builtin_table` one level up in the vocabulary.
///
/// A file declaring its own `bigint` must resolve to that declaration, not to the
/// primitive. Matching on text alone, before the resolver has a say, would silently type
/// this as `Primitive::BigInt` instead of the class the annotation actually names.
#[test]
fn a_locally_declared_bigint_shadows_the_primitive() {
    assert_eq!(
        type_of_last("class bigint {}\nlet x: bigint;", "type_annotation"),
        Some(Type::Nominal {
            name: "bigint".to_owned(),
            symbol: Some(lanekeep_types::Symbol {
                name: "bigint".to_owned(),
                exported: None,
                module: None,
            }),
        })
    );
}

/// The same guard, reached through an alias rather than a class.
///
/// `type bigint = string` shadows the primitive exactly as `class bigint {}` does above —
/// the resolver sees a local declaration either way, so the text-matched shortcut still
/// defers. What differs is where deferring leads: a class has nothing further to read and
/// stops at nominal, but an alias is followed to what it names. The right answer here is
/// the alias's target, not the primitive the name happens to spell.
#[test]
fn a_locally_aliased_bigint_resolves_through_the_alias() {
    assert_eq!(
        type_of_last("type bigint = string;\nlet x: bigint;", "type_annotation"),
        Some(Type::Primitive(Primitive::String))
    );
}

/// Type the last `identifier` whose text is `name`.
fn type_of_use(source: &str, name: &str) -> Option<Type> {
    let tree = parse(source);
    let support = TypeScriptSupport::probe(&TypeScript).expect("TypeScript is supported");
    let oracle = TypeScriptOracle::new(&support, &tree, source);

    let found = nodes(&tree)
        .into_iter()
        .rfind(|node| node.kind() == "identifier" && source.get(node.byte_range()) == Some(name));
    oracle.type_of(found.unwrap_or_else(|| panic!("no use of `{name}`")))
}

#[test]
fn an_annotated_parameter_has_its_annotated_type() {
    assert_eq!(
        type_of_use(
            "function credit(amount: number) { return amount; }",
            "amount"
        ),
        Some(Type::Primitive(Primitive::Number))
    );
}

#[test]
fn an_annotated_optional_parameter_has_its_annotated_type() {
    assert_eq!(
        type_of_use(
            "function credit(amount?: number) { return amount; }",
            "amount"
        ),
        Some(Type::Primitive(Primitive::Number))
    );
}

/// A parameter bound through a pattern is not given the pattern's own type.
///
/// `Money` is the type of the object being taken apart, not of `rate` taken out of it, and
/// the resolver hands back the same `required_parameter` for every name the pattern binds.
/// Reading the annotation regardless answers `Money` for `rate` — a confident type for a
/// name whose real one needs a property lookup this milestone does not have.
#[test]
fn a_destructured_parameter_is_not_given_its_pattern_s_type() {
    for source in [
        "function credit({ rate }: Money) { return rate; }",
        "function credit({ rate }?: Money) { return rate; }",
        "function credit([rate]: Money) { return rate; }",
        "const credit = ({ rate }: Money) => rate;",
    ] {
        assert_eq!(type_of_use(source, "rate"), None, "{source}");
    }
}

/// The other half: a plain parameter still answers, so the guard did not silence everything.
///
/// `let a!: number` is the adjacent shape worth pinning — measured, a definite-assignment
/// `!` leaves the bound name an `identifier`, so it is not mistaken for a pattern.
#[test]
fn the_pattern_guard_leaves_a_plain_binding_alone() {
    assert_eq!(
        type_of_use(
            "function credit(amount: number) { return amount; }",
            "amount"
        ),
        Some(Type::Primitive(Primitive::Number))
    );
    assert_eq!(
        type_of_use("let amount!: number;\nconst y = amount;", "amount"),
        Some(Type::Primitive(Primitive::Number))
    );
}

/// The same guard on a variable declarator, where both paths were wrong.
///
/// The initializer's type belongs to what was destructured, not to any name taken out of
/// it: `String(q)` is a string and `s.length` is a number. The annotation is wrong the same
/// way — `Money` is the type of `order`, and `rate` is a property of it.
#[test]
fn a_destructured_local_is_not_given_its_initializer_or_annotation_type() {
    assert_eq!(
        type_of_use(
            "const s = String(q);\nconst { length } = s;\nconst y = length;",
            "length"
        ),
        None
    );
    assert_eq!(
        type_of_use("const { rate }: Money = order;\nconst y = rate;", "rate"),
        None
    );
    assert_eq!(
        type_of_use("const [first] = xs;\nconst y = first;", "first"),
        None
    );
}

/// The headline: a local whose type comes from what it was initialized with.
#[test]
fn a_local_takes_the_type_of_its_initializer() {
    assert_eq!(
        type_of_use(
            "const amount = parseFloat(raw);\nconst y = amount;",
            "amount"
        ),
        Some(Type::Primitive(Primitive::Number))
    );
}

/// The annotation wins over the initializer, and this is the half that denies a real bug.
///
/// An implementation reading the initializer first would answer `number` here. The
/// declared type is what the program means.
#[test]
fn an_annotation_beats_the_initializer_it_sits_beside() {
    assert_eq!(
        type_of_use(
            "const amount: string = parseFloat(raw);\nconst y = amount;",
            "amount"
        ),
        Some(Type::Primitive(Primitive::String))
    );
}

#[test]
fn a_local_annotated_with_a_named_type_is_nominal() {
    assert_eq!(
        type_of_use(
            "import { Decimal } from 'decimal.js';\nfunction f(x: Decimal) { return x; }",
            "x"
        ),
        Some(Type::Nominal {
            name: "Decimal".to_owned(),
            symbol: Some(lanekeep_types::Symbol {
                name: "Decimal".to_owned(),
                exported: Some("Decimal".to_owned()),
                module: Some("decimal.js".to_owned()),
            }),
        })
    );
}

/// An imported *value* has no type this milestone can read.
///
/// Its declaration is in another file, which this oracle does not open. Cross-file
/// resolution is a later milestone; answering anything here would be a guess.
#[test]
fn an_imported_value_has_no_type_yet() {
    assert_eq!(
        type_of_use("import { total } from './m';\nconst y = total;", "total"),
        None
    );
}

#[test]
fn an_undeclared_name_has_no_type() {
    assert_eq!(type_of_use("const y = missing;", "missing"), None);
}

/// An initializer chain terminates rather than running away.
#[test]
fn a_chain_of_initializers_terminates() {
    let source = "const a = b;\nconst b = a;\nconst c = a;\n";
    assert_eq!(type_of_use(source, "c"), None);
}

#[test]
fn a_same_file_type_alias_resolves_to_what_it_aliases() {
    assert_eq!(
        type_of_last("type Amount = number;\nlet x: Amount;", "type_annotation"),
        Some(Type::Primitive(Primitive::Number))
    );
}

#[test]
fn an_alias_chain_resolves_through_every_link() {
    assert_eq!(
        type_of_last(
            "type A = number;\ntype B = A;\ntype C = B;\nlet x: C;",
            "type_annotation"
        ),
        Some(Type::Primitive(Primitive::Number))
    );
}

/// A cycle terminates instead of running away.
///
/// `type A = B; type B = A` is accepted by the parser and is meaningless. The bound is what
/// makes this return rather than recurse until the stack ends.
#[test]
fn an_alias_cycle_terminates_without_an_answer() {
    assert_eq!(
        type_of_last("type A = B;\ntype B = A;\nlet x: A;", "type_annotation"),
        None
    );
}

/// An alias to something the oracle cannot type is not itself an answer.
#[test]
fn an_alias_to_an_untyped_type_is_untyped() {
    assert_eq!(
        type_of_last("type A = () => void;\nlet x: A;", "type_annotation"),
        None
    );
}

/// A generic type parameter is not answered by an outer alias that shares its name.
///
/// The scope walk had no idea a signature declared `A`, so it escaped outward and found
/// `type A = number` — and `type_of(x)` came back `number` for a value that is whatever
/// the call site chose. That is a confidently wrong type where the honest answer is
/// nothing, on every shape that can carry a type parameter.
#[test]
fn a_type_parameter_is_not_answered_by_an_outer_alias_of_the_same_name() {
    for source in [
        "type A = number;\nfunction f<A>(x: A) { return x; }",
        "type A = number;\nclass C<A> { m(x: A) { return x; } }",
        "type A = number;\nclass C { m<A>(x: A) { return x; } }",
        "type A = number;\nconst f = <A,>(x: A) => x;",
    ] {
        assert_eq!(type_of_use(source, "x"), None, "{source}");
    }
}

/// The other half: without a type parameter in the way, the alias is still followed.
///
/// The fix must not have made every annotated parameter unknowable — it is the *shadow*
/// that is new, and one identical file minus the `<A>` has to keep answering `number`.
#[test]
fn an_alias_still_answers_a_parameter_that_no_type_parameter_shadows() {
    assert_eq!(
        type_of_use("type A = number;\nfunction f(x: A) { return x; }", "x"),
        Some(Type::Primitive(Primitive::Number))
    );
}

/// A `for...of` loop variable is not answered by an outer binding of the same name.
///
/// `for_in_statement` was in the resolver's scope list and bound nothing, so the walk went
/// straight past the loop head to whatever was outside it — and `type_of(x)` inside the
/// body came back `string` from a `const x = 'a'` the loop shadows entirely.
#[test]
fn a_for_of_loop_variable_is_not_answered_by_the_binding_it_shadows() {
    for source in [
        "const x = 'a';\nfor (const x of ns) { g(x); }",
        "const x = 'a';\nfor (let x of ns) { g(x); }",
        "const x = 'a';\nfor (const x in ns) { g(x); }",
    ] {
        assert_eq!(type_of_use(source, "x"), None, "{source}");
    }
}

/// The two halves that deny an over-eager version of the fix.
///
/// A head with no `const` / `let` / `var` declares nothing — `for (x of ns)` assigns to a
/// name that already exists — so binding it would invent a shadow the program does not
/// have. And a loop that binds some *other* name must leave the outer one reachable.
#[test]
fn a_loop_head_that_declares_nothing_leaves_the_outer_binding_reachable() {
    assert_eq!(
        type_of_use("const x = 'a';\nfor (x of ns) { g(x); }", "x"),
        Some(Type::Primitive(Primitive::String))
    );
    assert_eq!(
        type_of_use("const x = 'a';\nfor (const y of ns) { g(x); }", "x"),
        Some(Type::Primitive(Primitive::String))
    );
}

/// The `Debug` impl identifies the file rather than reproducing it.
///
/// `source` is a whole file. Printing it puts that file into every log line the oracle
/// appears in, which is what `LanguageRegistry` prints keys rather than languages to avoid.
#[test]
fn the_debug_impl_does_not_print_the_whole_source() {
    let source = "const aNameThatMustNotReachALogLine = 1;";
    let tree = parse(source);
    let support = TypeScriptSupport::probe(&TypeScript).expect("TypeScript is supported");
    let oracle = TypeScriptOracle::new(&support, &tree, source);

    let rendered = format!("{oracle:?}");
    assert!(
        !rendered.contains("aNameThatMustNotReachALogLine"),
        "{rendered}"
    );
    assert!(rendered.contains("source_len"), "{rendered}");
}

/// The symbol of the last use of `name`.
fn symbol_of_use(source: &str, name: &str) -> Option<lanekeep_types::Symbol> {
    let tree = parse(source);
    let support = TypeScriptSupport::probe(&TypeScript).expect("TypeScript is supported");
    let oracle = TypeScriptOracle::new(&support, &tree, source);

    let found = nodes(&tree).into_iter().rfind(|node| {
        matches!(node.kind(), "identifier" | "type_identifier")
            && source.get(node.byte_range()) == Some(name)
    });
    oracle.symbol_of(found.unwrap_or_else(|| panic!("no use of `{name}`")))
}

/// An unrenamed import copies the name rather than leaving `exported` empty.
///
/// The decision, asserted rather than left to fall out of the implementation. `None` here
/// would mean "no alias" and read as the more meaningful contract, and it would make a
/// consumer who forgot `?? name` silently accept every plain import — a false negative on
/// the most ordinary spelling there is, invisible because an ignored requirement only ever
/// removes reports. A copy has no such failure mode and costs one `String`, and it is copied
/// even when nothing was renamed rather than left empty.
#[test]
fn an_imported_name_carries_the_module_it_came_from() {
    assert_eq!(
        symbol_of_use(
            "import { Decimal } from 'decimal.js';\nconst x = Decimal;",
            "Decimal"
        ),
        Some(lanekeep_types::Symbol {
            name: "Decimal".to_owned(),
            exported: Some("Decimal".to_owned()),
            module: Some("decimal.js".to_owned()),
        })
    );
}

/// The shadow pair: the same name, locally declared, carries neither a module nor an
/// exported name — nothing was imported, so there is nothing a module exports it under.
#[test]
fn a_locally_declared_name_carries_no_module() {
    assert_eq!(
        symbol_of_use("class Decimal {}\nconst x = Decimal;", "Decimal"),
        Some(lanekeep_types::Symbol {
            name: "Decimal".to_owned(),
            exported: None,
            module: None,
        })
    );
}

#[test]
fn a_name_nothing_declares_has_no_symbol() {
    assert_eq!(symbol_of_use("const x = missing;", "missing"), None);
}

/// A renamed import carries both names: the alias at the use site, and the name the module
/// exports it under.
///
/// The whole point of the field. `a_renamed_import_s_symbol_name_is_the_local_alias` above
/// pins the first half and passed for the entire life of a `Symbol` that had no second half
/// at all — the resolver's `ImportedName::Named("Decimal")` reached `symbol_at` and was
/// dropped one line later.
#[test]
fn a_renamed_import_carries_the_exported_name_beside_the_alias() {
    assert_eq!(
        symbol_of_use(
            "import { Decimal as Money } from 'decimal.js';\nconst x = Money;",
            "Money"
        ),
        Some(lanekeep_types::Symbol {
            name: "Money".to_owned(),
            exported: Some("Decimal".to_owned()),
            module: Some("decimal.js".to_owned()),
        })
    );
}

/// A default import is exported under the literal name `default`.
///
/// Not the local name, which is chosen freely at the import site and says nothing about the
/// module: `import D from 'm'` and `import Decimal from 'm'` are the same import. `default`
/// is what the module actually exports it as, and Task 4's rule branches on exactly that
/// string to avoid accusing conforming code.
#[test]
fn a_default_import_is_exported_under_the_name_default() {
    assert_eq!(
        symbol_of_use("import Money from 'decimal.js';\nconst x = Money;", "Money"),
        Some(lanekeep_types::Symbol {
            name: "Money".to_owned(),
            exported: Some("default".to_owned()),
            module: Some("decimal.js".to_owned()),
        })
    );
}

/// A namespace import has a module and no exported name at all.
///
/// `import * as d from 'm'` binds the module object, and no single export names it. `None`
/// rather than `"*"`: a sentinel would be a string a comparison could match, and there is
/// nothing here for a name comparison to be right about. This is the discriminating pair for
/// the two tests above — an implementation that always answered `Some` of something, or that
/// defaulted to the use-site name, passes both of them and fails this.
#[test]
fn a_namespace_import_has_a_module_and_no_exported_name() {
    assert_eq!(
        symbol_of_use("import * as d from 'decimal.js';\nconst x = d;", "d"),
        Some(lanekeep_types::Symbol {
            name: "d".to_owned(),
            exported: None,
            module: Some("decimal.js".to_owned()),
        })
    );
}

/// An import specifier may name the export as a string — `import { "Decimal" as D }` — and the
/// exported name is the export's name, not its quoted spelling: a `require` comparing against
/// `Decimal` would otherwise never match it and report conforming code.
#[test]
fn a_string_named_import_specifier_is_exported_without_its_quotes() {
    assert_eq!(
        symbol_of_use(
            "import { \"Decimal\" as D } from 'decimal.js';\nconst x = D;",
            "D"
        ),
        Some(lanekeep_types::Symbol {
            name: "D".to_owned(),
            exported: Some("Decimal".to_owned()),
            module: Some("decimal.js".to_owned()),
        })
    );
}

/// Two runs over one input agree, byte for byte.
///
/// The ordering guarantee's own test shape. Nothing here reads a clock or iterates a hash
/// map, and this is what would notice if that stopped being true.
#[test]
fn two_runs_over_one_input_agree() {
    let source = "import { Decimal } from 'decimal.js';\n\
                  type Amount = number | string;\n\
                  function f(a: Amount, b: Decimal) { const c = parseFloat('1'); return c; }\n";
    let first = format!("{:?}", type_of_use(source, "c"));
    let second = format!("{:?}", type_of_use(source, "c"));
    assert_eq!(first, second);

    let one = format!("{:?}", type_of_last(source, "union_type"));
    let other = format!("{:?}", type_of_last(source, "union_type"));
    assert_eq!(one, other);
}

// --- type parameters on declaration kinds that were not scopes ------------------------
//
// The oracle's half of the resolver fix in `lanekeep-lang-js`. These four kinds carry a
// `type_parameters` field and were not in `SCOPE_KINDS`, so the walk escaped outward and an
// outer alias of the same name answered instead. The result is worse than a missing answer:
// it is a *confident* one, identical in every byte to a declared `number`, with nothing
// anywhere to say a type parameter was passed over.

/// A type parameter is whatever the call site chose, so the oracle says nothing about it.
#[test]
fn a_type_parameter_on_any_declaration_kind_gives_nothing() {
    for source in [
        "interface O<T> { x: T }",
        "type O<T> = { x: T };",
        "abstract class C<T> { abstract x: T }",
        "declare function f<T>(x: T): T;",
    ] {
        assert_eq!(type_of_last(source, "type_annotation"), None, "{source}");
    }
}

/// And it shadows an outer alias, which is the case that used to answer wrongly.
///
/// Distinct from the test above rather than a restatement of it. Without an alias in scope
/// the old behavior produced `Nominal { name: "T", symbol: None }`, which a rule checking a
/// `require` reports; with one it produced `Some(Primitive(Number))`, which a rule checking
/// `forbid` reports. Two different wrong answers, and only the second is visible here.
#[test]
fn a_type_parameter_shadowing_an_alias_does_not_answer_with_the_alias() {
    for source in [
        "type A = number;\ninterface O<A> { x: A }",
        "type A = number;\ntype O<A> = { x: A };",
        "type A = number;\nabstract class C<A> { abstract x: A }",
        "type A = number;\ndeclare function f<A>(x: A): A;",
    ] {
        assert_eq!(type_of_last(source, "type_annotation"), None, "{source}");
    }
}

/// The must-not-move half: with no type parameter shadowing it, the alias still answers.
#[test]
fn without_a_type_parameter_a_member_still_reads_the_outer_alias() {
    for source in [
        "type A = number;\ninterface O { x: A }",
        "type A = number;\ntype O = { x: A };",
        "type A = number;\nabstract class C { abstract x: A }",
    ] {
        assert_eq!(
            type_of_last(source, "type_annotation"),
            Some(Type::Primitive(Primitive::Number)),
            "{source}"
        );
    }
}

/// `function_signature` also carries `parameters`, so making it a scope makes an ambient
/// function's parameters resolvable for the first time.
///
/// A widening beyond the false-positive fix, and a deliberate one: `declare function
/// credit(amount: number)` declares money as a `number` exactly as the non-ambient form
/// does. Asserted here rather than left to be discovered by whoever notices
/// `no-restricted-types` reporting a shape it used to pass over.
#[test]
fn an_ambient_functions_parameter_is_typed() {
    assert_eq!(
        type_of_last("declare function f(a: number): void;", "identifier"),
        Some(Type::Primitive(Primitive::Number))
    );
}

// --- #208: the six carriers that were still not scopes --------------------------------
//
// The oracle's half. Anchored on a `type_annotation` whose text is `A`, never on a
// `: void` — every source below writes `: A` as its return type, so whichever annotation
// is last in the file resolves the name under test. A fixture that lands on `: void`
// asserts nothing, which is the dead row #207 shipped twice.
//
// #208 and the design both say the reproducer is `typeOf(x) == number`. It is not: with
// `method_signature` outside `SCOPE_KINDS` the walk from `x` finds no declaration at all
// and the oracle answers `None`. The confident wrong answer is reached through the
// *annotation*, which is what these tests read.

/// A type parameter is whatever the call site chose, so the oracle says nothing about it.
///
/// Before this commit the walk escaped past `method_signature` to the outer alias and this
/// answered `Some(Primitive(Number))` — identical in every byte to a declared `number`.
#[test]
fn a_type_parameter_on_a_method_signature_kind_gives_nothing() {
    for source in [
        "type A = number;\ninterface I { m<A>(x: A): A }",
        "type A = number;\nabstract class C { abstract m<A>(x: A): A }",
    ] {
        assert_eq!(type_of_last(source, "type_annotation"), None, "{source}");
    }
}

/// The must-not-move half: with nothing shadowing it, the alias still answers.
#[test]
fn without_a_type_parameter_a_method_signature_kind_reads_the_alias() {
    for source in [
        "type A = number;\ninterface I { m(x: A): A }",
        "type A = number;\nabstract class C { abstract m(x: A): A }",
    ] {
        assert_eq!(
            type_of_last(source, "type_annotation"),
            Some(Type::Primitive(Primitive::Number)),
            "{source}"
        );
    }
}

/// The parameter-side widening, which is the half that is a behavior change rather than a
/// bug fix: these kinds carry `parameters`, so their parameters become resolvable for the
/// first time and an annotated one is typed where it used to give nothing.
#[test]
fn a_parameter_of_a_method_signature_kind_is_typed() {
    for source in [
        "interface I { m(a: number): void }",
        "abstract class C { abstract m(a: number): void }",
    ] {
        assert_eq!(
            type_of_use(source, "a"),
            Some(Type::Primitive(Primitive::Number)),
            "{source}"
        );
    }
}

// --- #208's remaining four ------------------------------------------------------------
//
// `: A` as the return type again, and here it is doing more work than above: the four kinds
// spell their result differently — `call_signature` and `construct_signature` wrap it in a
// `type_annotation`, `constructor_type` and `function_type` hold a bare type after `=>` —
// so which node `type_of_last(_, "type_annotation")` lands on differs by kind. Writing `A`
// in both positions makes the assertion the same one either way.

/// A type parameter is whatever the call site chose in these four kinds too, so the oracle
/// says nothing about it — the same *pair* as `method_signature`'s above, one node kind
/// further from anything with a name. Not the same widening: this half is the bug fix, where
/// the walk used to escape to the outer alias and answer confidently. The widening for these
/// kinds is the parameter-side test below.
#[test]
fn a_type_parameter_in_signature_or_type_position_gives_nothing() {
    for source in [
        "type A = number;\ninterface F { <A>(x: A): A }",
        "type A = number;\ninterface F { new <A>(x: A): A }",
        "type A = number;\ntype F = new <A>(x: A) => A;",
        "type A = number;\ntype F = <A>(x: A) => A;",
    ] {
        assert_eq!(type_of_last(source, "type_annotation"), None, "{source}");
    }
}

/// The must-not-move half: with nothing shadowing it, the alias still answers, in each of
/// the four kinds.
#[test]
fn without_a_type_parameter_signature_or_type_position_reads_the_alias() {
    for source in [
        "type A = number;\ninterface F { (x: A): A }",
        "type A = number;\ninterface F { new (x: A): A }",
        "type A = number;\ntype F = new (x: A) => A;",
        "type A = number;\ntype F = (x: A) => A;",
    ] {
        assert_eq!(
            type_of_last(source, "type_annotation"),
            Some(Type::Primitive(Primitive::Number)),
            "{source}"
        );
    }
}

/// The parameter-side widening for these four kinds: each carries `parameters`, so an
/// annotated one is typed where it used to give nothing.
#[test]
fn a_parameter_in_signature_or_type_position_is_typed() {
    for source in [
        "interface F { (a: number): void }",
        "interface F { new (a: number): F }",
        "type F = new (a: number) => F;",
        "type F = (a: number) => void;",
    ] {
        assert_eq!(
            type_of_use(source, "a"),
            Some(Type::Primitive(Primitive::Number)),
            "{source}"
        );
    }
}

/// Without a provider attached, an imported value still has no type.
///
/// The pair for `an_imported_value_has_no_type_yet` above rather than a replacement for it:
/// that test is now specifically the *no-provider* path, and this names the reason so nobody
/// later reads it as "cross-file resolution does not work". An oracle built by
/// `TypeScriptOracle::new` alone opens no files, by construction — there is nothing attached
/// that could.
#[test]
fn an_oracle_with_no_import_resolution_answers_nothing_for_an_import() {
    assert_eq!(
        type_of_use(
            "import { Decimal } from 'm';\nconst y = Decimal;",
            "Decimal"
        ),
        None
    );
}

/// Type the expression whose source text is exactly `text`.
///
/// `type_of_last(_, "member_expression")` cannot address a chain: `nodes` is pre-order, so
/// the outer `a.b.c` is visited before the inner `a.b`, and `rfind` hands back the inner one.
/// Selecting by exact text names the whole expression a test means.
fn type_of_expr(source: &str, text: &str) -> Option<Type> {
    let tree = parse(source);
    let support = TypeScriptSupport::probe(&TypeScript).expect("TypeScript is supported");
    let oracle = TypeScriptOracle::new(&support, &tree, source);
    let found = nodes(&tree)
        .into_iter()
        .find(|node| source.get(node.byte_range()) == Some(text));
    oracle.type_of(found.unwrap_or_else(|| panic!("no node with text `{text}`")))
}

/// A member off a same-file interface is the member's annotated type.
#[test]
fn a_member_off_a_same_file_interface_is_its_annotated_type() {
    assert_eq!(
        type_of_expr(
            "interface Order { amount: number }\nfunction f(o: Order) { return o.amount; }",
            "o.amount"
        ),
        Some(Type::Primitive(Primitive::Number))
    );
}

/// A member off a same-file object-type alias reads the same way.
#[test]
fn a_member_off_a_same_file_object_alias_is_its_annotated_type() {
    assert_eq!(
        type_of_expr(
            "type Order = { amount: bigint };\nfunction f(o: Order) { return o.amount; }",
            "o.amount"
        ),
        Some(Type::Primitive(Primitive::BigInt))
    );
}

/// A public field off a same-file class is its annotated type.
#[test]
fn a_field_off_a_same_file_class_is_its_annotated_type() {
    assert_eq!(
        type_of_expr(
            "class Order { amount: number = 0 }\nfunction f(o: Order) { return o.amount; }",
            "o.amount"
        ),
        Some(Type::Primitive(Primitive::Number))
    );
}

/// An unknown member answers nothing rather than guessing.
#[test]
fn an_unknown_member_answers_nothing() {
    assert_eq!(
        type_of_expr(
            "interface Order { amount: number }\nfunction f(o: Order) { return o.missing; }",
            "o.missing"
        ),
        None
    );
}

/// A member off a base the oracle cannot type answers nothing.
#[test]
fn a_member_off_an_untyped_base_answers_nothing() {
    assert_eq!(
        type_of_expr("function f(o) { return o.amount; }", "o.amount"),
        None
    );
}

/// An optional access is the member type or `undefined`.
#[test]
fn an_optional_access_is_the_member_type_or_undefined() {
    assert_eq!(
        type_of_expr(
            "interface Order { amount: number }\nfunction f(o: Order) { return o?.amount; }",
            "o?.amount"
        ),
        Type::union(vec![
            Type::Primitive(Primitive::Number),
            Type::Primitive(Primitive::Undefined),
        ])
    );
}

/// An optional member is the member type or `undefined`, even accessed with a plain dot.
#[test]
fn an_optional_member_is_the_member_type_or_undefined() {
    assert_eq!(
        type_of_expr(
            "interface Order { amount?: number }\nfunction f(o: Order) { return o.amount; }",
            "o.amount"
        ),
        Type::union(vec![
            Type::Primitive(Primitive::Number),
            Type::Primitive(Primitive::Undefined),
        ])
    );
}

/// A chain reads through several same-file types.
#[test]
fn a_chain_reads_through_same_file_types() {
    assert_eq!(
        type_of_expr(
            "interface Inner { amount: number }\ninterface Outer { inner: Inner }\n\
             function f(o: Outer) { return o.inner.amount; }",
            "o.inner.amount"
        ),
        Some(Type::Primitive(Primitive::Number))
    );
}

/// An optional link taints the whole tail of the chain with `undefined`.
///
/// The `optional_chain` marker sits only on `o?.inner`, but `a?.b.c` short-circuits the whole
/// tail: if `o` is nullish the entire expression is `undefined`, so `.amount` is `number |
/// undefined`, not `number`.
#[test]
fn an_optional_link_taints_the_rest_of_the_chain() {
    assert_eq!(
        type_of_expr(
            "interface Inner { amount: number }\ninterface Outer { inner: Inner }\n\
             function f(o: Outer) { return o?.inner.amount; }",
            "o?.inner.amount"
        ),
        Type::union(vec![
            Type::Primitive(Primitive::Number),
            Type::Primitive(Primitive::Undefined),
        ])
    );
}

/// A string-literal subscript reads a member exactly as a dot access does.
#[test]
fn a_string_literal_subscript_reads_a_member() {
    assert_eq!(
        type_of_expr(
            "interface Order { amount: number }\nfunction f(o: Order) { return o[\"amount\"]; }",
            "o[\"amount\"]"
        ),
        Some(Type::Primitive(Primitive::Number))
    );
}

/// A dynamic subscript answers nothing — the oracle has no element-type representation.
#[test]
fn a_dynamic_subscript_answers_nothing() {
    assert_eq!(
        type_of_expr(
            "interface Order { amount: number }\nfunction f(o: Order, k: string) { return o[k]; }",
            "o[k]"
        ),
        None
    );
}

/// A locally shadowed type name resolves to the shadow, not the module-level declaration.
///
/// The member walk must resolve a base's type name scope-awarely: a top-level `Box` and a
/// `Box` declared inside a function are different types, and answering the module-level one's
/// member for a value typed by the local one is a confident wrong answer.
#[test]
fn a_member_off_a_shadowed_type_reads_the_shadow() {
    assert_eq!(
        type_of_expr(
            "interface Box { value: number }\n\
             function f() {\n\
             \x20 type Box = { value: string };\n\
             \x20 const b: Box = { value: 's' };\n\
             \x20 return b.value;\n\
             }",
            "b.value"
        ),
        Some(Type::Primitive(Primitive::String))
    );
}

/// A member off a receiver annotated `T | undefined` is the member type or `undefined`.
///
/// In type position `undefined` is a `literal_type`, not a bare `undefined` node — the receiver
/// resolves to its one non-nullish arm, and the whole access carries the `| undefined`.
#[test]
fn a_member_off_a_nullable_receiver_is_or_undefined() {
    assert_eq!(
        type_of_expr(
            "interface Order { amount: number }\n\
             function f(o: Order | undefined) { return o.amount; }",
            "o.amount"
        ),
        Type::union(vec![
            Type::Primitive(Primitive::Number),
            Type::Primitive(Primitive::Undefined),
        ])
    );
}

/// A nullable intermediate member taints the tail of the chain with `undefined`.
#[test]
fn a_nullable_intermediate_member_taints_the_tail() {
    assert_eq!(
        type_of_expr(
            "interface Amount { cents: number }\n\
             interface Order { amount: Amount | null }\n\
             function f(o: Order) { return o.amount.cents; }",
            "o.amount.cents"
        ),
        Type::union(vec![
            Type::Primitive(Primitive::Number),
            Type::Primitive(Primitive::Undefined),
        ])
    );
}

/// A member typed as an inline anonymous object is read through: node-based resolution walks
/// the `object_type` directly, so the chain does not need a name at every hop.
#[test]
fn a_chain_reads_through_an_inline_object_member() {
    assert_eq!(
        type_of_expr(
            "interface Outer { inner: { amount: number } }\n\
             function f(o: Outer) { return o.inner.amount; }",
            "o.inner.amount"
        ),
        Some(Type::Primitive(Primitive::Number))
    );
}