opy-rs 0.1.52

Standalone OverPy-compatible .opy implementation with parsing, tooling, and bounded Workshop compilation.
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
use super::*;

impl Lowerer {
    pub(super) fn lower_expr(
        &mut self,
        expr: &Expr,
        macro_params: &[String],
        position: CallPosition,
    ) -> HirExpr {
        match expr {
            Expr::Number { value, text, span } => HirExpr::Number {
                value: *value,
                text: text.clone(),
                span: Some(span.into()),
            },
            Expr::String { value, span } => self.lower_string(value, *span),
            Expr::Bool { value, span } => HirExpr::Bool {
                value: *value,
                span: Some(span.into()),
            },
            Expr::Null { span } => HirExpr::Null {
                span: Some(span.into()),
            },
            Expr::Array { elements, span } => HirExpr::Array {
                elements: elements
                    .iter()
                    .map(|element| self.lower_expr(element, macro_params, CallPosition::Value))
                    .collect(),
                span: Some(span.into()),
            },
            Expr::Dict { entries, span } => {
                if !self.allow_dict_literal {
                    self.error_at(
                        "dict-access",
                        "dictionary literals must be accessed by a key".to_string(),
                        *span,
                    );
                    return HirExpr::Null { span: None };
                }
                HirExpr::Dict {
                    entries: entries
                        .iter()
                        .map(|entry| HirDictEntry {
                            key: Box::new(self.lower_expr(
                                &entry.key,
                                macro_params,
                                CallPosition::Value,
                            )),
                            value: Box::new(self.lower_expr(
                                &entry.value,
                                macro_params,
                                CallPosition::Value,
                            )),
                            span: Some(entry.span.into()),
                        })
                        .collect(),
                    span: Some(span.into()),
                }
            }
            Expr::Comprehension {
                element,
                variable,
                variable_span,
                index,
                iterable,
                condition,
                span,
            } => {
                let iterable = self.lower_expr(iterable, macro_params, CallPosition::Value);
                let previous = std::mem::take(&mut self.locals);
                self.locals.push(variable.clone());
                if let Some((index, _)) = index {
                    self.locals.push(index.clone());
                }
                let element = self.lower_expr(element, macro_params, CallPosition::Value);
                let condition = condition.as_ref().map(|condition| {
                    Box::new(self.lower_expr(condition, macro_params, CallPosition::Value))
                });
                self.locals = previous;
                HirExpr::Comprehension {
                    element: Box::new(element),
                    variable: variable.clone(),
                    variable_span: Some(variable_span.into()),
                    index: index.as_ref().map(|(name, _)| name.clone()),
                    index_span: index.as_ref().map(|(_, span)| (*span).into()),
                    iterable: Box::new(iterable),
                    condition,
                    span: Some(span.into()),
                }
            }
            Expr::Lambda { params, body, span } => {
                if position != CallPosition::LambdaArgument {
                    self.error_at(
                        "lambda-context",
                        "lambda expressions are only valid as array operation arguments"
                            .to_string(),
                        *span,
                    );
                    return HirExpr::Null { span: None };
                }
                let previous = std::mem::take(&mut self.locals);
                self.locals = params.iter().map(|(name, _)| name.clone()).collect();
                let body = self.lower_expr(body, macro_params, CallPosition::Value);
                self.locals = previous;
                HirExpr::Lambda {
                    params: params.iter().map(|(name, _)| name.clone()).collect(),
                    param_spans: params
                        .iter()
                        .map(|(_, span)| Some((*span).into()))
                        .collect(),
                    body: Box::new(body),
                    span: Some(span.into()),
                }
            }
            Expr::StringModifier {
                modifier,
                value,
                format_text,
                interpolations,
                span,
            } => {
                if *modifier == 'f' {
                    if let Some(format_text) = format_text {
                        if !interpolations.is_empty() {
                            return HirExpr::Format {
                                text: format_text.clone(),
                                args: interpolations
                                    .iter()
                                    .map(|expr| {
                                        self.lower_expr(expr, macro_params, CallPosition::Value)
                                    })
                                    .collect(),
                                span: Some(span.into()),
                            };
                        }
                        return HirExpr::String {
                            value: format_text.clone(),
                            span: Some(span.into()),
                        };
                    }
                }
                HirExpr::StringModifier {
                    modifier: modifier.to_string(),
                    value: value.clone(),
                    span: Some(span.into()),
                }
            }
            Expr::Name { name, span } => self.lower_name(name, *span, macro_params),
            Expr::Type { name, args, span } => HirExpr::Type {
                name: name.clone(),
                args: args
                    .iter()
                    .map(|arg| self.lower_expr(arg, macro_params, CallPosition::Value))
                    .collect(),
                span: Some(span.into()),
            },
            Expr::Member {
                receiver,
                member,
                member_span,
                span,
            } => self.lower_member(receiver, member, *member_span, *span, macro_params),
            Expr::Index { array, index, span } => {
                let previous = self.allow_dict_literal;
                self.allow_dict_literal = true;
                let array = self.lower_expr(array, macro_params, CallPosition::Value);
                self.allow_dict_literal = previous;
                HirExpr::Index {
                    array: Box::new(array),
                    index: Box::new(self.lower_expr(index, macro_params, CallPosition::Value)),
                    span: Some(span.into()),
                }
            }
            Expr::Call {
                name,
                args,
                debug_source,
                span,
            } => self.lower_call(
                name,
                args,
                debug_source.as_deref(),
                *span,
                macro_params,
                position,
            ),
            Expr::ReceiverCall {
                receiver,
                name,
                args,
                span,
            } => self.lower_receiver_call(receiver, name, args, *span, macro_params, position),
            Expr::Binary {
                op,
                left,
                right,
                span,
            } => HirExpr::Binary {
                op: op.clone(),
                left: Box::new(self.lower_expr(left, macro_params, CallPosition::Value)),
                right: Box::new(self.lower_expr(right, macro_params, CallPosition::Value)),
                span: Some(span.into()),
            },
            Expr::Conditional {
                then_value,
                condition,
                else_value,
                span,
            } => HirExpr::Conditional {
                then_value: Box::new(self.lower_expr(
                    then_value,
                    macro_params,
                    CallPosition::Value,
                )),
                condition: Box::new(self.lower_expr(condition, macro_params, CallPosition::Value)),
                else_value: Box::new(self.lower_expr(
                    else_value,
                    macro_params,
                    CallPosition::Value,
                )),
                span: Some((*span).into()),
            },
            Expr::Unary { op, operand, span } => HirExpr::Unary {
                op: op.clone(),
                operand: Box::new(self.lower_expr(operand, macro_params, CallPosition::Value)),
                span: Some(span.into()),
            },
        }
    }

    pub(super) fn lower_name(
        &mut self,
        name: &str,
        span: Span,
        macro_params: &[String],
    ) -> HirExpr {
        if macro_params.iter().any(|param| param == name) {
            return HirExpr::MacroParam {
                name: name.to_string(),
                span: Some(span.into()),
            };
        }
        if self.locals.iter().any(|local| local == name) {
            return HirExpr::Local {
                name: name.to_string(),
                span: Some(span.into()),
            };
        }
        if let Some(player) = context_player_expr(name, Some(span)) {
            return player;
        }
        match name {
            "RULE_CONDITION" | "ruleCondition" => HirExpr::Call {
                name: "ruleCondition".to_string(),
                args: Vec::new(),
                debug_source: None,
                span: Some(span.into()),
            },
            "eventAbility" | "eventDamage" | "eventHealing" | "eventWasCriticalHit" => {
                HirExpr::Call {
                    name: name.to_string(),
                    args: Vec::new(),
                    debug_source: None,
                    span: Some(span.into()),
                }
            }
            _ if self.global_visible(name) => HirExpr::GlobalVar {
                name: name.to_string(),
                span: Some(span.into()),
            },
            _ if self.player_visible(name) => HirExpr::PlayerVar {
                player: Box::new(HirExpr::EventPlayer { span: None }),
                name: name.to_string(),
                member_span: None,
                span: Some(span.into()),
            },
            _ if self.constant_visible(name) => HirExpr::Constant {
                name: name.to_string(),
                span: Some(span.into()),
            },
            _ if self.enum_visible(name) => {
                self.error_at(
                    "enum-type-without-member",
                    format!("enum type '{name}' must be used with a member (e.g. {name}.MEMBER)"),
                    span,
                );
                HirExpr::Null { span: None }
            }
            // OverPy default variable names (A–Z, AA–…, DX): implicit global
            // variables at fixed Workshop slots. The pinned reference accepts
            // these without a `globalvar` declaration anywhere a variable may
            // appear, including as a `for ... in range(...)` loop binder
            // (#114). Custom enums take precedence over default-var names,
            // matching the reference's identifier resolution order.
            _ if default_var_index(name).is_some() => HirExpr::GlobalVar {
                name: name.to_string(),
                span: Some(span.into()),
            },
            _ => {
                self.error_at(
                    "unknown-identifier",
                    format!("unknown identifier '{name}'"),
                    span,
                );
                HirExpr::Null { span: None }
            }
        }
    }

    pub(super) fn lower_member(
        &mut self,
        receiver: &Expr,
        member: &str,
        member_span: Span,
        span: Span,
        macro_params: &[String],
    ) -> HirExpr {
        if let Some(name) = self.qualified_macro_for_member(member) {
            return HirExpr::MacroCall {
                name,
                args: vec![self.lower_expr(receiver, macro_params, CallPosition::Value)],
                span: Some(span.into()),
            };
        }
        if let Expr::Name { name, .. } = receiver {
            // Custom enum member: folds to its numeric constant.
            if self.enum_visible(name) {
                let members = self.enums.get(name).expect("enum span and members agree");
                return match members.iter().position(|candidate| candidate == member) {
                    Some(index) => HirExpr::Number {
                        value: index as f64,
                        text: index.to_string(),
                        span: Some(span.into()),
                    },
                    None => {
                        self.error_at(
                            "unknown-enum-member",
                            format!("enum '{name}' has no member '{member}'"),
                            span,
                        );
                        HirExpr::Null { span: None }
                    }
                };
            }
            if name == "Texture" {
                if let Some(tag) = super::textures::tag(member) {
                    self.texture_used = true;
                    return HirExpr::Format {
                        text: tag.replacen('<', "{0}", 1),
                        args: vec![HirExpr::GlobalVar {
                            name: "__holygrail__".to_string(),
                            span: Some(span.into()),
                        }],
                        span: Some(span.into()),
                    };
                }
                self.error_at(
                    "unknown-texture-member",
                    format!("unknown texture member '{member}'"),
                    span,
                );
                return HirExpr::Null { span: None };
            }
            if name == "Math" {
                match member {
                    "FUCKTON_OF_SPACES" | "LOTS_OF_SPACES" => {
                        return HirExpr::String {
                            value: "\u{2003}".repeat(170),
                            span: Some(span.into()),
                        };
                    }
                    "FUCKTON_OF_NEWLINES" | "LOTS_OF_NEWLINES" => {
                        return HirExpr::String {
                            value: "\n".repeat(125),
                            span: Some(span.into()),
                        };
                    }
                    _ => {}
                }
                if let Some((value, text)) = match member {
                    "PI" => Some((std::f64::consts::PI, "3.141592653589793")),
                    "E" => Some((std::f64::consts::E, "2.718281828459045")),
                    "INFINITY" => Some((999_999_999_999.0, "999999999999")),
                    "EPSILON" => Some((1192093e-13, "0.0000001192093")),
                    "SPHERE_HORIZONTAL_RADIUS_MULT" => Some((0.984724, "0.984724")),
                    "SPHERE_VERTICAL_RADIUS_MULT" => Some((0.998959, "0.998959")),
                    "INNER_RING_RADIUS_MULT" => Some((0.9415, "0.9415")),
                    "OUTER_RING_RADIUS_MULT" => Some((0.94965, "0.94965")),
                    "RING_EXPLOSION_RADIUS_MULT" => Some((0.48, "0.48")),
                    _ => None,
                } {
                    return HirExpr::Number {
                        value,
                        text: text.to_string(),
                        span: Some(span.into()),
                    };
                }
            }
            if name == "Color" {
                if let Some((red, green, blue)) = match member {
                    "LIGHT_RED" => Some((255, 112, 122)),
                    "LIGHT_PURPLE" => Some((210, 127, 243)),
                    "LIGHT_VIOLET" => Some((203, 135, 255)),
                    "LIGHT_GRAY" => Some((168, 168, 168)),
                    _ => None,
                } {
                    let number = |value: i32| HirExpr::Number {
                        value: f64::from(value),
                        text: value.to_string(),
                        span: Some(span.into()),
                    };
                    return HirExpr::Call {
                        name: "rgb".to_string(),
                        args: vec![number(red), number(green), number(blue)],
                        debug_source: None,
                        span: Some(span.into()),
                    };
                }
            }
            // Builtin Workshop enum: the domain name is a declared OPY
            // signature identity (manifest `param.domain`); the member list
            // is Workshop-owned catalog content, so the member access
            // resolves as an opaque identity after validating the member
            // against the canonical Workshop catalog.
            let catalog_domain = match name.as_str() {
                "Clip" => "Clipping",
                "AsyncBehavior" => "StartRuleBehavior",
                _ => name.as_str(),
            };
            if (!policy::is_contextual_domain(name) && self.manifest.domain_identity(name))
                || self.catalog.enum_domain(name).is_some()
                || self.catalog.enum_domain(catalog_domain).is_some()
                || (name == "Clip" && self.manifest.domain_identity(catalog_domain))
            {
                let locale = Locale::new("en-US");
                let catalog_member = match (name.as_str(), member) {
                    ("Map", "BLIZZ_WORLD") => "BLIZZARD_WORLD",
                    ("Map", "BLIZZ_WORLD_WINTER") => "BLIZZARD_WORLD_WINTER",
                    ("Map", "ROUTE66") => "ROUTE_66",
                    ("Map", "VOLSKAYA") => "VOLSKAYA_INDUSTRIES",
                    ("Clip", "NONE") => "DO_NOT_CLIP",
                    ("Clip", "SURFACES") => "CLIP_AGAINST_SURFACES",
                    ("SpecVisibility", "ALWAYS") => "VISIBLE_ALWAYS",
                    ("SpecVisibility", "NEVER") => "VISIBLE_NEVER",
                    ("EffectReeval", "VISIBILITY_POSITION_AND_RADIUS") => {
                        "VISIBLE_TO_POSITION_AND_RADIUS"
                    }
                    ("HudReeval", "VISIBILITY_AND_COLOR") => "VISIBLE_TO_AND_COLOR",
                    ("HudReeval", "VISIBILITY_STRING_AND_COLOR") => "VISIBLE_TO_STRING_AND_COLOR",
                    ("Hero", "MCCREE") => "CASSIDY",
                    ("Hero", "HAMMOND") => "WRECKING_BALL",
                    ("Hero", "SOLDIER") => "SOLDIER_76",
                    ("Hero", "DOMINA") => "JINYU",
                    ("Hero", "DMON") => "D_MON",
                    _ => member,
                };
                let canonical_member = self
                    .catalog
                    .enum_domain(catalog_domain)
                    .and_then(|domain| {
                        domain
                            .members
                            .iter()
                            .find(|candidate| candidate.member == catalog_member)
                            .map(|candidate| candidate.member.clone())
                            .or_else(|| {
                                (name == "Map").then(|| {
                                    let normalized = catalog_member.replace('_', "");
                                    domain
                                        .members
                                        .iter()
                                        .find(|candidate| {
                                            candidate.member.replace('_', "") == normalized
                                        })
                                        .map(|candidate| candidate.member.clone())
                                })?
                            })
                    })
                    .or_else(|| {
                        if name == "Team" && member.parse::<u32>().is_ok() {
                            self.catalog
                                .resolve_enum_member(name, &locale, &format!("{name} {member}"))
                                .map(|(_, member)| member)
                        } else {
                            None
                        }
                    })
                    .or_else(|| {
                        (name == "HudReeval" && member == "VISIBILITY_STRING_AND_COLOR")
                            .then_some(catalog_member.to_string())
                    });
                let Some(canonical_member) = canonical_member else {
                    self.error_at(
                        "unknown-enum-member",
                        format!("enum '{name}' has no member '{member}'"),
                        span,
                    );
                    return HirExpr::Null { span: None };
                };
                return HirExpr::Enum {
                    value_type: catalog_domain.to_string(),
                    value: canonical_member,
                    span: Some(span.into()),
                };
            }
            // Context-player member: a player-variable reference.
            if matches!(
                name.as_str(),
                "eventPlayer" | "hostPlayer" | "localPlayer" | "attacker" | "victim"
            ) {
                if !default_var_index(member).is_some() && !self.player_visible(member) {
                    self.error_at(
                        "unknown-member",
                        format!("unknown member '{member}'"),
                        member_span,
                    );
                    return HirExpr::Null { span: None };
                }
                let player = context_player_expr(
                    name,
                    (!matches!(name.as_str(), "eventPlayer" | "hostPlayer"))
                        .then_some(receiver.span()),
                )
                .expect("context-player receiver name is exhaustive");
                return HirExpr::PlayerVar {
                    player: Box::new(player),
                    name: member.to_string(),
                    member_span: Some(member_span.into()),
                    span: Some(span.into()),
                };
            }
            // A module member used without a call (`random.uniform` alone).
            if name == "random" {
                self.error_at(
                    "unsupported-member",
                    format!("module member '{name}.{member}' must be called"),
                    span,
                );
                return HirExpr::Null { span: None };
            }
            if self.player_visible(member) {
                return HirExpr::PlayerVar {
                    player: Box::new(self.lower_expr(receiver, macro_params, CallPosition::Value)),
                    name: member.to_string(),
                    member_span: Some(member_span.into()),
                    span: Some(span.into()),
                };
            }
            // A bare variable receiver member is valid OPY source syntax even
            // when canonical member existence is deferred to Workshop. Keep
            // both the resolved variable receiver and the source member
            // identity in HIR instead of treating it as an unknown member.
            if self.global_visible(name)
                || self.player_visible(name)
                || default_var_index(name).is_some()
            {
                let receiver = if default_var_index(name).is_some() {
                    HirExpr::GlobalVar {
                        name: name.to_string(),
                        span: Some(receiver.span().into()),
                    }
                } else {
                    self.lower_name(name, receiver.span(), &[])
                };
                return HirExpr::Member {
                    receiver: Box::new(receiver),
                    member: member.to_string(),
                    member_span: Some(member_span.into()),
                    span: Some(span.into()),
                };
            }
        }
        if self.player_visible(member) {
            return HirExpr::PlayerVar {
                player: Box::new(self.lower_expr(receiver, macro_params, CallPosition::Value)),
                name: member.to_string(),
                member_span: Some(member_span.into()),
                span: Some(span.into()),
            };
        }
        if matches!(member, "x" | "y" | "z") {
            return HirExpr::Member {
                receiver: Box::new(self.lower_expr(receiver, macro_params, CallPosition::Value)),
                member: member.to_string(),
                member_span: Some(member_span.into()),
                span: Some(span.into()),
            };
        }
        self.error_at(
            "unsupported-member",
            "unsupported member access on this expression".to_string(),
            span,
        );
        HirExpr::Null { span: None }
    }

    pub(super) fn lower_call(
        &mut self,
        name: &str,
        args: &[cst::CallArg],
        debug_source: Option<&str>,
        span: Span,
        macro_params: &[String],
        position: CallPosition,
    ) -> HirExpr {
        if matches!(name, "_" | "__" | "___") {
            if !matches!(args.len(), 1 | 2) {
                self.error_at(
                    "translations-invalid",
                    format!("translation function '{name}' expects one or two arguments"),
                    span,
                );
                return HirExpr::Null { span: None };
            }
            if args.len() == 2 && !matches!(args[0].value, cst::Expr::String { .. }) {
                self.error_at(
                    "translations-invalid",
                    "translation context must be a string literal".to_string(),
                    args[0].value.span(),
                );
                return HirExpr::Null { span: None };
            }
            return HirExpr::Call {
                name: name.to_string(),
                args: self.lower_arg_values(args, macro_params),
                debug_source: None,
                span: Some(span.into()),
            };
        }
        if name == "createWorkshopSetting" {
            return self.lower_workshop_setting(args, span, macro_params);
        }
        if name == "compressed" {
            return HirExpr::Call {
                name: name.to_string(),
                args: self.lower_arg_values(args, macro_params),
                debug_source: None,
                span: Some(span.into()),
            };
        }
        if matches!(
            name,
            "createWorkshopSettingBool"
                | "createWorkshopSettingEnum"
                | "createWorkshopSettingInt"
                | "createWorkshopSettingFloat"
        ) {
            return HirExpr::Call {
                name: name.to_string(),
                args: self.lower_arg_values(args, macro_params),
                debug_source: None,
                span: Some(span.into()),
            };
        }
        // Builtin identity and position checks run before the special forms
        // so that a misplaced `wait`/`vect` still diagnoses its position.
        if !self.macro_visible(name) && !self.subroutine_visible(name) && name != "sorted" {
            match self.manifest.resolve_function(name) {
                Some(entry) => self.check_call_position(name, entry, position, span),
                None => {
                    let (code, message) = match position {
                        CallPosition::Statement => {
                            ("unknown-action", format!("unknown action '{name}'"))
                        }
                        CallPosition::Value => ("unknown-value", format!("unknown value '{name}'")),
                        CallPosition::ForIterable => (
                            "invalid-iterable",
                            format!("for-loop iterable '{name}' must be a range(...) call"),
                        ),
                        CallPosition::LambdaArgument => {
                            ("unknown-value", format!("unknown value '{name}'"))
                        }
                        CallPosition::MacroBody => {
                            ("unknown-value", format!("unknown value '{name}'"))
                        }
                    };
                    self.error_at(code, message, span);
                }
            }
        }
        match name {
            "sorted" => HirExpr::Call {
                name: name.to_string(),
                args: self.lower_arg_values_with_lambda(args, macro_params, |index, arg| {
                    index == 1 || arg.keyword.as_ref().is_some_and(|(name, _)| name == "key")
                }),
                debug_source: None,
                span: Some(span.into()),
            },
            "vect" => {
                // `vect` goes through the generic argument binder so its
                // keyword forms (`vect(x=1, y=2, z=3)`) bind like any other
                // manifest signature; the result must fill exactly the three
                // declared parameters (x, y, z).
                let (bound, _) = match self.manifest.resolve_function(name) {
                    Some(entry) => self.bind_args(entry, args, macro_params),
                    None => (self.lower_arg_values(args, macro_params), None),
                };
                if bound.len() < 3 {
                    self.error_at(
                        "vect-arity",
                        format!(
                            "vect() expects 3 arguments (x, y, z) but got {}",
                            args.len()
                        ),
                        span,
                    );
                    return HirExpr::Null { span: None };
                }
                HirExpr::Vector {
                    x: Box::new(bound[0].clone()),
                    y: Box::new(bound[1].clone()),
                    z: Box::new(bound[2].clone()),
                    span: Some(span.into()),
                }
            }
            _ => {
                if self.macro_visible(name) {
                    // A declared `macro` invocation is recorded as a macroCall
                    // (positional-only; keyword arguments are an explicit
                    // diagnostic).
                    for arg in args {
                        if let Some((keyword, span)) = &arg.keyword {
                            self.error_at(
                                "keyword-unsupported",
                                format!(
                                    "macro '{name}' does not accept keyword \
                                     arguments ('{keyword}')"
                                ),
                                *span,
                            );
                        }
                    }
                    return HirExpr::MacroCall {
                        name: name.to_string(),
                        args: self.lower_arg_values(args, macro_params),
                        span: Some(span.into()),
                    };
                }
                if name == "async" {
                    let lowered = args
                        .iter()
                        .enumerate()
                        .map(|(index, arg)| {
                            if index == 0 && arg.keyword.is_none() {
                                if let cst::Expr::Name {
                                    name: subroutine,
                                    span,
                                } = &arg.value
                                {
                                    if self.subroutine_visible(subroutine) {
                                        return HirExpr::Call {
                                            name: subroutine.clone(),
                                            args: Vec::new(),
                                            debug_source: None,
                                            span: Some((*span).into()),
                                        };
                                    }
                                }
                            }
                            self.lower_expr(&arg.value, macro_params, CallPosition::Value)
                        })
                        .collect();
                    return HirExpr::Call {
                        name: name.to_string(),
                        args: lowered,
                        debug_source: None,
                        span: Some(span.into()),
                    };
                }
                match self.manifest.resolve_function(name) {
                    Some(entry) => {
                        // Declared subroutines with arguments stay generic
                        // calls; builtins get keyword binding, arity, and
                        // domain/default handling.
                        if self.subroutine_visible(name) {
                            return HirExpr::Call {
                                name: name.to_string(),
                                args: self.lower_arg_values(args, macro_params),
                                debug_source: (name == "debug")
                                    .then(|| debug_source.map(str::to_string))
                                    .flatten(),
                                span: Some(span.into()),
                            };
                        }
                        let (bound, selector) = self.bind_args(entry, args, macro_params);
                        let (call_name, bound) =
                            self.resolve_contextual_domain(entry, bound, selector.as_deref());
                        HirExpr::Call {
                            name: call_name,
                            args: bound,
                            debug_source: (name == "debug")
                                .then(|| debug_source.map(str::to_string))
                                .flatten(),
                            span: Some(span.into()),
                        }
                    }
                    None => HirExpr::Call {
                        name: name.to_string(),
                        args: self.lower_arg_values(args, macro_params),
                        debug_source: None,
                        span: Some(span.into()),
                    },
                }
            }
        }
    }

    pub(super) fn lower_arg_values(
        &mut self,
        args: &[cst::CallArg],
        macro_params: &[String],
    ) -> Vec<HirExpr> {
        self.lower_arg_values_with_lambda(args, macro_params, |_, _| false)
    }

    pub(super) fn lower_arg_values_with_lambda(
        &mut self,
        args: &[cst::CallArg],
        macro_params: &[String],
        allows_lambda: impl Fn(usize, &cst::CallArg) -> bool,
    ) -> Vec<HirExpr> {
        args.iter()
            .enumerate()
            .map(|(index, arg)| {
                let position = if allows_lambda(index, arg) {
                    CallPosition::LambdaArgument
                } else {
                    CallPosition::Value
                };
                self.lower_expr(&arg.value, macro_params, position)
            })
            .collect()
    }

    /// Bind positional and keyword arguments against a manifest signature
    /// (issue #110), producing lowered values in parameter order with
    /// declared defaults filled. Diagnostics are structured and
    /// source-located: `unknown-keyword`, `duplicate-argument`,
    /// `keyword-required`, `positional-after-keyword`, `missing-argument`,
    /// `keyword-unsupported`, `invalid-arity` (overflow), and
    /// `invalid-argument` (variable-required parameters).
    ///
    /// The returned `selector` is the keyword spelling used to bind the
    /// entry's contextual-domain selector parameter (the `chase` form's
    /// `rate`/`duration`), when the entry declares one.
    pub(super) fn bind_args(
        &mut self,
        entry: &Function,
        args: &[cst::CallArg],
        macro_params: &[String],
    ) -> (Vec<HirExpr>, Option<String>) {
        let mut slots: Vec<Option<HirExpr>> = vec![None; entry.params.len()];
        let mut selector = None;
        let mut has_keyword = false;
        let mut binding_error = false;
        let contextual = policy::contextual_domain(&entry.id);

        // Keyword spellings resolve through the declared parameter names
        // (alternate spellings included) — generic binding, no per-spelling
        // branches.
        let mut by_spelling: HashMap<&str, usize> = HashMap::new();
        for (index, param) in entry.params.iter().enumerate() {
            by_spelling.insert(param.name.as_str(), index);
            for alternate in &param.alternate_names {
                by_spelling.insert(alternate.as_str(), index);
            }
        }

        for (arg_index, arg) in args.iter().enumerate() {
            match &arg.keyword {
                Some((keyword, name_span)) => {
                    if !entry.keyword_args {
                        binding_error = true;
                        self.error_at(
                            "keyword-unsupported",
                            format!(
                                "function '{}' does not accept keyword arguments ('{keyword}')",
                                entry.id
                            ),
                            *name_span,
                        );
                        continue;
                    }
                    has_keyword = true;
                    match by_spelling.get(keyword.as_str()) {
                        None => {
                            binding_error = true;
                            self.error_at(
                                "unknown-keyword",
                                format!(
                                    "unknown keyword argument '{keyword}' for function '{}'",
                                    entry.id
                                ),
                                *name_span,
                            );
                        }
                        Some(&index) => {
                            let param = &entry.params[index];
                            if param.positional_only {
                                binding_error = true;
                                self.error_at(
                                    "unknown-keyword",
                                    format!(
                                        "parameter '{}' of '{}' cannot be bound by keyword",
                                        param.name, entry.id
                                    ),
                                    *name_span,
                                );
                            } else if slots[index].is_some() {
                                binding_error = true;
                                self.error_at(
                                    "duplicate-argument",
                                    format!(
                                        "argument '{}' of function '{}' is defined twice",
                                        keyword, entry.id
                                    ),
                                    *name_span,
                                );
                            } else {
                                slots[index] = Some(self.lower_call_arg_value(
                                    entry,
                                    index,
                                    arg,
                                    macro_params,
                                ));
                                if contextual.is_some_and(|c| c.by == param.name) {
                                    selector = Some(keyword.clone());
                                }
                            }
                        }
                    }
                }
                None => {
                    // The reference's generic binder rejects positional
                    // arguments after keyword arguments; its special forms
                    // (the contextual-domain entries, e.g. `chase`) bind the
                    // trailing positionals by slot and skip the ordering
                    // rule.
                    if has_keyword && contextual.is_none() {
                        binding_error = true;
                        self.error_at(
                            "positional-after-keyword",
                            format!(
                                "cannot use positional arguments after keyword \
                                 arguments in call to '{}'",
                                entry.id
                            ),
                            arg.value.span(),
                        );
                    }
                    // Positional arguments fill the slot at their argument
                    // index (keywords occupy their named slots), matching
                    // the reference binder.
                    let index = arg_index;
                    if index < entry.params.len() {
                        let param = &entry.params[index];
                        if param.keyword_only {
                            binding_error = true;
                            self.error_at(
                                "keyword-required",
                                format!(
                                    "argument {} of '{}' must be passed as a keyword \
                                     (name = value; accepted names: {})",
                                    index + 1,
                                    entry.id,
                                    keyword_spellings(param).join(", ")
                                ),
                                arg.value.span(),
                            );
                        }
                        if slots[index].is_none() {
                            slots[index] =
                                Some(self.lower_call_arg_value(entry, index, arg, macro_params));
                        }
                    } else {
                        self.lower_expr(&arg.value, macro_params, CallPosition::Value);
                    }
                }
            }
        }

        // Positional overflow: the declared arity bounds report the
        // reference's "takes N arguments, received M" rejection. A binding
        // error already reported (duplicate keyword, unknown keyword, …)
        // suppresses the secondary arity noise, matching the reference's
        // first-error behavior.
        if !binding_error && args.len() > entry.params.len() {
            self.check_arity(entry, args.len(), arg_span(args));
        }

        // Unbound parameters: declared defaults fill; required parameters
        // without a default are the reference's missing-argument rejection;
        // `optional` parameters stay omittable without an emitted expansion.
        let mut bound: Vec<HirExpr> = Vec::with_capacity(entry.params.len());
        for (index, param) in entry.params.iter().enumerate() {
            match &slots[index] {
                Some(value) => bound.push(value.clone()),
                None => match &param.default {
                    Some(ParamDefault::Call { call }) => {
                        bound.push(HirExpr::Call {
                            name: call.clone(),
                            args: Vec::new(),
                            debug_source: None,
                            span: None,
                        });
                    }
                    Some(ParamDefault::EnumMember(member)) => {
                        let domain = param.domain.clone().unwrap_or_default();
                        bound.push(HirExpr::Enum {
                            value_type: domain,
                            value: member.clone(),
                            span: None,
                        });
                    }
                    Some(ParamDefault::Bool(value)) => {
                        bound.push(HirExpr::Bool {
                            value: *value,
                            span: None,
                        });
                    }
                    Some(ParamDefault::Number(number)) => {
                        bound.push(HirExpr::Number {
                            value: *number,
                            text: format!("{number}"),
                            span: None,
                        });
                    }
                    None if param.optional => {
                        // Omitted entirely (the reference's short forms keep
                        // the argument list short, e.g. `range(3)`).
                    }
                    None => {
                        self.error_at(
                            "missing-argument",
                            format!(
                                "missing argument '{}' for function '{}'",
                                param.name, entry.id
                            ),
                            arg_span(args),
                        );
                        bound.push(HirExpr::Null { span: None });
                    }
                },
            }
        }

        // Variable-required parameters (the chase family's first argument)
        // must resolve to a variable reference.
        for (index, param) in entry.params.iter().enumerate() {
            if !param.variable {
                continue;
            }
            if let Some(Some(value)) = slots.get(index) {
                if !matches!(value, HirExpr::GlobalVar { .. } | HirExpr::PlayerVar { .. }) {
                    self.error_at(
                        "invalid-argument",
                        format!(
                            "argument {} of '{}' must be a variable (globalvar or \
                             playervar)",
                            index + 1,
                            entry.id
                        ),
                        arg_span(args),
                    );
                }
            }
        }

        (bound, selector)
    }

    /// Lower one call argument's value; the contextual-domain parameter (the
    /// `chase` form's `ChaseReeval` member) is recorded as a pending enum
    /// without validating the domain — it resolves only against the concrete
    /// domain selected by the call's keyword selector (issue #110). Outside
    /// that signature context `ChaseReeval` never resolves because it is not
    /// a declared enum domain.
    pub(super) fn lower_call_arg_value(
        &mut self,
        entry: &Function,
        param_index: usize,
        arg: &cst::CallArg,
        macro_params: &[String],
    ) -> HirExpr {
        if let Some(contextual) = policy::contextual_domain(&entry.id) {
            let is_contextual = entry.params[param_index]
                .domain
                .as_deref()
                .is_some_and(|domain| domain == contextual.domain);
            if is_contextual {
                if let Expr::Member {
                    receiver,
                    member,
                    span,
                    ..
                } = &arg.value
                {
                    if let Expr::Name { name, .. } = receiver.as_ref() {
                        if name == contextual.domain {
                            return HirExpr::Enum {
                                value_type: contextual.domain.to_string(),
                                value: member.clone(),
                                span: Some((*span).into()),
                            };
                        }
                    }
                }
            }
        }
        self.lower_expr(&arg.value, macro_params, CallPosition::Value)
    }

    /// Resolve a contextual enum-domain parameter (the `chase` form's
    /// `ChaseReeval` member, issue #110): the keyword spelling bound to the
    /// selector parameter selects the concrete domain and the function the
    /// call lowers to. This is pure catalog-identity dispatch — member
    /// *existence* in the selected domain is Workshop-owned knowledge and is
    /// not validated here (lowering-dependent, issue #8). Outside this
    /// signature context `ChaseReeval` never resolves (it is not a standalone
    /// domain identity). A call that does not bind a contextual member keeps
    /// its original function identity.
    pub(super) fn resolve_contextual_domain(
        &mut self,
        entry: &Function,
        mut bound: Vec<HirExpr>,
        selector: Option<&str>,
    ) -> (String, Vec<HirExpr>) {
        let Some(contextual) = policy::contextual_domain(&entry.id) else {
            return (entry.id.clone(), bound);
        };
        let Some(contextual_param) = entry
            .params
            .iter()
            .position(|param| param.domain.as_deref() == Some(contextual.domain))
        else {
            return (entry.id.clone(), bound);
        };
        // Dispatch only when the argument is written as a member of the
        // contextual domain; anything else keeps the generic call (the
        // reference's "expected an enum" rejection is lowering-dependent).
        let HirExpr::Enum {
            value_type,
            value,
            span: value_span,
        } = &bound[contextual_param]
        else {
            return (entry.id.clone(), bound);
        };
        if value_type != contextual.domain {
            return (entry.id.clone(), bound);
        }
        let Some(keyword) = selector else {
            return (entry.id.clone(), bound);
        };
        let Some(option) = contextual
            .options
            .iter()
            .find(|option| option.keyword == keyword)
        else {
            return (entry.id.clone(), bound);
        };
        bound[contextual_param] = HirExpr::Enum {
            value_type: option.domain.to_string(),
            value: value.clone(),
            span: *value_span,
        };
        (option.target.to_string(), bound)
    }

    pub(super) fn lower_receiver_call(
        &mut self,
        receiver: &Expr,
        name: &str,
        args: &[cst::CallArg],
        span: Span,
        macro_params: &[String],
        position: CallPosition,
    ) -> HirExpr {
        if let Some(macro_name) = self.qualified_macro_for_member(name) {
            return HirExpr::MacroCall {
                name: macro_name,
                args: std::iter::once(self.lower_expr(receiver, macro_params, CallPosition::Value))
                    .chain(self.lower_arg_values(args, macro_params))
                    .collect(),
                span: Some(span.into()),
            };
        }
        if name == "getOppositeTeam" {
            return HirExpr::ReceiverCall {
                receiver: Box::new(self.lower_expr(receiver, macro_params, CallPosition::Value)),
                name: "getOppositeTeam".to_string(),
                args: self.lower_arg_values(args, macro_params),
                span: Some(span.into()),
            };
        }
        if name == "toArray" {
            if let Expr::Name {
                name: type_name, ..
            } = receiver
            {
                if self.manifest.domain_identity(type_name)
                    || self.catalog.enum_domain(type_name).is_some()
                {
                    return HirExpr::ReceiverCall {
                        receiver: Box::new(HirExpr::Type {
                            name: type_name.clone(),
                            args: Vec::new(),
                            span: Some(receiver.span().into()),
                        }),
                        name: name.to_string(),
                        args: self.lower_arg_values(args, macro_params),
                        span: Some(span.into()),
                    };
                }
            }
        }
        if matches!(name, "map" | "filter" | "all" | "any") {
            let lowered = HirExpr::ReceiverCall {
                receiver: Box::new(self.lower_expr(receiver, macro_params, CallPosition::Value)),
                name: name.to_string(),
                args: self.lower_arg_values_with_lambda(args, macro_params, |index, _| index == 0),
                span: Some(span.into()),
            };
            return lowered;
        }
        // `random.uniform(...)` etc. are dotted generic calls.
        if let Expr::Name { name: root, .. } = receiver {
            if root == "random" {
                return self.lower_call(
                    &format!("random.{name}"),
                    args,
                    None,
                    span,
                    macro_params,
                    position,
                );
            }
        }
        // `.format` on a string literal is the format special form; it is
        // also a declared member value (receiver category `String`), so
        // position misuse diagnoses here.
        if let Expr::String { value, .. } = receiver {
            if name == "format" {
                if args.iter().any(|arg| arg.keyword.is_some()) {
                    for arg in args {
                        if let Some((keyword, span)) = &arg.keyword {
                            self.error_at(
                                "keyword-unsupported",
                                format!(
                                    "function 'format' does not accept keyword \
                                     arguments ('{keyword}')"
                                ),
                                *span,
                            );
                        }
                    }
                }
                let lowered: Vec<HirExpr> = self.lower_arg_values(args, macro_params);
                if let Some(entry) = self.manifest.resolve_member("format") {
                    self.check_call_position("format", entry, position, span);
                }
                return HirExpr::Format {
                    text: value.clone(),
                    args: lowered,
                    span: Some(span.into()),
                };
            }
        }
        // Member calls resolve through the manifest (receiver category,
        // explicit-argument signatures, keyword binding).
        let (member_name, lowered) = match self.manifest.resolve_member(name) {
            Some(entry) => {
                self.check_call_position(name, entry, position, span);
                if let Some(category) = entry.receiver {
                    self.check_receiver(receiver, category, entry, span);
                }
                let (bound, _) = self.bind_args(entry, args, macro_params);
                (entry.id.clone(), bound)
            }
            None => {
                self.error_at("unknown-member", format!("unknown member '{name}'"), span);
                (name.to_string(), self.lower_arg_values(args, macro_params))
            }
        };
        // `eventPlayer.member(...)` → receiver call on the event player.
        if let Expr::Name { name: root, .. } = receiver {
            if matches!(
                root.as_str(),
                "eventPlayer" | "hostPlayer" | "localPlayer" | "attacker" | "victim"
            ) {
                return HirExpr::ReceiverCall {
                    receiver: Box::new(
                        context_player_expr(
                            root,
                            (!matches!(root.as_str(), "eventPlayer" | "hostPlayer"))
                                .then_some(receiver.span()),
                        )
                        .expect("context-player receiver name is exhaustive"),
                    ),
                    name: member_name,
                    args: lowered,
                    span: Some(span.into()),
                };
            }
        }
        // Any other receiver: resolve it and keep the receiver call.
        HirExpr::ReceiverCall {
            receiver: Box::new(self.lower_expr(receiver, macro_params, CallPosition::Value)),
            name: member_name,
            args: lowered,
            span: Some(span.into()),
        }
    }

    /// Check a builtin entry against its call position: action/value
    /// identity and for-iterable context.
    pub(super) fn check_call_position(
        &mut self,
        name: &str,
        entry: &Function,
        position: CallPosition,
        span: Span,
    ) {
        match position {
            CallPosition::Statement => {
                if policy::function_context(&entry.id) == Some(policy::FunctionContext::ForIterable)
                {
                    self.error_at(
                        "invalid-call-context",
                        format!("'{name}' is only valid as a for-loop iterable"),
                        span,
                    );
                } else if entry.kind.is_value() {
                    self.error_at(
                        "value-in-action-position",
                        format!("value function '{name}' cannot be used as an action"),
                        span,
                    );
                }
            }
            CallPosition::Value => {
                if entry.kind.is_action() {
                    self.error_at(
                        "action-in-value-position",
                        format!("action function '{name}' cannot be used as a value"),
                        span,
                    );
                } else if policy::function_context(&entry.id)
                    == Some(policy::FunctionContext::ForIterable)
                {
                    self.error_at(
                        "invalid-call-context",
                        format!("'{name}' is only valid as a for-loop iterable"),
                        span,
                    );
                }
            }
            CallPosition::ForIterable => {
                if policy::function_context(&entry.id) != Some(policy::FunctionContext::ForIterable)
                {
                    self.error_at(
                        "invalid-iterable",
                        format!("for-loop iterable '{name}' must be a range(...) call"),
                        span,
                    );
                }
            }
            CallPosition::LambdaArgument => {
                if entry.kind.is_action() {
                    self.error_at(
                        "action-in-value-position",
                        format!("action function '{name}' cannot be used as a value"),
                        span,
                    );
                } else if policy::function_context(&entry.id)
                    == Some(policy::FunctionContext::ForIterable)
                {
                    self.error_at(
                        "invalid-call-context",
                        format!("'{name}' is only valid as a for-loop iterable"),
                        span,
                    );
                }
            }
            CallPosition::MacroBody => {}
        }
    }

    /// Check a member call's receiver against its declared category. Only
    /// the reference-enforced categories reject: `.append` requires an
    /// assignable receiver and `.format` a string literal; player-oriented
    /// members accept any receiver (the pinned reference does not type-check
    /// them).
    pub(super) fn check_receiver(
        &mut self,
        receiver: &Expr,
        category: ReceiverCategory,
        entry: &Function,
        span: Span,
    ) {
        let mismatch = match category {
            ReceiverCategory::String => {
                !matches!(receiver, Expr::String { .. } | Expr::StringModifier { .. })
            }
            ReceiverCategory::Variable => !assignable_receiver(receiver),
            ReceiverCategory::Player | ReceiverCategory::Vector | ReceiverCategory::Any => false,
        };
        if mismatch {
            self.error_at(
                "invalid-receiver",
                format!(
                    "member '{}' requires {} as its receiver",
                    entry.id,
                    category.describe()
                ),
                span,
            );
        }
    }

    /// Check a builtin call's argument count against its declared arity.
    pub(super) fn check_arity(&mut self, entry: &Function, got: usize, span: Span) {
        let (min, max) = entry.arity_bounds();
        let valid = got >= min && max.is_none_or(|max| got <= max);
        if !valid {
            let expects = match max {
                Some(max) if min == max => format!("exactly {min}"),
                Some(max) => format!("{min} to {max}"),
                None => format!("at least {min}"),
            };
            let role = match entry.kind {
                FunctionKind::Action => "action",
                FunctionKind::Value => "value",
                FunctionKind::MemberAction => "member action",
                FunctionKind::MemberValue => "member value",
            };
            self.error_at(
                "invalid-arity",
                format!(
                    "{role} '{}' expects {expects} arguments but got {got}",
                    entry.id
                ),
                span,
            );
        }
    }
}

impl Lowerer {
    fn lower_string(&mut self, value: &str, span: Span) -> HirExpr {
        if !self.setup_tags {
            return HirExpr::String {
                value: value.to_string(),
                span: Some(span.into()),
            };
        }
        let mut text = value.to_string();
        let mut tagged = false;
        for (source, replacement) in [
            ("<fg", "{0}fg"),
            ("</fg>", "{0}/fg>"),
            ("<tx", "{0}tx"),
            ("<TX", "{0}TX"),
            ("</tx>", "{0}/tx>"),
            ("</TX>", "{0}/TX>"),
        ] {
            if text.contains(source) {
                text = text.replace(source, replacement);
                tagged = true;
            }
        }
        if !tagged {
            return HirExpr::String {
                value: value.to_string(),
                span: Some(span.into()),
            };
        }
        self.texture_used = true;
        HirExpr::Format {
            text,
            args: vec![HirExpr::GlobalVar {
                name: "__holygrail__".to_string(),
                span: Some(span.into()),
            }],
            span: Some(span.into()),
        }
    }
}