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
pub mod config;
pub mod fingerprint;
pub mod graph;
pub mod vartype;
use crate::components::context::config::Config;
use crate::components::context::config::Environment;
use crate::components::context::config::TargetLanguage;
use crate::components::context::graph::Graph;
use crate::components::context::unification_map::UnificationMap;
use crate::components::context::vartype::VarType;
use crate::components::error_message::help_data::HelpData;
use crate::components::language::var::Var;
use crate::components::language::var_function::VarFunction;
use crate::components::language::Lang;
use crate::components::r#type::argument_type::ArgumentType;
use crate::components::r#type::kind::Kind;
use crate::components::r#type::type_system::TypeSystem;
use crate::components::r#type::vector_type::ConstructorCategory;
use crate::components::r#type::Type;
use crate::processes::type_checking::facets;
use crate::processes::type_checking::match_types_to_generic;
use crate::processes::type_checking::type_comparison::reduce_type;
use crate::processes::type_checking::unification_map;
use crate::utils::builder;
use crate::utils::standard_library::not_in_blacklist;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use std::collections::HashSet;
use std::ops::Add;
use std::sync::Arc;
use tap::Pipe;
/// True for the auto-generated names given to anonymous record types
/// (`Record0`, `Record1`, …), as produced by `VarType::push_alias_increment`
/// (`format!("{}{}", TypeCategory::Record, count)`).
fn is_anonymous_record_name(name: &str) -> bool {
name.strip_prefix("Record")
.map(|rest| !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit()))
.unwrap_or(false)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Context {
pub typing_context: VarType,
pub subtypes: Graph<Type>,
/// Registry of user-declared `typeconstructor`s: (name, parameter signature, category).
#[serde(default)]
pub type_constructors: Vec<(String, Vec<Type>, ConstructorCategory)>,
/// Constraints mapping a rigid generic variable name to its interface.
/// Introduced when an interface type appears in parameter position:
/// fn(i: I): R ⇒ i : A with A: I stored here.
#[serde(default)]
pub interface_constraints: HashMap<String, Type>,
/// Counter for generating unique rigid generic variable names.
#[serde(default)]
pub rigid_counter: u64,
/// Flat, whole-program registry of every `type X <- list { ... }` record
/// alias declared anywhere, including inside `mod` bodies. Unlike
/// `typing_context.aliases`, this is never scoped away at a module
/// boundary: R's S3 class system has no module privacy, so transpilation
/// needs the full picture to compute structural supertypes for the class
/// vector (see `record_field_class` callers in `processes::transpiling`).
#[serde(default)]
pub record_aliases: Vec<(String, Type)>,
/// Named type embedding (`embed field: Type`): provenance of every function
/// auto-generated by forwarding/reconstruction, as `(type_name, method_name,
/// source_field_name)`. Used to detect a later explicit definition that
/// collides with an inherited embedded function (E-EMBED-003).
#[serde(default)]
pub embedded_methods: Vec<(String, String, String)>,
/// RFC-TR-031: lines injected at the top of a `Test { ... }` file so the
/// test body can reach `@testable` private members of the enclosing module
/// (e.g. `sq <- Math$.test_sq`). Set while transpiling a module body in a
/// test build; empty otherwise. Not serialised.
#[serde(skip)]
pub test_preamble: Vec<String>,
/// `Self:{ ... }` (generic_constructor.md): the type bound to the
/// enclosing function/method's first parameter, set only while
/// type-checking that function's body. `None` everywhere else, which is
/// what makes `Self` invalid outside a function body.
#[serde(skip)]
pub self_type: Option<Type>,
/// The declared return type of the function whose body is currently being
/// type-checked (audit_type_checking.md C1) — lets `Lang::Return` compare
/// an early `return` against the same target the trailing expression is
/// checked against in `function()`. `None` outside a function body.
#[serde(skip)]
pub expected_return_type: Option<Type>,
/// Inner typing contexts computed while type-checking each `module M { ... }`
/// body, keyed by module name. Populated during type-checking; consumed
/// during transpilation to avoid re-running `typing()` on every module body.
#[serde(skip)]
pub module_inner_contexts: HashMap<String, Arc<Context>>,
/// Cache of fully type-checked modules. Maps module name → its
/// `Type::Module` so that `use Module::*;` can be resolved without
/// re-walking the module path in the variable table. Populated by
/// `eval()` for `Lang::Module` and consumed by `typing()` for
/// `Lang::UseModule`.
#[serde(skip)]
pub processed_modules: HashMap<String, Type>,
/// Set of module names whose body is currently being type-checked.
/// Used to detect circular import chains at the type-checking level.
/// A `Lang::UseModule` targeting a name in this set is a cycle error.
#[serde(skip)]
pub modules_in_progress: HashSet<String>,
/// Registry of `@extern` function declarations: (TypR name, R-side qualified name).
/// When `Option<String>` is `None` the TypR name is used directly as the R call.
#[serde(default)]
pub extern_fns: Vec<(String, Option<String>)>,
/// Registry of `@importFrom` declarations: (TypR function name, "pkg::fn_name").
/// At call sites the transpiler emits `pkg::fn_name(args)` instead of `fn_name(args)`,
/// bypassing TypR's own S3 generic stubs for names like `get`, `map`, `factor`.
#[serde(default)]
pub import_from_fns: Vec<(String, String)>,
/// Names declared signature-only (`@name: T;`), i.e. typed here but
/// implemented in R somewhere else — base R, a package, or hand-written R.
/// Unlike an ordinary `let`, such a name has no TypR body to transpile
/// into `name.<Type>` methods, so shadowing it with a `UseMethod` stub
/// strands whatever R implementation it was declared for. `typr build`
/// reads this to tell the two cases apart when deciding whether a missing
/// `<name>.default` is worth reporting (see `r_name_lint`).
#[serde(default)]
pub signature_fns: Vec<String>,
/// Static vectorizability of user-declared functions, keyed by name:
/// `true` means every declaration seen so far for that name has a body
/// made only of natively-vectorized R operations (see
/// `processes::type_checking::vectorizability`), so a `Vec[N, T]` call
/// site may call it directly instead of wrapping it in `vapply`. Any
/// non-vectorizable overload of the same name downgrades the entry to
/// `false` for good (S3 dispatch at the call site can't tell overloads
/// apart by name alone).
#[serde(default)]
pub vectorizable_fns: Vec<(String, bool)>,
config: Config,
}
/// The canonical sentinel nodes seeded into every subtype `Graph` so the
/// kind-sigil generic categories materialize as intermediate levels of the
/// lattice. Because `is_subtype_raw` already gives `RecordN <: %_ <: Generic
/// <: Any` (a concrete Record is a subtype of a record-kinded `KindedGen`, and
/// any generic is a subtype of the bare `Generic`), seeding one anchor per
/// kind makes every monomorphized record/interface/char/bool/number auto-nest
/// under its `G*` node. These sentinels all answer `has_generic() == true`, so
/// `get_classes` filters them out of generated R `class = c(...)` vectors —
/// they are a compile-time organisation of the hierarchy only.
fn generic_sentinels() -> Vec<Type> {
let h = HelpData::default();
let name = "_".to_string();
vec![
Type::Generic(name.clone(), h.clone()),
Type::KindedGen(Kind::Record, name.clone(), h.clone()),
Type::KindedGen(Kind::Interface, name.clone(), h.clone()),
Type::KindedGen(Kind::String, name.clone(), h.clone()),
Type::KindedGen(Kind::Boolean, name.clone(), h.clone()),
Type::IndexGen(name, h),
]
}
/// A fresh subtype graph pre-seeded with the kind-sigil generic sentinels
/// (see [`generic_sentinels`]). Built against `Context::empty()` since the
/// sentinel ordering only exercises the structural `is_subtype_raw` arms
/// (`(_, Generic)`, `(_, Any)`, the `KindedGen`/`IndexGen` arms) and needs no
/// typing context.
fn seeded_subtype_graph() -> Graph<Type> {
Graph::new().add_types(&generic_sentinels(), &Context::empty())
}
impl Default for Context {
fn default() -> Self {
let config = Config::default();
Context {
config: config.clone(),
typing_context: VarType::from_config(config),
subtypes: seeded_subtype_graph(),
type_constructors: Vec::new(),
interface_constraints: HashMap::new(),
rigid_counter: 0,
record_aliases: Vec::new(),
embedded_methods: Vec::new(),
test_preamble: Vec::new(),
self_type: None,
expected_return_type: None,
extern_fns: Vec::new(),
import_from_fns: Vec::new(),
signature_fns: Vec::new(),
vectorizable_fns: Vec::new(),
module_inner_contexts: HashMap::new(),
processed_modules: HashMap::new(),
modules_in_progress: HashSet::new(),
}
}
}
impl From<Vec<(Lang, Type)>> for Context {
fn from(val: Vec<(Lang, Type)>) -> Self {
let val2: Vec<(Var, Type)> = val
.iter()
.map(|(lan, typ)| (Var::from_language(lan.clone()).unwrap(), typ.clone()))
.collect();
Context {
typing_context: val2.into(),
..Context::default()
}
}
}
impl Context {
pub fn new(types: Vec<(Var, Type)>) -> Context {
Context {
typing_context: types.into(),
..Context::default()
}
}
pub fn empty() -> Self {
Context {
config: Config::default(),
typing_context: VarType::new(),
subtypes: Graph::new(),
type_constructors: Vec::new(),
interface_constraints: HashMap::new(),
rigid_counter: 0,
record_aliases: Vec::new(),
embedded_methods: Vec::new(),
test_preamble: Vec::new(),
self_type: None,
expected_return_type: None,
extern_fns: Vec::new(),
import_from_fns: Vec::new(),
signature_fns: Vec::new(),
vectorizable_fns: Vec::new(),
module_inner_contexts: HashMap::new(),
processed_modules: HashMap::new(),
modules_in_progress: HashSet::new(),
}
}
pub fn is_extern_fn(&self, name: &str) -> bool {
self.extern_fns.iter().any(|(n, _)| n == name)
}
/// Whether `name` was introduced by a signature declaration (`@name: T;`)
/// rather than by a TypR definition with a body.
pub fn is_signature_fn(&self, name: &str) -> bool {
self.signature_fns.iter().any(|n| n == name)
}
pub fn get_extern_r_name(&self, name: &str) -> Option<String> {
self.extern_fns
.iter()
.find(|(n, _)| n == name)
.and_then(|(_, r)| r.clone())
}
pub fn is_import_from_fn(&self, name: &str) -> bool {
self.import_from_fns.iter().any(|(n, _)| n == name)
}
pub fn get_import_from_r_name(&self, name: &str) -> Option<String> {
self.import_from_fns
.iter()
.find(|(n, _)| n == name)
.map(|(_, r)| r.clone())
}
/// Record whether a user function declaration has a natively-vectorizable
/// body. A name is only vectorizable while *every* declaration seen for it
/// is — one non-vectorizable overload downgrades the entry permanently.
pub fn register_vectorizable_fn(mut self, name: &str, is_vectorizable: bool) -> Self {
match self.vectorizable_fns.iter_mut().find(|(n, _)| n == name) {
Some(entry) => entry.1 = entry.1 && is_vectorizable,
None => self.vectorizable_fns.push((name.to_string(), is_vectorizable)),
}
self
}
pub fn is_vectorizable_fn(&self, name: &str) -> bool {
self.vectorizable_fns.iter().any(|(n, v)| n == name && *v)
}
pub fn set_config(self, config: Config) -> Self {
Self { config, ..self }
}
pub fn set_as_module_context(self) -> Context {
Self {
config: self.config.set_as_module(),
..self
}
}
pub fn set_test_mode(self, val: bool) -> Context {
Self {
config: self.config.set_test_mode(val),
..self
}
}
pub fn get_test_mode(&self) -> bool {
self.config.test_mode
}
pub fn set_checked_mode(self, val: bool) -> Context {
Self {
config: self.config.set_checked_mode(val),
..self
}
}
pub fn get_checked_mode(&self) -> bool {
self.config.checked_mode
}
pub fn set_test_preamble(self, lines: Vec<String>) -> Context {
Self {
test_preamble: lines,
..self
}
}
/// `Self:{ ... }` (generic_constructor.md §4.1): bind/clear the type
/// denoted by `Self` for the duration of typing a function body.
pub fn set_self_type(self, self_type: Option<Type>) -> Context {
Self { self_type, ..self }
}
/// Bind/clear the declared return type of the function whose body is
/// currently being type-checked (audit_type_checking.md C1).
pub fn set_expected_return_type(self, expected_return_type: Option<Type>) -> Context {
Self {
expected_return_type,
..self
}
}
pub fn get_expected_return_type(&self) -> Option<Type> {
self.expected_return_type.clone()
}
pub fn store_module_inner_context(mut self, name: &str, inner: &Context) -> Self {
// `inner` is the module body's final context, which inherits (and thus
// still carries) every `module_inner_contexts` entry that was already
// present in the *ambient* context before this module started (nested
// sibling modules typed earlier in the same file/enclosing module).
// Storing `inner` as-is would re-embed all of those already-stored
// snapshots inside this module's own boxed snapshot; since `Context`
// is cloned pervasively throughout type-checking, and every module
// boundary would repeat this, the nesting depth (and thus clone cost)
// grows exponentially with the number of `mod` declarations. Keep
// only the entries genuinely *new* to this module's own body (i.e.
// not already known to the ambient context) — those are exactly the
// modules declared/nested directly within this one.
let new_entries: HashMap<String, Arc<Context>> = inner
.module_inner_contexts
.iter()
.filter(|(k, _)| !self.module_inner_contexts.contains_key(k.as_str()))
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
let mut trimmed = inner.clone();
trimmed.module_inner_contexts = new_entries;
self.module_inner_contexts.insert(name.to_string(), Arc::new(trimmed));
self
}
pub fn get_module_inner_context(&self, name: &str) -> Option<&Context> {
self.module_inner_contexts.get(name).map(|b| b.as_ref())
}
/// Mark a module as currently being type-checked. Returns the updated
/// context with `name` added to `modules_in_progress`.
pub fn mark_module_in_progress(self, name: &str) -> Self {
let mut set = self.modules_in_progress.clone();
set.insert(name.to_string());
Self {
modules_in_progress: set,
..self
}
}
/// Remove a module from the in-progress set after its body has been
/// fully type-checked.
pub fn unmark_module_in_progress(self, name: &str) -> Self {
let mut set = self.modules_in_progress.clone();
set.remove(name);
Self {
modules_in_progress: set,
..self
}
}
/// True when `name` is currently being type-checked (its body is on the
/// call stack). A `use {name}::*;` encountered while this returns `true`
/// is a circular dependency.
pub fn is_module_in_progress(&self, name: &str) -> bool {
self.modules_in_progress.contains(name)
}
/// Register `module_type` in the processed-module cache so that
/// subsequent `use {name}::*;` directives can resolve it without
/// walking the full variable-path chain.
pub fn cache_processed_module(self, name: &str, module_type: Type) -> Self {
let mut map = self.processed_modules.clone();
map.insert(name.to_string(), module_type);
Self {
processed_modules: map,
..self
}
}
/// Look up a previously cached module by name. Returns `Some(module_type)`
/// when `name` has already been fully type-checked in this session.
pub fn get_processed_module(&self, name: &str) -> Option<&Type> {
self.processed_modules.get(name)
}
pub fn set_in_module_body(self) -> Self {
Self {
config: self.config.set_in_module_body(true),
..self
}
}
pub fn is_in_module_body(&self) -> bool {
self.config.in_module_body
}
/// See `Config::in_loop` — set while type-checking the body of a
/// `Loop`/`WhileLoop`/`ForLoop` so `break`/`next` inside it are valid.
pub fn set_in_loop(self, val: bool) -> Self {
Self {
config: self.config.set_in_loop(val),
..self
}
}
pub fn is_in_loop(&self) -> bool {
self.config.in_loop
}
/// Retourne un nouveau Context avec le Graph de sous-typage mis à jour
pub fn with_subtypes(self, subtypes: Graph<Type>) -> Self {
Self { subtypes, ..self }
}
pub fn get_members(&self) -> Vec<(Var, Type)> {
self.typing_context
.variables()
.chain(self.aliases())
.cloned()
.collect::<Vec<_>>()
}
pub fn variable_exist(&self, var: Var) -> Option<Var> {
self.typing_context.variable_exist(var, self)
}
pub fn get_type_from_variable(&self, var: &Var) -> Result<Type, String> {
let res = self
.typing_context
.entries_named(&var.get_name())
.into_iter()
.flat_map(|(var2, typ)| {
let conditions =
(var.is_opaque == var2.is_opaque) && var.related_type.is_subtype(&var2.related_type, self).0;
if conditions {
Some(typ)
} else {
None
}
})
.reduce(|acc, x| if x.is_subtype(&acc, self).0 { x } else { acc });
match res {
Some(typ) => Ok(typ),
// Every call site discards this message via `.ok()`/`unwrap_or_else`,
// so `display_typing_context()` (formats ~1700 stdlib+user entries)
// is never actually read — skip it rather than pay it on every
// speculative lookup (see project_typechecking_optimization memory).
_ => Err(format!("Didn't find {} in the context", var.get_name())),
}
}
pub fn get_types_from_name(&self, name: &str) -> Vec<Type> {
self.typing_context
.entries_named(name)
.into_iter()
.map(|(_, typ)| typ)
.collect()
}
pub fn get_type_from_aliases(&self, var: &Var) -> Option<Type> {
self.aliases()
.flat_map(|(var2, type_)| {
let conditions = (var.name == var2.name)
&& (var.is_opaque == var2.is_opaque)
&& var.related_type.is_subtype(&var2.related_type, self).0;
if conditions {
Some(type_.clone())
} else {
None
}
})
.next()
}
/// Search every module currently in scope (declared via `module M { ... }`
/// somewhere visible, whether or not any of its members were ever brought
/// in via `use`) for a public alias named `name`. Returns the module's
/// name on a hit — used to tell "genuinely undefined alias" apart from
/// "exists, but this file never imported it" so the error can point at
/// the fix (`use M::Name;`) instead of just saying "not defined".
pub fn find_alias_source_module(&self, name: &str) -> Option<String> {
self.variables().find_map(|(var, typ)| {
let module_type = typ.clone().to_module_type().ok()?;
module_type
.get_aliases()
.iter()
.any(|(alias_var, _)| alias_var.get_name() == name)
.then(|| var.get_name())
})
}
/// Same idea as `find_alias_source_module`, but for ordinary names
/// (variables and functions) rather than type aliases. Scans every
/// module currently in scope for a member named `name`, checking public
/// members first, then private ones — returns `(module_name,
/// is_public)` on a hit. A private hit still points the error at
/// `use M::name;` (per the fix this supports): the member exists and
/// this is where it lives, even though that particular `use` will itself
/// fail with `PrivateImport` until the declaration gains `@pub`/`@export`.
pub fn find_variable_source_module(&self, name: &str) -> Option<(String, bool)> {
self.variables().find_map(|(var, typ)| {
let module_type = typ.clone().to_module_type().ok()?;
if module_type.is_public_member(name) {
Some((var.get_name(), true))
} else if module_type.has_private_member(name) {
Some((var.get_name(), false))
} else {
None
}
})
}
fn is_matching_alias(&self, var1: &Var, var2: &Var) -> bool {
var1.name == var2.name
}
pub fn get_matching_alias_signature(&self, var: &Var) -> Option<(Type, Vec<Type>)> {
self.aliases()
.find(|(var2, _)| self.is_matching_alias(var, var2))
.map(|(var2, target_type)| {
if var2.is_opaque() {
(var2.clone().to_alias_type(), vec![])
} else if let Type::Params(types, _) = var2.get_type() {
(target_type.clone(), types.clone())
} else {
panic!("The related type is not Params([...])");
}
})
// Module-internal record aliases are dropped from `aliases()` at
// the module boundary for encapsulation, but their names still
// appear inside hoisted structural types and exported signatures.
// `record_aliases` is the whole-program record registry kept for
// codegen (see `merge_record_aliases`) — resolve through it so
// structural subtype checks don't collapse such names to `Any`.
.or_else(|| {
self.record_aliases
.iter()
.find(|(name, _)| *name == var.get_name())
.map(|(_, typ)| (typ.clone(), vec![]))
})
}
pub fn variables(&self) -> impl Iterator<Item = &(Var, Type)> + '_ {
self.typing_context.variables()
}
pub fn aliases(&self) -> impl Iterator<Item = &(Var, Type)> + '_ {
self.typing_context.aliases()
}
/// Generate a fresh rigid generic variable name (immutable builder pattern).
pub fn fresh_rigid_name(self) -> (String, Self) {
let name = format!("__rigid_{}", self.rigid_counter);
(
name,
Self {
rigid_counter: self.rigid_counter + 1,
..self
},
)
}
/// Register a constraint: rigid variable → interface type.
pub fn add_interface_constraint(mut self, rigid_name: String, interface: Type) -> Context {
self.interface_constraints.insert(rigid_name, interface);
self
}
/// Look up the interface constraint for a rigid variable.
pub fn get_interface_constraint(&self, name: &str) -> Option<&Type> {
self.interface_constraints.get(name)
}
/// Check if a name is a constrained rigid variable.
pub fn is_rigid_constrained(&self, name: &str) -> bool {
self.interface_constraints.contains_key(name)
}
pub fn push_var_type(self, lang: Var, typ: Type, context: &Context) -> Context {
let reduced_type = typ.reduce(context);
let types = reduced_type.extract_types();
let new_subtypes = self.subtypes.add_types(&types, context);
let var_type = self
.typing_context
.pipe(|vt| {
if reduced_type.is_interface() && lang.is_variable() {
vt.push_interface(lang.clone(), reduced_type, typ.clone(), context)
} else {
vt.push_var_type(&[(lang.clone(), typ.clone())])
}
})
.push_types(&types);
Context {
typing_context: var_type,
subtypes: new_subtypes,
..self
}
}
pub fn replace_or_push_var_type(self, lang: Var, typ: Type, context: &Context) -> Context {
let types = typ.reduce(context).extract_types();
let var_type = self
.typing_context
.clone()
.replace_or_push_var_type(&[(lang.clone(), typ.clone())])
.push_types(&types);
let new_subtypes = self.subtypes.add_types(&types, context);
Context {
typing_context: var_type,
subtypes: new_subtypes,
..self
}
}
// Remove variables from the context
// For removing added variables for evaluating a function's body
pub fn remove_vars(self, vars: &[Var]) -> Context {
Context {
typing_context: self.typing_context.remove_vars(vars),
..self
}
}
pub fn push_types(self, types: &[Type]) -> Self {
// The subtype graph is the whole-program registry the transpiler
// walks to compute class chains (`get_classes`): every registered
// type must be a node there, or values annotated with it lose their
// structural supertype classes at runtime dispatch.
let new_subtypes = self.subtypes.clone().add_types(types, &self);
Self {
typing_context: self.typing_context.clone().push_types(types),
subtypes: new_subtypes,
..self
}
}
/// Hoists auto-generated type-alias registrations from an inner scope's
/// context (function body, module body) into this one — see
/// `VarType::hoist_aliases`. The hoisted types are also added to the
/// subtype graph so structural supertype lookups (S3 class chains)
/// keep working outside the scope that registered them.
pub fn hoist_aliases(self, inner: &Context) -> Self {
let hoisted_types: Vec<Type> = self
.typing_context
.hoisted_alias_pairs(&inner.typing_context)
.into_iter()
.map(|(_, typ)| typ)
.collect();
let new_subtypes = self.subtypes.clone().add_types(&hoisted_types, &self);
Self {
typing_context: self.typing_context.clone().hoist_aliases(&inner.typing_context),
subtypes: new_subtypes,
..self
}
}
pub fn get_type_from_existing_variable(&self, var: Var) -> Type {
if let Type::UnknownFunction(_) = var.get_type() {
var.get_type()
} else {
self.typing_context
.variables()
.find(|(v, _)| var.match_with(v, self))
.map(|(_, ty)| ty)
// Return Any type instead of panicking if variable not found
.unwrap_or(&Type::Any(var.get_help_data()))
.clone()
}
}
pub fn get_true_variable(&self, var: &Var) -> Var {
let res = self
.typing_context
.variables()
.find(|(v, _)| var.match_with(v, self))
.map(|(v, _)| v);
match res {
Some(vari) => vari.clone(),
_ => {
// Return the variable with UnknownFunction type if it's a standard function
// Otherwise return with Any type to allow error collection
if self.is_an_untyped_function(&var.get_name()) {
var.clone().set_type(Type::UnknownFunction(var.get_help_data()))
} else {
var.clone().set_type(Type::Any(var.get_help_data()))
}
}
}
}
fn is_a_standard_function(&self, name: &str) -> bool {
!self.typing_context.name_exists_outside_of_std(name)
}
pub fn is_an_untyped_function(&self, name: &str) -> bool {
self.is_a_standard_function(name)
}
/// Step â‘¢ (unification_arrays.md): does `t` denote an array with the
/// bare-atomic-vector runtime representation? See
/// `VarType::atomic_array_elem` — the single representation predicate.
pub fn atomic_array_elem(&self, t: &Type) -> Option<Type> {
self.typing_context.atomic_array_elem(t)
}
pub fn get_class(&self, t: &Type) -> String {
// For a named alias whose underlying type is a record or array, return the alias
// name directly. push_types may have also registered the same underlying type with
// an auto-generated "Record0"/"Array0" name; searching aliases by type value would
// find that first (insertion-order) and return the wrong name.
if let Type::Alias(name, _, false, _) = t {
if let Some((_, underlying)) = self.aliases().find(|(v, _)| v.get_name() == *name) {
if matches!(underlying, Type::Record(_, _) | Type::Vec(_, _, _, _)) {
return "'".to_string() + name + "'";
}
}
}
let reduced = t.reduce(self);
if matches!(reduced, Type::Any(_)) {
if let Type::Alias(name, _, _, _) = t {
return "'".to_string() + name + "'";
}
}
self.typing_context.get_class(&reduced)
}
pub fn get_class_unquoted(&self, t: &Type) -> String {
// Same rationale as get_class: bypass the record/array alias search for named aliases.
if let Type::Alias(name, _, false, _) = t {
if let Some((_, underlying)) = self.aliases().find(|(v, _)| v.get_name() == *name) {
if matches!(underlying, Type::Record(_, _) | Type::Vec(_, _, _, _)) {
return name.clone();
}
}
}
let reduced = t.reduce(self);
if matches!(reduced, Type::Any(_)) {
if let Type::Alias(name, _, _, _) = t {
return name.clone();
}
}
self.typing_context.get_class_unquoted(&reduced)
}
pub fn module_aliases(&self) -> Vec<(Var, Type)> {
self.variables()
.flat_map(|(_, typ)| typ.clone().to_module_type())
.flat_map(|module| module.get_aliases())
.collect()
}
pub fn get_type_anotations(&self) -> String {
self.aliases()
.chain(
[
(Var::from_name("Integer"), builder::integer_type_default()),
(Var::from_name("Character"), builder::character_type_default()),
(Var::from_name("Number"), builder::number_type()),
(Var::from_name("Boolean"), builder::boolean_type()),
]
.iter(),
)
.cloned()
.chain(self.module_aliases())
.filter(|(_, typ)| typ.clone().to_module_type().is_err())
// Records that have a user-given alias are excluded: their `as.X` cast
// is emitted by the inline constructor/validator pipeline. Anonymous
// records (auto-named `Record0`, `Record1`, …) have no constructor, so
// they still need their `as.RecordN` annotation generated here.
.filter(|(var, typ)| !matches!(typ, Type::Record(_, _)) || is_anonymous_record_name(&var.get_name()))
// Aliases whose underlying type still mentions an unresolved generic
// (e.g. `type Animator<%T> <- %T & list { ... }`) have no single
// fixed runtime class — there's no monomorphization, so a static
// `as.Animator` cast can't be generated. Without this, get_class
// panics trying to render `%T` as an R class name.
.filter(|(_, typ)| !typ.has_generic())
.map(|(var, typ)| (typ, var.get_name()))
.map(|(typ, name)| {
let name0 = if ["Integer", "Character", "Boolean", "Number"].iter().any(|x| name == *x) {
format!("'{}', ", name)
} else {
Default::default()
};
let class_str = self.get_class(&typ);
let prefix = if name0.is_empty() && class_str != format!("'{}'", name) {
format!("'{}', ", name)
} else {
name0
};
format!(
"as.{} <- function(x) x |> struct(c({}{}, {}))",
name,
prefix,
class_str,
self.get_classes(&typ).unwrap()
)
})
.collect::<Vec<_>>()
.join("\n")
}
pub fn get_type_anotation(&self, t: &Type) -> String {
self.typing_context.get_type_anotation(t)
}
pub fn get_type_anotation_no_parentheses(&self, t: &Type) -> String {
self.typing_context.get_type_anotation_no_parentheses(t)
}
/// Does `name` resolve (through alias hops) to the stdlib `Foreign<T>`
/// alias? See `VarType::resolves_to_foreign` / `get_type_anotation` for
/// the rationale (soundness_transpilation.md Phase D).
pub fn resolves_to_foreign_alias(&self, name: &str) -> bool {
self.typing_context.resolves_to_foreign(name)
}
pub fn get_classes(&self, t: &Type) -> Option<String> {
let mut classes: Vec<String> = self
.subtypes
.get_supertypes(t, self)
.iter()
.filter(|typ| (*typ).clone().to_module_type().is_err())
.filter(|typ| !typ.is_empty())
// A supertype that still mentions an unresolved generic (e.g. a
// record-kinded `%T` picked up structurally from a generic alias
// like `Animator<%T> <- %T & list {...}`) has no R class name —
// it's a compile-time-only constraint, never render it.
.filter(|typ| !typ.has_generic())
.map(|typ| self.get_class(typ))
.collect();
// A record's own class chain gets interface names injected ad hoc
// where its constructor is generated (transpiling/mod.rs, "Interfaces
// as classes"), keyed on structural interface satisfaction. Array
// aliases (`ArrayN`) never went through an equivalent step: an array
// of `Point` never gained `ArrayK` (registered for `[N, Eq]`) in its
// own class chain, even though `Point` satisfies `Eq` — so a function
// whose first param is `[N, Eq]` had no runtime class to dispatch on
// for a real `[N, Point]` value. Mirror the record injection here,
// generically, for any array whose element structurally satisfies
// another registered array's (pure-interface) element type.
if let Type::Vec(_, _, elem, _) = t {
let mut iface_array_classes: Vec<String> = self
.aliases()
.filter_map(|(_, other_typ)| match &other_typ {
Type::Vec(_, _, other_elem, _)
if facets::interface_facet(self, other_elem).is_some()
&& elem.is_subtype_raw(other_elem, self) =>
{
Some(self.get_class(&other_typ))
}
_ => None,
})
.filter(|cls| !classes.contains(cls))
.collect();
iface_array_classes.sort();
iface_array_classes.dedup();
classes.extend(iface_array_classes);
}
let res = classes.join(", ");
if res.is_empty() {
Some("'None'".to_string())
} else {
Some(res)
}
}
pub fn get_functions(&self, var1: Var) -> Vec<(Var, Type)> {
self.typing_context
.variables()
.filter(|(var2, typ)| {
let reduced_type1 = var1.get_type().reduce(self);
let reduced_type2 = var2.get_type().reduce(self);
var1.get_name() == var2.get_name()
&& typ.is_function()
&& reduced_type1.is_subtype(&reduced_type2, self).0
})
.cloned()
.collect()
}
pub fn get_all_generic_functions(&self) -> Vec<(Var, Type)> {
let res = self
.typing_context
.variables()
.filter(|(_, typ)| typ.is_function())
.filter(|(var, _)| not_in_blacklist(&var.get_name()))
.filter(|(var, _)| !var.get_type().is_any())
// `@extern`/`@importFrom` names call an existing R function
// directly by (possibly package-qualified) name — never through
// `UseMethod` dispatch. Emitting the standard `name <- function(x,
// ...) UseMethod('name', x)` stub for them here would shadow the
// real R function at exactly the call site meant to reach it (the
// `nlevels` bug's shape, see the std.R hard rule in CLAUDE.md),
// discovered while wiring up the Phase D interop matrix
// (soundness_transpilation.md) for a bare `@extern base::readRDS`.
.filter(|(var, _)| !self.is_extern_fn(&var.get_name()))
.filter(|(var, _)| !self.is_import_from_fn(&var.get_name()))
.collect::<HashSet<_>>();
let mut result: Vec<(Var, Type)> = res
.iter()
.map(|(var, typ)| (var.clone().add_backticks_if_percent(), typ.clone()))
.collect();
// Stable order: the list is rendered into generic_functions.R, which
// must not reshuffle between builds (HashSet iteration is random).
result.sort_by_key(|(var, _)| var.get_name());
result
}
pub fn get_first_matching_function(&self, var1: Var) -> Type {
let res = self.typing_context.variables().find(|(var2, typ)| {
let reduced_type1 = var1.get_type().reduce(self);
let reduced_type2 = var2.get_type().reduce(self);
var1.get_name() == var2.get_name()
&& typ.is_function()
&& (reduced_type1.is_subtype(&reduced_type2, self).0 || reduced_type1.is_upperrank_of(&reduced_type2))
});
if let Some(res) = res {
res.1.clone()
} else {
self.typing_context
.standard_library()
.iter()
.find(|(var2, _)| var2.get_name() == var1.get_name())
.unwrap_or_else(|| {
panic!(
"Can't find var {} in the context:\n {}",
var1,
self.display_typing_context()
)
})
.1
.clone()
}
}
pub fn get_matching_typed_functions(&self, var1: Var) -> Vec<Type> {
self.typing_context
.variables()
.filter(|(var2, typ)| {
let reduced_type1 = var1.get_type().reduce(self);
let reduced_type2 = var2.get_type().reduce(self);
var1.get_name() == var2.get_name()
&& typ.is_function()
&& (reduced_type1.is_subtype(&reduced_type2, self).0
|| reduced_type1.is_upperrank_of(&reduced_type2))
})
.map(|(_, typ)| typ.clone())
.collect::<Vec<_>>()
}
pub fn get_matching_untyped_functions(&self, var: Var) -> Result<Vec<Type>, String> {
let name1 = var.get_name();
let std_lib = self.typing_context.standard_library();
let res = std_lib
.iter()
.find(|(var2, _)| var2.get_name() == name1)
.map(|(_, typ)| typ);
match res {
Some(val) => Ok(vec![val.clone()]),
_ => Err(format!(
"Can't find var {} in the context:\n {}",
var,
self.display_typing_context()
)),
}
}
pub fn get_matching_functions(&self, var: Var) -> Result<Vec<Type>, String> {
let res = self.get_matching_typed_functions(var.clone());
if res.is_empty() {
self.get_matching_untyped_functions(var)
} else {
Ok(res)
}
}
pub fn get_type_from_class(&self, class: &str) -> Type {
self.typing_context.get_type_from_class(class)
}
pub fn add_arg_types(&self, params: &[ArgumentType]) -> Context {
let param_types = params
.iter()
.map(|arg_typ| reduce_type(self, &arg_typ.get_type()).for_var())
.map(|typ| match typ.to_owned() {
Type::Function(typs, _, _) => {
if !typs.is_empty() {
typs[0].get_type()
} else {
typ
}
}
t => t,
})
.collect::<Vec<_>>();
params
.iter()
.zip(param_types.clone())
.map(|(arg_typ, par_typ): (&ArgumentType, Type)| {
(
Var::from_name(&arg_typ.get_argument_str()).set_type(reduce_type(self, &par_typ)),
reduce_type(self, &arg_typ.get_type()),
)
})
.fold(self.clone(), |cont: Context, (var, typ): (Var, Type)| {
cont.clone().push_var_type(var, typ, &cont)
})
}
pub fn set_environment(&self, e: Environment) -> Context {
Context {
config: self.config.set_environment(e),
..self.clone()
}
}
pub fn display_typing_context(&self) -> String {
let res = self
.variables()
.chain(self.aliases())
.map(|(var, typ)| format!("{} ==> {}", var, typ))
.collect::<Vec<_>>()
.join("\n");
format!("CONTEXT:\n{}", res)
}
pub fn error(&self, msg: String) -> String {
format!("{}{}", msg, self.display_typing_context())
}
pub fn push_alias(self, alias_name: String, typ: Type) -> Self {
Context {
typing_context: self.typing_context.push_alias(alias_name, typ),
..self
}
}
/// Register a user-declared `typeconstructor` in the registry.
pub fn push_type_constructor(self, name: String, parameters: Vec<Type>, category: ConstructorCategory) -> Self {
let mut type_constructors = self.type_constructors.clone();
// Last declaration wins: drop any previous entry with the same name.
type_constructors.retain(|(n, _, _)| n != &name);
type_constructors.push((name, parameters, category));
Context {
type_constructors,
..self
}
}
/// Look up a declared `typeconstructor` by name.
pub fn get_type_constructor(&self, name: &str) -> Option<&(String, Vec<Type>, ConstructorCategory)> {
self.type_constructors.iter().find(|(n, _, _)| n == name)
}
/// Register a `type X <- list { ... }` record alias in the whole-program
/// registry, regardless of the current module scope. No-op for non-record
/// aliases. Last declaration for a given name wins.
pub fn push_record_alias(self, name: String, typ: Type) -> Self {
if !matches!(typ, Type::Record(_, _)) {
return self;
}
let mut record_aliases = self.record_aliases.clone();
record_aliases.retain(|(n, _)| n != &name);
record_aliases.push((name, typ));
Context { record_aliases, ..self }
}
/// Merge another context's whole-program record-alias registry into this
/// one. Used at module boundaries, where the rest of the inner typing
/// context is intentionally discarded for encapsulation but this registry
/// must still bubble up (see `Lang::Module` in `processes::type_checking`).
pub fn merge_record_aliases(self, other: &Context) -> Self {
let mut record_aliases = self.record_aliases.clone();
for (name, typ) in &other.record_aliases {
if !record_aliases.iter().any(|(n, _)| n == name) {
record_aliases.push((name.clone(), typ.clone()));
}
}
Context { record_aliases, ..self }
}
/// Record that `method_name` on `type_name` was auto-generated by named type
/// embedding (`embed field: Type`), forwarded from `field_name`. See
/// `processes::type_checking::embedding`.
pub fn push_embedded_method(self, type_name: String, method_name: String, field_name: String) -> Self {
let mut embedded_methods = self.embedded_methods.clone();
embedded_methods.push((type_name, method_name, field_name));
Context {
embedded_methods,
..self
}
}
/// If `method_name` on `type_name` was inherited via named type embedding,
/// return the source field name it was forwarded from.
pub fn get_embedded_method(&self, type_name: &str, method_name: &str) -> Option<String> {
self.embedded_methods
.iter()
.find(|(t, m, _)| t == type_name && m == method_name)
.map(|(_, _, field)| field.clone())
}
pub fn push_alias2(self, alias_var: Var, typ: Type) -> Self {
Context {
typing_context: self.typing_context.push_alias2(alias_var, typ),
..self
}
}
pub fn in_a_project(&self) -> bool {
self.config.environment == Environment::Project
}
pub fn get_unification_map(&self, entered_types: &[Type], param_types: &[Type]) -> Option<UnificationMap> {
let res = entered_types
.iter()
.zip(param_types.iter())
.map(|(val_typ, par_typ)| match_types_to_generic(self, &val_typ.clone(), par_typ))
.collect::<Option<Vec<_>>>();
res.map(|vec| vec.iter().flatten().cloned().collect::<Vec<_>>())
.and_then(UnificationMap::try_new)
}
fn s3_type_definition(&self, var: &Var, typ: &Type) -> String {
let first_part = format!("{} <- function(x) x |> ", var.get_name());
match typ {
Type::RClass(v, _) => format!(
"{} struct(c({}))",
first_part,
v.iter().cloned().collect::<Vec<_>>().join(", ")
),
_ => {
let class = if typ.is_primitive() {
format!("'{}'", var.get_name())
} else {
self.get_class(typ)
};
format!("{} struct(c({}))", first_part, class)
}
}
}
fn get_primitive_type_definition(&self) -> Vec<String> {
let primitives = [
("Integer", builder::integer_type_default()),
("Character", builder::character_type_default()),
("Number", builder::number_type()),
("Boolean", builder::boolean_type()),
];
let new_context = self
.clone()
.push_types(&primitives.iter().map(|(_, typ)| typ).cloned().collect::<Vec<_>>());
primitives
.iter()
.map(|(name, prim)| {
(
name,
new_context.get_classes(prim).unwrap(),
new_context.get_class(prim),
)
})
.map(|(name, cls, cl)| format!("{} <- function(x) x |> struct(c({}, {}))", name, cls, cl))
.collect::<Vec<_>>()
}
pub fn get_related_functions(&self, typ: &Type, functions: &VarFunction) -> Vec<Lang> {
let names = self.typing_context.get_related_functions(typ);
functions.get_bodies(&names)
}
pub fn get_functions_from_type(&self, typ: &Type) -> Vec<(Var, Type)> {
// `var.get_type()` (the parser-set "related type" marking a function as
// a dispatchable method, e.g. `let animate <- fn(self: Circle, …)`) is
// the primary signal, matched either exactly or via reduced forms — a
// caller may hold a structurally-identical but alias-stripped type
// (e.g. an array literal's element type, which `typing_container`
// reduces away from its alias for homogeneity checking — see
// `[Object]`/`[Circle]` array-covariance).
let reduced_typ = reduce_type(self, typ);
self.variables()
.filter(|&(var, typ2)| {
if !typ2.is_function() {
return false;
}
if var.get_type() == *typ || reduce_type(self, &var.get_type()) == reduced_typ {
return true;
}
// Fallback: `var.get_type()` comes back `Empty` for a function
// re-imported across a module boundary — `Lang::Module`'s
// `pub_arg_types` export rebuilds a fresh `Var` from just the
// exported name, losing the parser's related-type marker even
// though the function itself is a perfectly good method.
// The function's own declared first parameter can't be lost
// this way, so use it as the structural anchor instead:
// interface satisfaction in TypR is meant to be purely
// structural, not keyed on a bookkeeping field surviving a
// module re-export.
typ2.get_first_parameter()
.is_some_and(|p| p == *typ || reduce_type(self, &p) == reduced_typ)
})
.cloned()
.collect()
}
pub fn get_functions_from_name(&self, name: &str) -> Vec<(Var, Type)> {
self.typing_context
.entries_named(name)
.into_iter()
.filter(|(_, typ2)| typ2.is_function())
.collect()
}
pub fn get_type_definition(&self, _functions: &VarFunction) -> String {
match self.get_target_language() {
TargetLanguage::R => self
.typing_context
.aliases
.iter()
.map(|(var, typ)| self.s3_type_definition(var, typ))
.chain(self.get_primitive_type_definition().iter().cloned())
.collect::<Vec<_>>()
.join("\n"),
TargetLanguage::JS => {
todo!();
}
}
}
pub fn update_variable(self, var: Var) -> Self {
Self {
typing_context: self.typing_context.update_variable(var),
..self
}
}
pub fn set_target_language(self, language: TargetLanguage) -> Self {
Self {
config: self.config.set_target_language(language),
typing_context: self.typing_context.source(language),
..self
}
}
pub fn set_default_var_types(self) -> Self {
Self {
typing_context: self.typing_context.set_default_var_types(),
..self
}
}
pub fn get_target_language(&self) -> TargetLanguage {
self.config.get_target_language()
}
pub fn set_new_aliase_signature(self, alias: &str, related_type: Type) -> Self {
let alias = Var::from_type(alias.parse::<Type>().unwrap()).unwrap();
self.clone().push_alias2(alias, related_type)
}
pub fn extract_module_as_vartype(&self, module_name: &str) -> Self {
let typ = self
.get_type_from_variable(&Var::from_name(module_name))
.expect("The module name was not found");
let empty_context = Context::default();
let new_context = match typ.clone() {
Type::Module(args, _, _) => {
args.iter()
.rev()
.map(|arg_type| (Var::try_from(arg_type.0.clone()).unwrap(), arg_type.1.clone())) //TODO: Differenciate between pushing variable and
//aliases
.fold(empty_context.clone(), |acc, (var, typ)| {
acc.clone().push_var_type(var, typ, &acc)
})
}
_ => panic!("{} is not a module", module_name),
};
new_context
.clone()
.push_var_type(Var::from_name(module_name), typ, &new_context)
}
pub fn get_vartype(&self) -> VarType {
self.clone().typing_context
}
pub fn get_environment(&self) -> Environment {
self.config.environment
}
pub fn extend_typing_context(self, var_types: VarType) -> Self {
Self {
typing_context: self.typing_context + var_types,
..self
}
}
}
impl Add for Context {
type Output = Self;
fn add(self, other: Self) -> Self::Output {
let mut type_constructors = self.type_constructors;
for (name, params, cat) in other.type_constructors {
type_constructors.retain(|(n, _, _)| n != &name);
type_constructors.push((name, params, cat));
}
let mut interface_constraints = self.interface_constraints;
interface_constraints.extend(other.interface_constraints);
let rigid_counter = self.rigid_counter.max(other.rigid_counter);
let mut test_preamble = self.test_preamble;
test_preamble.extend(other.test_preamble);
let mut record_aliases = self.record_aliases;
for entry in other.record_aliases {
if !record_aliases.contains(&entry) {
record_aliases.push(entry);
}
}
let mut embedded_methods = self.embedded_methods;
for entry in other.embedded_methods {
if !embedded_methods.contains(&entry) {
embedded_methods.push(entry);
}
}
let mut extern_fns = self.extern_fns;
for entry in other.extern_fns {
if !extern_fns.iter().any(|(n, _)| n == &entry.0) {
extern_fns.push(entry);
}
}
let mut import_from_fns = self.import_from_fns;
for entry in other.import_from_fns {
if !import_from_fns.iter().any(|(n, _)| n == &entry.0) {
import_from_fns.push(entry);
}
}
let mut signature_fns = self.signature_fns;
for name in other.signature_fns {
if !signature_fns.contains(&name) {
signature_fns.push(name);
}
}
let mut vectorizable_fns = self.vectorizable_fns;
for (name, is_vec) in other.vectorizable_fns {
match vectorizable_fns.iter_mut().find(|(n, _)| n == &name) {
Some(entry) => entry.1 = entry.1 && is_vec,
None => vectorizable_fns.push((name, is_vec)),
}
}
let mut module_inner_contexts = self.module_inner_contexts;
module_inner_contexts.extend(other.module_inner_contexts);
let mut processed_modules = self.processed_modules;
processed_modules.extend(other.processed_modules);
let mut modules_in_progress = self.modules_in_progress;
modules_in_progress.extend(other.modules_in_progress);
Context {
typing_context: self.typing_context + other.typing_context,
subtypes: self.subtypes + other.subtypes,
type_constructors,
interface_constraints,
rigid_counter,
record_aliases,
embedded_methods,
test_preamble,
self_type: None,
expected_return_type: None,
extern_fns,
import_from_fns,
signature_fns,
vectorizable_fns,
config: self.config,
module_inner_contexts,
processed_modules,
modules_in_progress,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_context1() {
let context = Context::default();
assert!(!context.display_typing_context().is_empty());
}
#[test]
fn test_record_nests_under_grecord_sentinel() {
let ctx = Context::default();
let rec = builder::record_type(&[("x".to_string(), builder::integer_type_default())]);
let graph = ctx.subtypes.clone().add_type(rec.clone(), &ctx);
let supers = graph.get_supertypes(&rec, &ctx);
assert!(
supers.iter().any(|t| matches!(t, Type::KindedGen(Kind::Record, _, _))),
"a record must nest under the GRecord (%_) sentinel; supers = {:?}",
supers
);
assert!(
supers.iter().any(|t| matches!(t, Type::Generic(_, _))),
"GRecord must itself sit under the bare Generic sentinel; supers = {:?}",
supers
);
}
#[test]
fn test_generic_sentinels_absent_from_r_classes() {
let ctx = Context::default();
let rec = builder::record_type(&[("x".to_string(), builder::integer_type_default())]);
let graph = ctx.subtypes.clone().add_type(rec.clone(), &ctx);
let ctx = ctx.with_subtypes(graph);
let classes = ctx.get_classes(&rec).unwrap();
assert!(
!classes.contains("GRecord") && !classes.contains('%') && !classes.contains("Generic"),
"generic sentinels must be filtered out of generated R classes, got: {}",
classes
);
}
}