1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
//! Evaluating properties and the entries of an object body.
use super::*;
impl Evaluator {
/// Evaluate a property declared inside a class or object body. A union
/// without a selected default stays undefined here, so an instance can
/// assign it; only a module property must have a value to render.
pub(super) fn eval_property(
&mut self,
prop: &Property,
scope: &Scope,
depth: usize,
) -> Result<Option<Value>> {
self.eval_property_with(prop, scope, depth, false)
}
pub(super) fn eval_property_with(
&mut self,
prop: &Property,
scope: &Scope,
depth: usize,
require_union_default: bool,
) -> Result<Option<Value>> {
if let Some(expr) = &prop.value {
// `x: T = new { ... }` amends T's default, so an untyped `new`
// takes its parent from the declared type.
let mut value = match &prop.type_ann {
Some(ty) if parser::has_untyped_result_new(expr) && !type_is_any(ty) => {
let mut inferred = expr.clone();
parser::infer_method_return_new(&mut inferred, ty);
self.eval_expr(&inferred, scope, depth)?
}
_ => self.eval_expr(expr, scope, depth)?,
};
apply_mapping_type_annotation(&mut value, prop.type_ann.as_ref());
return Ok(Some(value));
}
if let Some(body) = &prop.body {
let mut nullable_default = prop
.type_ann
.as_ref()
.and_then(|ty| nullable_inner_default(ty, scope));
if let Some(default) = &mut nullable_default {
apply_mapping_type_annotation(default, prop.type_ann.as_ref());
}
// A body amendment amends a member the receiver itself holds. A
// same-named property of an enclosing object, declared or
// inherited, is a different member and must not become the base.
let scoped = scope
.get(&prop.name)
.filter(|_| scope.vars.contains_key(prop.name.as_ref()));
let amendment_base = scoped
.filter(|value| !is_null_value(value))
.or(nullable_default.as_ref())
.or(scoped);
if let Some(Value::List(items)) = amendment_base
&& matches!(items.kind(), ListKind::List | ListKind::Set)
{
let class = if items.kind() == ListKind::List {
"List"
} else {
"Set"
};
return Err(Error::Eval(format!(
"Cannot instantiate, or amend an instance of, external class `{class}`."
)));
}
if let Some(function @ Value::Lambda(params, ..)) = amendment_base {
return Ok(Some(amended_function(
params.len(),
function.clone(),
body,
scope,
)));
}
if matches!(amendment_base, Some(Value::List(_)))
|| (!matches!(amendment_base, Some(Value::Object(..)))
&& (prop.type_ann.as_ref().is_some_and(type_is_listing)
|| entries_are_listing_amendment(body)))
{
let mut items = match amendment_base {
Some(Value::List(existing)) => existing.clone(),
_ => ListValue::new(ListKind::Listing, Vec::new()),
};
let mut amendment_scope = scope.child();
amendment_scope.set("super", Value::List(items.clone()));
amendment_scope.receiver_entries = Some(body.clone());
amendment_scope.receiver_list_base = Some(items.len());
self.eval_listing_entries(body, &amendment_scope, depth, items.make_mut())?;
return Ok(Some(Value::List(items)));
}
// `foo { ... }` — object body amendment.
// If the property already has a value in scope (e.g., from a base class),
// amend that value so its ObjectSource (type info, default template) is preserved.
if let Some(Value::Object(existing_map, Some(src))) = amendment_base {
if !src.mapping_value_types.is_empty() {
// Mapping ObjectSource entries are mapping body entries such as
// `default` and dynamic keys. Rebuild the entry map with the
// type-aware evaluator so single-type and union mappings both keep
// mapping defaults plus converter type metadata after amendment.
let (inherited_scope, mut amendment_scope) =
mapping_amendment_scopes(src.scope(), src.scope_declared(), scope);
amendment_scope.set(
"super",
Value::Object(Arc::clone(existing_map), Some(Arc::clone(src))),
);
let mut receiver_entries = existing_map
.keys()
.map(|key| Entry::DynProperty(Expr::String(Arc::clone(key)), Expr::Null))
.collect::<Vec<_>>();
receiver_entries.extend_from_slice(body);
amendment_scope.receiver_entries = Some(Arc::new(receiver_entries));
let value_type_defaults = src
.mapping_value_types
.iter()
.filter_map(|name| {
let name = mapping_value_type_base(name);
resolve_dotted(&inherited_scope, name)
.map(|value| (name.to_string(), value))
})
.collect::<Vec<_>>();
let inherited_default =
self.find_default_template(&src.entries, &inherited_scope, depth)?;
let mut amended = ObjectMap::default();
self.eval_mapping_entries_with_type_default(
&src.entries,
&inherited_scope,
depth,
&mut amended,
&value_type_defaults,
&src.mapping_value_types,
MappingInheritedDefault::default(),
)?;
amended.extend(existing_map.iter().map(|(k, v)| (k.clone(), v.clone())));
self.eval_mapping_entries_with_type_default(
body,
&amendment_scope,
depth,
&mut amended,
&value_type_defaults,
&src.mapping_value_types,
MappingInheritedDefault {
value: inherited_default,
entries: find_default_body_entries(&src.entries),
},
)?;
return Ok(Some(Value::Object(
Arc::new(amended),
Some(Arc::clone(src)),
)));
}
return Ok(Some(self.eval_amended_object(
existing_map,
src,
body,
scope,
depth,
)?));
}
let mut body_scope = scope.child();
body_scope.set("super", Value::Object(Arc::default(), None));
let val = self.eval_entries(body, &body_scope, depth)?;
return Ok(Some(val));
}
if let Some(ty) = &prop.type_ann {
if let Some(message) = type_default_error(ty, scope) {
return Err(Error::Eval(message));
}
let mut default = type_default_value(ty, scope);
// A class used as a property's implicit default denotes a fresh
// instance, not its unchecked class template. Rebuild it so
// member failures and declared types are checked before the
// property can render.
if let Some(Value::Object(map, Some(source))) = default.as_ref()
&& source.type_name.is_some()
{
let class_identity = source
.type_identity
.clone()
.or_else(|| source.type_name.clone())
.expect("typed class defaults always have an identity or name");
if !self.active_typed_defaults.insert(nm(&class_identity)) {
return Err(Error::Eval("recursive typed default".into()));
}
let instance = self.eval_amended_object(map, source, &[], scope, depth);
self.active_typed_defaults.remove(class_identity.as_str());
let instance = instance?;
if let Some(message) = rendered_member_failure(&instance) {
return Err(Error::Eval(message.to_string()));
}
default = Some(instance);
}
if let Some(default) = &mut default {
apply_mapping_type_annotation(default, Some(ty));
}
if require_union_default
&& default.is_none()
&& matches!(ty, crate::parser::TypeExpr::Union(variants) if !variants.iter().any(is_default_type))
{
return Err(Error::Eval(format!(
"union property '{}' has no selected default",
prop.name
)));
}
return Ok(default);
}
Ok(None)
}
pub(super) fn eval_entries(
&mut self,
entries: &Body,
scope: &Scope,
depth: usize,
) -> Result<Value> {
let mut receiver_scope = scope.clone();
receiver_scope.receiver_entries = Some(entries.clone());
receiver_scope.receiver_list_base = None;
self.eval_entries_with_lexical_scopes(
entries,
&receiver_scope,
depth,
None,
None,
None,
false,
None,
)
}
#[allow(clippy::too_many_arguments)] // Mapping context is independent of inherited source.
pub(super) fn eval_entries_with_lexical_scopes(
&mut self,
entries: &Body,
scope: &Scope,
depth: usize,
entry_scopes: Option<&[Option<Arc<CapturedScope>>]>,
inherited_source: Option<&ObjectSource>,
initial_non_const_members: Option<&HashSet<Name>>,
// Generator bodies do not inherit the receiver's source entries, but
// they do inherit its mapping-key semantics.
mapping_context: bool,
// For a generator body, the members its receiver holds so far. Its
// members are the receiver's, so a body amendment (`o { ... }` or
// `["k"] { ... }`) amends the receiver's existing member.
receiver_members: Option<&ReceiverMembers<'_>>,
) -> Result<Value> {
// A Mapping may retain the first spelling of a native-unit key, while
// Pkl identity is its normalized amount. Keep that rule in the shared
// amendment evaluator rather than selecting a second evaluator from
// the key's surface syntax.
let mapping_entries = mapping_context
|| inherited_source.is_some_and(|source| source.kind == ObjectKind::Mapping);
let mut child_scope = scope.child();
let entry_owners = entry_scope_owners(entries, entry_scopes, inherited_source);
let own_body = own_body_names(entries, entry_scopes, inherited_source);
// Inherited members whose entries are evaluated again below. Until its
// first entry runs, a member holds the parent's final value.
let mut inherited_seeded: HashSet<&str> = HashSet::default();
if let Some(source) = inherited_source {
for entry in source.entries.iter() {
if let Entry::Property(prop) = entry
&& !has_modifier(&prop.modifiers, Modifier::Local)
&& source.evaluated_properties.contains(&prop.name)
&& let Some(value) = source.scope().get(prop.name.as_ref())
{
child_scope.set(&prop.name, value.clone());
inherited_seeded.insert(prop.name.as_ref());
}
}
}
// Locals of an enclosing object that alias its `this` (`local self =
// this`) hold the same snapshot. Drop the ones this body never names so
// they are not captured by the object built here; `outer` keeps them
// when the body uses `outer`, since `outer.self` would still reach them.
let unused_this_aliases = {
let aliases = scope.visible_this_aliases();
if aliases.is_empty() {
aliases
} else {
let refs = self.body_referenced_roots(entries);
if refs.contains("outer") {
Vec::new()
} else {
aliases
.into_iter()
.filter(|name| !refs.contains(name))
.collect()
}
}
};
// `outer` is only reachable by name, so a body that never mentions it
// (the common case) skips flattening the enclosing scope for it.
if entries_mention(entries, "outer") || scope.type_aliases_mention("outer") {
bind_outer(&mut child_scope, scope, entries, &unused_this_aliases);
}
// Class-as-a-function definitions commonly use `local self = this` so
// output properties can close over the amended instance. Bind `this`
// before locals are evaluated, then keep direct aliases synchronized as
// properties populate the instance.
// A generator body is evaluated as a temporary object, but its `this`
// is the enclosing receiver. Seed its receiver view without copying
// those members into its output map.
let all_props: Arc<ObjectMap> = receiver_members.map_or_else(Arc::default, |members| {
let mut receiver = members
.outer
.map_or_else(ObjectMap::default, |outer| (*outer.own).clone());
receiver.extend(
members
.own
.iter()
.map(|(key, value)| (key.clone(), value.clone())),
);
Arc::new(receiver)
});
let this_aliases = Vec::<Name>::new();
refresh_this_aliases(&mut child_scope, &this_aliases, &all_props);
// Locals run before properties, so an untyped local may initially be
// unable to read a member of this body. Keep only those locals for a
// later retry as members bind; typed locals retain their existing
// failure behavior.
let failed_locals: Vec<usize> = Vec::new();
// A property may depend on one of those locals. This is deliberately
// narrower than a general object retry: only value properties that
// failed while a local was pending are revisited.
let failed_properties: Vec<(usize, String)> = Vec::new();
// Generators and other output entries can also read one of those
// deferred properties. Keep the whole entry for the same retry phase
// instead of treating the temporary poison as its final error.
let mut failed_entries: Vec<(usize, String)> = Vec::new();
// A const local may only read const members. Seed this with actual
// inherited members, then add own and generated members as they bind.
let mut non_const_members: HashSet<Name> = HashSet::default();
if let Some(source) = inherited_source {
for name in &source.evaluated_properties {
if body_member_is_non_const(&source.entries, name) {
non_const_members.insert(nm(name));
}
}
}
if let Some(initial) = initial_non_const_members {
non_const_members.extend(initial.iter().cloned());
}
// An own member shadows an enclosing binding even before evaluation.
// Include generator bodies too: an untaken branch must not make a
// const local capture an outer member of the same name.
let pending_members = body_property_names(entries);
let bound_members: HashSet<Name> = HashSet::default();
let mut cx = BodyContext {
entries,
scope,
depth,
entry_scopes,
inherited_source,
receiver_members,
mapping_entries,
entry_owners,
own_body,
pending_members,
deferred_lambdas: Vec::new(),
default_template: None,
track_dynamic_members: tracks_dynamic_members(entries),
};
let mut st = BodyState {
child_scope,
all_props,
this_aliases,
failed_locals,
failed_properties,
non_const_members,
bound_members,
inherited_seeded,
map: ObjectMap::default(),
member_entry_indices: HashMap::default(),
elements: Vec::new(),
generated: HashSet::default(),
defined_by_layer: None,
};
// First pass: collect locals, class definitions, and type aliases in
// declaration order so they can reference each other correctly.
// Non-lambda locals are evaluated eagerly; lambda locals are deferred
// to a second pass so they capture the fully-populated scope.
cx.deferred_lambdas = self.eval_body_declarations(&cx, &mut st)?;
self.guard_const_local_lambdas(
&mut st.child_scope,
&cx.deferred_lambdas,
&st.non_const_members,
);
cx.default_template = self.eval_default_template(&cx, &st)?;
let cx = cx;
for (entry_index, entry) in entries.iter().enumerate() {
// Only a failure while locals are still pending is deferred and
// retried, so the state is snapshotted only then. Entries never add
// to `failed_locals`, so empty before means empty after and the
// rollback arm below cannot be taken.
let rollback = (!st.failed_locals.is_empty()).then(|| st.clone());
match self.eval_output_entry(&cx, &mut st, entry_index, entry) {
Ok(()) => {}
Err(Error::Eval(message)) if rollback.is_some() && !st.failed_locals.is_empty() => {
st = rollback.expect("checked by the guard");
failed_entries.push((entry_index, message));
}
Err(error) => return Err(error),
}
}
// Revisit only the ordinary value properties deferred because they
// read a still-pending local. Once no deferred property recovers, the
// first current error is the one Pkl surfaces.
self.retry_failed_properties(&cx, &mut st)?;
// Retry non-property output entries only after ordinary properties
// have had a chance to resolve their deferred local dependencies.
// This includes nested generator bodies, spreads, elements, and
// dynamic entries that encountered a temporary poisoned property.
self.retry_failed_entries(&cx, &mut st, failed_entries)?;
// Evaluate deferred local lambdas (function definitions) AFTER all
// properties so they capture overridden values (late binding).
self.bind_deferred_lambdas(&cx, &mut st)?;
let hidden_aliases = unused_this_aliases
.iter()
// A binding of the same name made by this body shadows the alias.
.filter(|name| {
!st.child_scope.vars.contains_key(&**name)
&& !st.child_scope.poisoned.contains_key(&**name)
})
.map(|name| name_of(name))
.collect();
let source = ObjectSource {
entries: entries.clone(),
captured: SourceScope::lazy(&st.child_scope, hidden_aliases, Vec::new()),
body_members: cx
.own_body
.clone()
.unwrap_or_else(|| entries.iter().filter_map(entry_member_name).collect()),
is_open: true, // default: allow new properties
is_abstract: false,
type_name: None,
type_identity: None,
parent_type_names: Vec::new(),
parent_type_identities: Vec::new(),
entry_scopes: cx.entry_scopes.map(<[_]>::to_vec).unwrap_or_default(),
evaluated_properties: st.all_props.keys().cloned().collect(),
elements: st.elements,
mapping_value_types: Vec::new(),
deprecated: collect_deprecated(entries),
poisoned_members: None,
kind: ObjectKind::Object,
is_parsed_json: false,
prototype: None,
};
Ok(Value::Object(Arc::new(st.map), Some(Arc::new(source))))
}
/// Evaluate the locals, classes and type aliases of a body in declaration
/// order so they can reference each other. Non-lambda locals are
/// evaluated eagerly. Lambda locals are bound now for declaration-order
/// visibility, and returned to be bound again once the properties are
/// in scope.
fn eval_body_declarations<'a>(
&mut self,
cx: &BodyContext<'a, '_>,
st: &mut BodyState<'a>,
) -> Result<Vec<DeferredLambda<'a>>> {
// Direct properties are known to be non-const from their declaration,
// even before their value binds. Generator members stay absent here
// until a branch actually yields them.
let declared_direct_non_const_members: HashSet<Name> = cx
.entries
.iter()
.filter_map(|entry| match entry {
Entry::Property(prop)
if !has_modifier(&prop.modifiers, Modifier::Local)
&& !has_modifier(&prop.modifiers, Modifier::Const) =>
{
Some(prop.name.clone())
}
_ => None,
})
.collect();
let mut deferred_lambdas: Vec<(Name, &Property, &crate::parser::Expr, usize)> = Vec::new();
for (entry_index, entry) in cx.entries.iter().enumerate() {
// Only locals, classes and type aliases are handled in this pass,
// so build the entry's scope only for those.
if !matches!(
entry,
Entry::Property(prop)
if has_modifier(&prop.modifiers, Modifier::Local) && prop.value.is_some()
) && !matches!(entry, Entry::ClassDef(..) | Entry::TypeAlias(..))
{
continue;
}
let mut active_scope = scope_for_object_entry(
entry_index,
&st.child_scope,
cx.entry_scopes,
&cx.entry_owners,
cx.own_body_scope(),
);
if matches!(entry, Entry::Property(prop)
if has_modifier(&prop.modifiers, Modifier::Local)
&& (!matches!(prop.value.as_ref(), Some(Expr::Lambda(..)))
|| has_modifier(&prop.modifiers, Modifier::Const)))
{
for name in cx
.pending_members
.iter()
.filter(|name| !st.bound_members.contains(*name))
{
active_scope.poison(name.clone(), format!("undefined variable: {name}"));
}
}
match entry {
Entry::Property(prop)
if has_modifier(&prop.modifiers, Modifier::Local) && prop.value.is_some() =>
{
let expr = prop.value.as_ref().unwrap();
// Bind every local in declaration order so later locals and
// entries can reference it (e.g. a non-lambda local that
// calls a lambda local defined just above it).
let is_lambda = matches!(expr, Expr::Lambda(..));
let const_message = if is_lambda {
let mut lambda_non_const_members = st.non_const_members.clone();
lambda_non_const_members
.extend(declared_direct_non_const_members.iter().cloned());
const_local_reads_non_const(prop, &lambda_non_const_members)
} else {
const_local_reads_non_const(prop, &st.non_const_members)
};
let result = if is_lambda {
self.eval_expr(expr, &active_scope, cx.depth)
.map(|value| self.const_local_lambda_guard(value, const_message))
} else {
match const_message {
Some(message) => Err(Error::Eval(message)),
None => self.eval_expr(expr, &active_scope, cx.depth),
}
};
// Release the entry scope before binding, as for properties.
drop(active_scope);
match result {
Ok(val) => {
if cx.binds_declared(&prop.name) {
st.child_scope.declare(&prop.name, val);
} else {
st.child_scope.set(&prop.name, val);
}
if matches!(expr, Expr::Ident(name) if name == "this" || st.this_aliases.iter().any(|alias| **alias == **name))
{
st.this_aliases.push(prop.name.clone());
st.child_scope.mark_this_alias(&prop.name);
}
}
Err(Error::Eval(message)) => {
if prop.type_ann.is_none()
&& const_local_reads_non_const(prop, &st.non_const_members)
.is_none()
{
st.failed_locals.push(entry_index);
}
if cx.binds_declared(&prop.name) {
st.child_scope.declare_poisoned(prop.name.clone(), message);
} else {
st.child_scope.poison(prop.name.clone(), message);
}
}
Err(error) => return Err(error),
}
if matches!(expr, crate::parser::Expr::Lambda(..)) {
// Lambda evaluation only captures the current scope; it
// does not run the body. Bind once for declaration-order
// visibility, then re-bind after properties for late
// binding of overrides.
deferred_lambdas.push((prop.name.clone(), prop, expr, entry_index));
}
}
Entry::ClassDef(name, class_mods, parent, body) => {
let defaults = self.eval_class_def(
name,
class_mods,
parent.as_deref(),
body,
&active_scope,
cx.depth,
)?;
if cx.binds_declared(name) {
st.child_scope.declare(name, defaults);
} else {
st.child_scope.set(name, defaults);
}
}
Entry::TypeAlias(name, ty) => {
let mut resolved_scope = active_scope;
self.eval_type_alias(name, ty, &mut resolved_scope);
st.child_scope.set_type_alias(name.clone(), ty.clone());
if let Some(value) = resolved_scope.vars.get(name.as_str()) {
st.child_scope.set(name, value.clone());
}
}
_ => {}
}
}
Ok(deferred_lambdas)
}
/// Evaluate the body's `default` property, the template its other entries
/// amend.
fn eval_default_template(&mut self, cx: &BodyContext, st: &BodyState) -> Result<Option<Value>> {
let mut default_template: Option<Value> = None;
for (entry_index, entry) in cx.entries.iter().enumerate() {
let Entry::Property(prop) = entry else {
continue;
};
if &*prop.name != "default" || has_modifier(&prop.modifiers, Modifier::Local) {
continue;
}
let mut active_scope = scope_for_object_entry(
entry_index,
&st.child_scope,
cx.entry_scopes,
&cx.entry_owners,
cx.own_body_scope(),
);
if let Some(template) = &default_template {
active_scope.set("default", template.clone());
}
default_template = self.eval_property(prop, &active_scope, cx.depth)?;
}
Ok(default_template)
}
/// Retry the untyped locals that failed because they read a member not
/// yet bound, until a pass recovers none.
fn retry_failed_locals(&mut self, cx: &BodyContext, st: &mut BodyState) -> Result<()> {
let mut recovered = true;
while recovered {
recovered = false;
let mut retry_index = 0;
while retry_index < st.failed_locals.len() {
let entry_index = st.failed_locals[retry_index];
let Entry::Property(prop) = &cx.entries[entry_index] else {
unreachable!("only local properties are retried");
};
let Some(expr) = &prop.value else {
unreachable!("only valued local properties are retried");
};
if let Some(message) = const_local_reads_non_const(prop, &st.non_const_members) {
if cx.binds_declared(&prop.name) {
st.child_scope.declare_poisoned(prop.name.clone(), message);
} else {
st.child_scope.poison(prop.name.clone(), message);
}
st.failed_locals.swap_remove(retry_index);
continue;
}
let mut active_scope = scope_for_object_entry(
entry_index,
&st.child_scope,
cx.entry_scopes,
&cx.entry_owners,
cx.own_body_scope(),
);
for name in cx
.pending_members
.iter()
.filter(|name| !st.bound_members.contains(*name))
{
active_scope.poison(name.clone(), format!("undefined variable: {name}"));
}
let result = self.eval_expr(expr, &active_scope, cx.depth);
drop(active_scope);
match result {
Ok(value) => {
if cx.binds_declared(&prop.name) {
st.child_scope.declare(&prop.name, value);
} else {
st.child_scope.set(&prop.name, value);
}
if matches!(expr, Expr::Ident(name) if name == "this" || st.this_aliases.iter().any(|alias| **alias == **name))
{
st.this_aliases.push(prop.name.clone());
st.child_scope.mark_this_alias(&prop.name);
}
st.failed_locals.swap_remove(retry_index);
recovered = true;
}
Err(Error::Eval(message)) => {
if cx.binds_declared(&prop.name) {
st.child_scope.declare_poisoned(prop.name.clone(), message);
} else {
st.child_scope.poison(prop.name.clone(), message);
}
retry_index += 1;
}
Err(error) => return Err(error),
}
}
}
Ok(())
}
/// Bind a property's value in the body: in its scope, its members and,
/// unless hidden, its output. A `recovered` property, one evaluated again
/// after its local bound, returns to its declaration position.
fn bind_object_property_value(
&mut self,
cx: &BodyContext,
st: &mut BodyState,
prop: &Property,
value: Value,
entry_index: usize,
recovered: bool,
) -> Result<()> {
st.generated.remove(prop.name.as_ref());
if cx.binds_declared(&prop.name) {
st.child_scope.declare(&prop.name, value.clone());
} else {
st.child_scope.set(&prop.name, value.clone());
}
cx.entry_owners.release_this(&st.this_aliases);
if recovered {
let index = st
.all_props
.iter()
.position(|(key, _)| {
st.member_entry_indices
.get(key)
.is_some_and(|existing| *existing > entry_index)
})
.unwrap_or_else(|| st.all_props.len());
props_shift_insert(
&mut st.child_scope,
&st.this_aliases,
&mut st.all_props,
index,
prop.name.clone(),
value.clone(),
);
} else {
props_insert(
&mut st.child_scope,
&st.this_aliases,
&mut st.all_props,
prop.name.clone(),
value.clone(),
);
}
if !has_modifier(&prop.modifiers, Modifier::Hidden) {
if recovered {
let index = st
.map
.iter()
.position(|(key, _)| {
st.member_entry_indices
.get(key)
.is_some_and(|existing| *existing > entry_index)
})
.unwrap_or_else(|| st.map.len());
st.map.shift_insert(index, prop.name.as_ref().into(), value);
} else {
st.map.insert(prop.name.as_ref().into(), value);
}
}
st.member_entry_indices
.insert(prop.name.as_ref().into(), entry_index);
if !has_modifier(&prop.modifiers, Modifier::Const) {
st.non_const_members.insert(prop.name.clone());
}
st.bound_members.insert(prop.name.clone());
self.guard_const_local_lambdas(
&mut st.child_scope,
&cx.deferred_lambdas,
&st.non_const_members,
);
refresh_this_aliases(&mut st.child_scope, &st.this_aliases, &st.all_props);
self.retry_failed_locals(cx, st)?;
Ok(())
}
/// Evaluate one output entry of a body: a property, a dynamic member, a
/// spread, a generator or an element.
fn eval_output_entry<'a>(
&mut self,
cx: &BodyContext<'a, '_>,
st: &mut BodyState<'a>,
entry_index: usize,
entry: &'a Entry,
) -> Result<()> {
match entry {
Entry::Property(prop) => {
self.eval_property_entry(cx, st, entry_index, prop)?;
}
Entry::DynProperty(key_expr, val_expr) => {
self.eval_dynamic_entry(cx, st, entry_index, key_expr, val_expr)?;
}
Entry::Spread(expr) => {
let active_scope = scope_for_object_entry(
entry_index,
&st.child_scope,
cx.entry_scopes,
&cx.entry_owners,
cx.own_body_scope(),
);
let val = self.eval_expr(expr, &active_scope, cx.depth)?;
check_iterable(&val)?;
match val {
Value::Object(m, source) => {
if let Some(inherited) = cx.inherited_source
&& let Some(message) =
immutable_copied_member_error(m.keys(), inherited)
{
return Err(Error::Eval(message));
}
drop(active_scope);
cx.entry_owners.release_this(&st.this_aliases);
props_extend_mapping(
&mut st.child_scope,
&st.this_aliases,
&mut st.all_props,
m.iter().map(|(k, v)| (k.clone(), v.clone())),
cx.mapping_entries,
);
extend_object_entries(&mut st.map, &m, cx.mapping_entries);
st.member_entry_indices
.extend(m.keys().cloned().map(|key| (key, entry_index)));
if let Some(source) = source {
st.elements.extend(source.elements.iter().cloned());
}
refresh_this_aliases(&mut st.child_scope, &st.this_aliases, &st.all_props);
}
Value::List(items) => st.elements.extend(items.iter().cloned()),
_ => unreachable!("check_iterable accepted an unsupported value"),
}
}
Entry::ForGenerator(fgen) => {
let active_scope = scope_for_object_entry(
entry_index,
&st.child_scope,
cx.entry_scopes,
&cx.entry_owners,
cx.own_body_scope(),
);
let collection = self.eval_expr(&fgen.collection, &active_scope, cx.depth)?;
let items = collection_to_items(collection)?;
for (k, v) in items {
let mut iter_scope = active_scope.child();
iter_scope.set(&fgen.val_var, v);
if let Some(key_var) = &fgen.key_var {
iter_scope.set(key_var, k);
}
let body_val = self.eval_entries_with_lexical_scopes(
&fgen.body,
&iter_scope,
cx.depth,
None,
None,
None,
cx.mapping_entries,
Some(&ReceiverMembers {
own: &st.all_props,
outer: cx.receiver_members,
}),
)?;
if let Value::Object(m, source) = body_val {
self.merge_generated_members(cx, st, entry_index, &fgen.body, &m, source)?;
}
}
}
Entry::WhenGenerator(wgen) => {
let active_scope = scope_for_object_entry(
entry_index,
&st.child_scope,
cx.entry_scopes,
&cx.entry_owners,
cx.own_body_scope(),
);
let cond = self.eval_expr(&wgen.condition, &active_scope, cx.depth)?;
if is_truthy(&cond) {
let body_val = self.eval_entries_with_lexical_scopes(
&wgen.body,
&active_scope,
cx.depth,
None,
None,
None,
cx.mapping_entries,
Some(&ReceiverMembers {
own: &st.all_props,
outer: cx.receiver_members,
}),
)?;
if let Value::Object(m, source) = body_val {
self.merge_generated_members(cx, st, entry_index, &wgen.body, &m, source)?;
}
} else if let Some(else_body) = &wgen.else_body {
let else_val = self.eval_entries_with_lexical_scopes(
else_body,
&active_scope,
cx.depth,
None,
None,
None,
cx.mapping_entries,
Some(&ReceiverMembers {
own: &st.all_props,
outer: cx.receiver_members,
}),
)?;
if let Value::Object(m, source) = else_val {
self.merge_generated_members(cx, st, entry_index, else_body, &m, source)?;
}
}
}
Entry::Elem(expr) => {
let active_scope = scope_for_object_entry(
entry_index,
&st.child_scope,
cx.entry_scopes,
&cx.entry_owners,
cx.own_body_scope(),
);
st.elements
.push(self.eval_expr(expr, &active_scope, cx.depth + 1)?);
}
Entry::ClassDef(..) | Entry::TypeAlias(..) => {} // handled in scope setup
Entry::Predicate(..) => return Err(member_predicates_unsupported()),
}
Ok(())
}
/// Evaluate a property entry of the body and bind its value.
fn eval_property_entry(
&mut self,
cx: &BodyContext,
st: &mut BodyState,
entry_index: usize,
prop: &Property,
) -> Result<()> {
let mods = &prop.modifiers;
if has_modifier(mods, Modifier::Local) {
return Ok(());
}
// Skip the `default` property — it's a template, not an output entry
if &*prop.name == "default" && cx.default_template.is_some() {
return Ok(());
}
if has_modifier(mods, Modifier::Abstract) && prop.value.is_none() && prop.body.is_none() {
return Ok(()); // abstract without value — skip (must be overridden)
}
// The first entry of a re-evaluated inherited member starts
// its amendment chain. Amending the parent's final value
// would apply the inherited bodies twice (`l { 1 }`
// amended again with `1`), so it starts from no value.
if st.inherited_seeded.remove(prop.name.as_ref())
&& prop.value.is_none()
&& prop.body.is_some()
{
st.child_scope.set(&prop.name, Value::Null);
}
refresh_this_aliases(&mut st.child_scope, &st.this_aliases, &st.all_props);
let mut active_scope = scope_for_object_entry(
entry_index,
&st.child_scope,
cx.entry_scopes,
&cx.entry_owners,
cx.own_body_scope(),
);
// eval_property amends the value bound for the name in the
// receiver's own scope. A generator body can amend both a
// member previously generated in this body and one held by
// its enclosing receiver.
if prop.value.is_none()
&& prop.body.is_some()
&& let Some(existing) = st.all_props.get(prop.name.as_ref()).or_else(|| {
cx.receiver_members
.and_then(|members| members.get(prop.name.as_ref()))
})
{
active_scope.set(&prop.name, existing.clone());
}
let value = match self.eval_property(prop, &active_scope, cx.depth) {
Ok(value) => value,
Err(Error::Eval(message)) if prop.value.is_some() && !st.failed_locals.is_empty() => {
// This body declaration shadows an enclosing or
// inherited property even while its local
// dependency is unresolved. Keep later members
// from binding that stale value before retry.
drop(active_scope);
if cx.binds_declared(&prop.name) {
st.child_scope
.declare_poisoned(prop.name.clone(), message.clone());
} else {
st.child_scope.poison(prop.name.clone(), message.clone());
}
st.failed_properties.push((entry_index, message));
return Ok(());
}
Err(error) => return Err(error),
};
// Release the entry scope first: it may share the object
// scope's bindings, which binding the value would then copy.
drop(active_scope);
if let Some(v) = value {
self.bind_object_property_value(cx, st, prop, v, entry_index, false)?;
}
Ok(())
}
/// Evaluate a dynamic member, `[key] = value` or `[key] { ... }`, which
/// amends an existing entry of that key.
fn eval_dynamic_entry(
&mut self,
cx: &BodyContext,
st: &mut BodyState,
entry_index: usize,
key_expr: &Expr,
val_expr: &Expr,
) -> Result<()> {
let active_scope = scope_for_object_entry(
entry_index,
&st.child_scope,
cx.entry_scopes,
&cx.entry_owners,
cx.own_body_scope(),
);
let class_key = self.class_key_of(key_expr, &active_scope);
let key = class_key
.is_none()
.then(|| self.eval_expr(key_expr, &active_scope, cx.depth))
.transpose()?;
let key_str = match class_key {
Some(key) => key,
None => value_to_key(key.as_ref().expect("non-class mapping keys are evaluated"))?,
};
let storage_key = if cx.mapping_entries {
equivalent_mapping_key(&st.map, &key_str).unwrap_or_else(|| key_str.clone())
} else {
key_str.clone()
};
if cx.mapping_entries
&& let Some(key) = key.as_ref()
{
self.remember_mapping_key(storage_key.clone(), key);
}
// A body may define each key once. An object body still
// amends an inherited value, but it is a definition in
// this body and must participate in duplicate detection.
if cx.track_dynamic_members {
let defined_by_layer = st.defined_by_layer.get_or_insert_default();
let layer = entry_layer(cx.entry_scopes, entry_index);
let duplicate = cx.mapping_entries
&& defined_by_layer.iter().any(|(defined_layer, defined_key)| {
*defined_layer == layer
&& crate::value::mapping_storage_keys_equal(defined_key, &key_str)
});
if duplicate || !defined_by_layer.insert((layer, key_str.clone())) {
let key = match key.as_ref() {
None => key_str.to_string(),
Some(Value::String(s)) => format!("{s:?}"),
Some(key) => value_to_display(key),
};
return Err(Error::Eval(format!(
"Duplicate definition of member `{key}`."
)));
}
}
// `["key"] { ... }` amends an entry inherited from the parent
// (for example when amending an untyped `Mapping`) rather than
// replacing it.
if let Expr::ObjectBody(body) = val_expr
&& let Some(existing @ (Value::Object(..) | Value::List(_))) = st
.map
.get(&storage_key)
.or_else(|| {
cx.receiver_members.and_then(|members| {
if cx.mapping_entries {
equivalent_mapping_key(members.own, &key_str)
.and_then(|key| members.own.get(&key))
.or_else(|| {
members.outer.and_then(|outer| {
equivalent_mapping_key(outer.own, &key_str)
.and_then(|key| outer.own.get(&key))
})
})
} else {
members.get(&key_str)
}
})
})
.cloned()
{
// A listing amendment only takes elements, so a property
// would otherwise be dropped silently. Reject it as Pkl does.
if matches!(existing, Value::List(_))
&& let Some(name) = find_listing_body_property(body)
{
return Err(Error::Eval(format!(
"cannot amend listing entry '{key_str}' with property '{name}': \
object of type Listing cannot have a property (other than default)"
)));
}
let val = self.eval_value_amendment(existing, body, &active_scope, cx.depth)?;
drop(active_scope);
cx.entry_owners.release_this(&st.this_aliases);
props_insert_mapping(
&mut st.child_scope,
&st.this_aliases,
&mut st.all_props,
storage_key.clone(),
val.clone(),
cx.mapping_entries,
);
st.member_entry_indices
.insert(storage_key.clone(), entry_index);
st.map.insert(storage_key, val);
refresh_this_aliases(&mut st.child_scope, &st.this_aliases, &st.all_props);
self.retry_failed_locals(cx, st)?;
return Ok(());
}
let val = if let Some(Value::Object(template_map, Some(src))) = &cx.default_template
&& let Expr::ObjectBody(body) = val_expr
{
// Default template has ObjectSource — use eval_amended_object
// so nested property amendments work properly.
let mut result =
self.eval_amended_object(template_map, src, body, &active_scope, cx.depth)?;
// Propagate the template's type_name so converters can match.
if let Some(ref tn) = src.type_name
&& let Value::Object(_, ref mut result_src) = result
{
let new_src = match result_src.take() {
Some(s) => {
let mut ns = Arc::unwrap_or_clone(s);
ns.type_name = Some(tn.clone());
ns
}
None => ObjectSource {
entries: vec![].into(),
captured: SourceScope::default(),
body_members: HashSet::default(),
is_open: true,
is_abstract: false,
type_name: Some(tn.clone()),
type_identity: src.type_identity.clone(),
parent_type_names: src.parent_type_names.clone(),
parent_type_identities: src.parent_type_identities.clone(),
entry_scopes: Vec::new(),
evaluated_properties: Vec::new(),
elements: Vec::new(),
mapping_value_types: Vec::new(),
deprecated: merge_deprecated(&src.deprecated, body),
poisoned_members: None,
kind: ObjectKind::Object,
is_parsed_json: false,
prototype: None,
},
};
*result_src = Some(std::sync::Arc::new(new_src));
}
result
} else {
let mut val = self.eval_expr(val_expr, &active_scope, cx.depth)?;
if let Some(ref tpl) = cx.default_template {
val = merge_values(tpl.clone(), val);
}
val
};
drop(active_scope);
cx.entry_owners.release_this(&st.this_aliases);
props_insert_mapping(
&mut st.child_scope,
&st.this_aliases,
&mut st.all_props,
storage_key.clone(),
val.clone(),
cx.mapping_entries,
);
st.member_entry_indices
.insert(storage_key.clone(), entry_index);
st.map.insert(storage_key, val);
refresh_this_aliases(&mut st.child_scope, &st.this_aliases, &st.all_props);
self.retry_failed_locals(cx, st)?;
Ok(())
}
/// Merge the members a generator body produced into this body: its
/// members and output, its elements, and the members const locals may not
/// read. Locals waiting on a member are then retried.
fn merge_generated_members(
&mut self,
cx: &BodyContext,
st: &mut BodyState,
entry_index: usize,
body: &Body,
m: &ObjectMap,
source: Option<Arc<ObjectSource>>,
) -> Result<()> {
if let Some(inherited) = cx.inherited_source
&& let Some(message) = immutable_copied_member_error(m.keys(), inherited)
{
return Err(Error::Eval(message));
}
if cx.track_dynamic_members {
record_generated_members(
st.defined_by_layer.get_or_insert_default(),
entry_layer(cx.entry_scopes, entry_index),
m,
body,
cx.mapping_entries,
)?;
}
cx.entry_owners.release_this(&st.this_aliases);
props_extend_mapping(
&mut st.child_scope,
&st.this_aliases,
&mut st.all_props,
m.iter().map(|(k, v)| (k.clone(), v.clone())),
cx.mapping_entries,
);
for name in m.keys() {
if body_member_is_non_const(body, name) {
st.non_const_members.insert(nm(name));
}
}
st.bound_members.extend(m.keys().cloned());
self.guard_const_local_lambdas(
&mut st.child_scope,
&cx.deferred_lambdas,
&st.non_const_members,
);
st.generated.extend(m.keys().cloned());
extend_object_entries(&mut st.map, m, cx.mapping_entries);
st.member_entry_indices
.extend(m.keys().cloned().map(|key| (key, entry_index)));
if let Some(source) = source {
st.elements.extend(source.elements.iter().cloned());
}
refresh_this_aliases(&mut st.child_scope, &st.this_aliases, &st.all_props);
self.retry_failed_locals(cx, st)?;
Ok(())
}
/// Evaluate again the value properties deferred because they read a
/// still-pending local. Once no deferred property recovers, the first
/// current error is the one Pkl surfaces.
fn retry_failed_properties(&mut self, cx: &BodyContext, st: &mut BodyState) -> Result<()> {
while !st.failed_properties.is_empty() {
let mut retrying = std::mem::take(&mut st.failed_properties);
let mut recovered_property = false;
for (entry_index, _) in retrying.drain(..) {
let Entry::Property(prop) = &cx.entries[entry_index] else {
unreachable!("only properties are deferred");
};
let active_scope = scope_for_object_entry(
entry_index,
&st.child_scope,
cx.entry_scopes,
&cx.entry_owners,
cx.own_body_scope(),
);
match self.eval_property(prop, &active_scope, cx.depth) {
Ok(value) => {
drop(active_scope);
if let Some(value) = value {
self.bind_object_property_value(
cx,
st,
prop,
value,
entry_index,
true,
)?;
}
recovered_property = true;
}
Err(Error::Eval(message)) => {
drop(active_scope);
st.failed_properties.push((entry_index, message));
}
Err(error) => return Err(error),
}
}
if !recovered_property {
return Err(Error::Eval(st.failed_properties[0].1.clone()));
}
}
Ok(())
}
/// Evaluate again the non-property output entries that failed while a
/// local was pending, restoring the body's state after each that fails
/// again. Once none recovers, the first current error is the one Pkl
/// surfaces.
fn retry_failed_entries<'a>(
&mut self,
cx: &BodyContext<'a, '_>,
st: &mut BodyState<'a>,
mut failed_entries: Vec<(usize, String)>,
) -> Result<()> {
while !failed_entries.is_empty() {
let mut retrying = std::mem::take(&mut failed_entries);
let mut recovered_entry = false;
for (entry_index, _) in retrying.drain(..) {
let entry = &cx.entries[entry_index];
let before = st.clone();
match self.eval_output_entry(cx, st, entry_index, entry) {
Ok(()) => recovered_entry = true,
Err(Error::Eval(message)) => {
*st = before;
failed_entries.push((entry_index, message));
}
Err(error) => return Err(error),
}
}
if !recovered_entry {
return Err(Error::Eval(failed_entries[0].1.clone()));
}
}
Ok(())
}
/// Bind the deferred local lambdas again, now that the properties are
/// bound, so they capture overridden values (late binding).
fn bind_deferred_lambdas(&mut self, cx: &BodyContext, st: &mut BodyState) -> Result<()> {
refresh_this_aliases(&mut st.child_scope, &st.this_aliases, &st.all_props);
for &(ref name, prop, expr, entry_index) in &cx.deferred_lambdas {
let active_scope = scope_for_object_entry(
entry_index,
&st.child_scope,
cx.entry_scopes,
&cx.entry_owners,
cx.own_body_scope(),
);
let val = self.eval_expr(expr, &active_scope, cx.depth)?;
drop(active_scope);
// Lambda construction is lazy, so const-local validation must be
// deferred until invocation too. At this point the final object
// members are known; make a forbidden lambda body fail when it is
// called without rejecting an otherwise unused local function.
let val = self.const_local_lambda_guard(
val,
const_local_reads_non_const(prop, &st.non_const_members),
);
st.child_scope.set(name, val);
}
Ok(())
}
}
/// A local lambda of a body, bound again once the body's properties are:
/// its name, declaration, value and entry index.
type DeferredLambda<'a> = (Name, &'a Property, &'a Expr, usize);
/// What stays fixed while one object body is evaluated.
struct BodyContext<'a, 'r> {
entries: &'a Body,
/// The scope the body is evaluated in.
scope: &'a Scope,
depth: usize,
entry_scopes: Option<&'a [Option<Arc<CapturedScope>>]>,
inherited_source: Option<&'a ObjectSource>,
receiver_members: Option<&'a ReceiverMembers<'r>>,
/// Whether the body's keys follow Mapping identity: a Mapping may retain
/// the first spelling of a native-unit key, while Pkl identity is its
/// normalized amount.
mapping_entries: bool,
entry_owners: EntryOwners,
/// The names of the body's own definition body, when it has one.
own_body: Option<HashSet<Name>>,
/// The body's own members, which shadow an enclosing binding even before
/// they are evaluated.
pending_members: HashSet<Name>,
deferred_lambdas: Vec<DeferredLambda<'a>>,
default_template: Option<Value>,
/// Whether member names must be tracked for duplicates. A single direct
/// dynamic member cannot conflict with anything. Avoid the hash lookup on
/// that common shape; tracking is needed only once a second dynamic member
/// or a generator can produce another name.
track_dynamic_members: bool,
}
impl BodyContext<'_, '_> {
/// Entries without a captured scope belong to the object's own
/// definition body. Bindings they see as declared are that body's
/// members; members the object inherits from elsewhere (a parent class
/// or an amendment) are not, so a nested object's inherited member of
/// the same name still resolves through its own `this`.
fn binds_declared(&self, name: &str) -> bool {
self.own_body.as_ref().is_none_or(|own| own.contains(name))
}
fn own_body_scope(&self) -> Option<(&Scope, &HashSet<Name>)> {
self.own_body.as_ref().map(|own| (self.scope, own))
}
}
/// What evaluating an object body builds up. An entry that fails while a
/// local is still pending restores a copy of it, to be evaluated again.
#[derive(Clone)]
struct BodyState<'a> {
child_scope: Scope,
all_props: Arc<ObjectMap>,
this_aliases: Vec<Name>,
/// Untyped locals that failed, possibly because they read a member of
/// this body not yet bound.
failed_locals: Vec<usize>,
/// Value properties that failed while a local was pending.
failed_properties: Vec<(usize, String)>,
/// The members a const local may not read.
non_const_members: HashSet<Name>,
bound_members: HashSet<Name>,
/// Inherited members whose entries are evaluated again. Until its first
/// entry runs, a member holds the parent's final value.
inherited_seeded: HashSet<&'a str>,
map: ObjectMap,
/// Source entry positions for members already emitted. A property that
/// recovers after its local becomes available uses these to return to
/// its declaration position instead of remaining appended at the end.
member_entry_indices: HashMap<Arc<str>, usize>,
/// A Dynamic body can contain bare elements as well as named members.
/// Keep the former separately so XML elements can render precisely the
/// values Pkl gives them, in source order.
elements: Vec<Value>,
/// Names of members produced by generators and not since rebound by a
/// property entry.
generated: HashSet<Arc<str>>,
/// The members each layer defines. The output map is keyed by its
/// rendered member name, so duplicate bookkeeping must use that same
/// identity. Sharing the set with generators makes direct-before-generator
/// and generator-before-direct checks symmetric.
defined_by_layer: Option<HashSet<(usize, Arc<str>)>>,
}
/// Whether a body needs its dynamic member names tracked for duplicates: it
/// has a second dynamic member, or a generator that can produce one.
fn tracks_dynamic_members(entries: &[Entry]) -> bool {
let mut direct_dynamic_members = 0;
let mut track_dynamic_members = false;
for entry in entries.iter() {
match entry {
Entry::DynProperty(..) => {
direct_dynamic_members += 1;
track_dynamic_members |= direct_dynamic_members > 1;
}
Entry::ForGenerator(..) | Entry::WhenGenerator(..) => {
track_dynamic_members = true;
}
_ => {}
}
}
track_dynamic_members
}
/// Set `outer` to a snapshot of the parent scope's variables as an object.
/// Also insert Null for any nullable-no-default properties declared in these
/// entries but absent from the parent scope, so that `outer.optionalProp`
/// resolves to Null rather than failing with "field not found".
fn bind_outer(
child_scope: &mut Scope,
scope: &Scope,
entries: &[Entry],
unused_this_aliases: &[Name],
) {
let mut outer_map = scope.flatten();
// `this` inside the body is rebound to the new object, so the parent's
// `this` snapshot is unreachable through `outer`. Leaving it out keeps
// nested objects from holding a reference to the parent's property map,
// which would otherwise force a full copy on every parent insert.
outer_map.shift_remove("this");
for name in unused_this_aliases {
outer_map.shift_remove(&**name);
}
for entry in entries.iter() {
if let Entry::Property(prop) = entry
&& prop.value.is_none()
&& prop.body.is_none()
&& !has_modifier(&prop.modifiers, Modifier::Local)
&& !outer_map.contains_key(prop.name.as_ref())
&& matches!(prop.type_ann, Some(crate::parser::TypeExpr::Nullable(_)))
{
outer_map.insert(prop.name.as_ref().into(), Value::Null);
}
}
let outer_obj = Value::Object(Arc::new(outer_map), None);
child_scope.set("outer", outer_obj);
}
/// Whether a body (or a generator in it) has a member matching `is_kind`.
pub(super) fn body_has(entries: &[Entry], is_kind: &dyn Fn(&Entry) -> bool) -> bool {
entries.iter().any(|entry| match entry {
Entry::ForGenerator(generator) => body_has(&generator.body, is_kind),
Entry::WhenGenerator(generator) => {
body_has(&generator.body, is_kind)
|| generator
.else_body
.as_deref()
.is_some_and(|body| body_has(body, is_kind))
}
entry => is_kind(entry),
})
}
/// Whether an evaluated member of `entries` is a non-const property. A name
/// is considered only after the entry that produced it actually ran, so a
/// member in an untaken generator branch does not turn a const-local lookup
/// into a const violation.
pub(super) fn body_member_is_non_const(entries: &[Entry], name: &str) -> bool {
entries.iter().rev().any(|entry| match entry {
Entry::Property(prop)
if &*prop.name == name && !has_modifier(&prop.modifiers, Modifier::Local) =>
{
!has_modifier(&prop.modifiers, Modifier::Const)
}
Entry::ForGenerator(generator) => body_member_is_non_const(&generator.body, name),
Entry::WhenGenerator(generator) => {
body_member_is_non_const(&generator.body, name)
|| generator
.else_body
.as_deref()
.is_some_and(|body| body_member_is_non_const(body, name))
}
_ => false,
})
}
/// Names a body can define as object properties, including names in generator
/// branches that may later bind. They must shadow enclosing bindings while a
/// const local waits to learn whether the branch actually produces them.
pub(super) fn body_property_names(entries: &[Entry]) -> HashSet<Name> {
let mut names = HashSet::default();
for entry in entries {
match entry {
Entry::Property(prop) if !has_modifier(&prop.modifiers, Modifier::Local) => {
names.insert(prop.name.clone());
}
Entry::ForGenerator(generator) => names.extend(body_property_names(&generator.body)),
Entry::WhenGenerator(generator) => {
names.extend(body_property_names(&generator.body));
if let Some(else_body) = &generator.else_body {
names.extend(body_property_names(else_body));
}
}
_ => {}
}
}
names
}
/// Pkl requires a const local to depend only on const members of its body.
/// Bare references are collected with the evaluator's normal lexical walker;
/// `this.member` and `super.member` need their own checks because the walker
/// records the receiver as the root rather than the selected member.
pub(super) fn const_local_reads_non_const(
prop: &Property,
non_const_members: &HashSet<Name>,
) -> Option<String> {
if !has_modifier(&prop.modifiers, Modifier::Const) {
return None;
}
let expr = prop.value.as_ref()?;
let mut refs = HashSet::default();
collect_expr_refs(expr, &mut refs, &HashSet::default());
let name = refs
.into_iter()
.find(|name| non_const_members.contains(name))
.map(|name| name.to_string())
.or_else(|| this_member_reads_non_const(expr, non_const_members))?;
Some(format!(
"Cannot reference property `{name}` from here because it is not `const`."
))
}
/// Return the first non-const member read through a direct `this.member` or
/// `super.member` expression. Nested object bodies have their own receiver,
/// so this deliberately does not descend into them.
pub(super) fn this_member_reads_non_const(
expr: &Expr,
non_const_members: &HashSet<Name>,
) -> Option<String> {
match expr {
Expr::Field(base, name) | Expr::NullSafeField(base, name)
if matches!(base.as_ref(), Expr::Ident(root) if root == "this" || root == "super")
&& non_const_members.contains(name.as_str()) =>
{
Some(name.clone())
}
Expr::Field(base, _) | Expr::NullSafeField(base, _) => {
this_member_reads_non_const(base, non_const_members)
}
Expr::Index(base, index) | Expr::Binop(_, base, index) => {
this_member_reads_non_const(base, non_const_members)
.or_else(|| this_member_reads_non_const(index, non_const_members))
}
Expr::Call(callee, args) => {
this_member_reads_non_const(callee, non_const_members).or_else(|| {
args.iter()
.find_map(|arg| this_member_reads_non_const(arg, non_const_members))
})
}
Expr::If(condition, then_expr, else_expr) => {
this_member_reads_non_const(condition, non_const_members)
.or_else(|| this_member_reads_non_const(then_expr, non_const_members))
.or_else(|| this_member_reads_non_const(else_expr, non_const_members))
}
Expr::Let(_, value, body) => this_member_reads_non_const(value, non_const_members)
.or_else(|| this_member_reads_non_const(body, non_const_members)),
Expr::Is(value, _) | Expr::As(value, _) => {
this_member_reads_non_const(value, non_const_members)
}
Expr::Lambda(_, value) => this_member_reads_non_const(value, non_const_members),
Expr::Unop(_, value)
| Expr::Throw(value)
| Expr::TemplateLocals(_, value)
| Expr::Trace(value, _)
| Expr::Read(value, _)
| Expr::ReadOrNull(value, _)
| Expr::ReadGlob(value, _) => this_member_reads_non_const(value, non_const_members),
Expr::StringInterpolation(parts) => parts.iter().find_map(|part| match part {
StringInterpPart::Expr(expr) => this_member_reads_non_const(expr, non_const_members),
StringInterpPart::Literal(_) => None,
}),
// New and anonymous-object bodies create their own receivers.
Expr::New(..) | Expr::InferredNew(..) | Expr::ObjectBody(..) | _ => None,
}
}
/// Reject elements in the body of an object of type `type_display`, and
/// entries too when `typed` (a class instance has only properties).
pub(super) fn check_member_kinds(type_display: &str, entries: &[Entry], typed: bool) -> Result<()> {
if body_has(entries, &|entry| matches!(entry, Entry::Elem(_))) {
return Err(Error::Eval(format!(
"Object of type `{type_display}` cannot have an element."
)));
}
if typed && body_has(entries, &|entry| matches!(entry, Entry::DynProperty(..))) {
return Err(Error::Eval(format!(
"Object of type `{type_display}` cannot have an entry."
)));
}
Ok(())
}
/// The members a generator body's receiver holds so far: those of the object
/// it is directly in, over those of any generator body enclosing that. The
/// maps are borrowed rather than merged so nested generators copy nothing.
pub(super) struct ReceiverMembers<'a> {
own: &'a ObjectMap,
outer: Option<&'a ReceiverMembers<'a>>,
}
impl ReceiverMembers<'_> {
fn get(&self, name: &str) -> Option<&Value> {
self.own
.get(name)
.or_else(|| self.outer.and_then(|outer| outer.get(name)))
}
}