kcl-lib 0.2.186

KittyCAD Language implementation and tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
use std::collections::BTreeMap;
use std::str::FromStr;
use std::sync::Arc;

use ahash::AHashMap;
use anyhow::Result;
use indexmap::IndexMap;
pub use kcl_api::KclVersion;
use kcl_api::UnitAngle;
use kcl_api::UnitLength;
use serde::Deserialize;
use serde::Serialize;
use uuid::Uuid;

use crate::CompilationIssue;
use crate::ExecutorContext;
use crate::KclErrorWithOutputs;
use crate::MockConfig;
use crate::NodePath;
use crate::SegmentDragAnchor;
use crate::SourceRange;
use crate::collections::AhashIndexSet;
use crate::engine::engine_manager::EngineManager;
use crate::errors::KclError;
use crate::errors::KclErrorDetails;
use crate::errors::Severity;
use crate::exec::DefaultPlanes;
use crate::execution::Artifact;
use crate::execution::ArtifactCommand;
use crate::execution::ArtifactGraph;
use crate::execution::ArtifactId;
use crate::execution::ConstrainableLine2d;
use crate::execution::EnvironmentRef;
use crate::execution::ExecOutcome;
use crate::execution::ExecutorSettings;
use crate::execution::KclValue;
use crate::execution::KclValueView;
use crate::execution::OperationCallbackArgs;
use crate::execution::OperationsByModule;
use crate::execution::ProgramLookup;
use crate::execution::SketchVarId;
use crate::execution::UnsolvedSegment;
use crate::execution::annotations;
use crate::execution::cad_op::Operation;
use crate::execution::id_generator::IdGenerator;
#[cfg(test)]
use crate::execution::memory::MemoryBackendKind;
use crate::execution::memory::ProgramMemory;
use crate::execution::memory::Stack;
use crate::execution::sketch_solve::Solved;
use crate::execution::types::NumericType;
use crate::front::Number;
use crate::front::Object;
use crate::front::ObjectId;
use crate::front::ObjectKind;
use crate::id::IncIdGenerator;
use crate::modules::ModuleId;
use crate::modules::ModuleInfo;
use crate::modules::ModuleLoader;
use crate::modules::ModulePath;
use crate::modules::ModuleRepr;
use crate::modules::ModuleSource;
use crate::parsing::ast::types::Annotation;
use crate::parsing::ast::types::Node;
use crate::parsing::ast::types::NodeRef;
use crate::parsing::ast::types::Program;
use crate::parsing::ast::types::TagNode;

/// State for executing a program.
#[derive(Debug, Clone)]
pub struct ExecState {
    pub(super) execution_callbacks: Option<std::sync::Arc<dyn crate::execution::ExecutionCallbacks>>,
    pub(super) global: GlobalState,
    pub(super) mod_local: ModuleState,
}

pub type ModuleInfoMap = IndexMap<ModuleId, ModuleInfo>;

#[derive(Debug, Clone)]
pub(super) struct GlobalState {
    /// The deepest machine-executor call depth reached by executions sharing
    /// this state: the root module, its callbacks, and module bodies executed
    /// inline on it. Imported modules pre-executed in parallel run on cloned
    /// state whose counter is dropped, so their depths are not aggregated
    /// here. Used to survey real-world depth against the runaway guard's
    /// limit; see `machine::DEFAULT_MACHINE_CALL_DEPTH_LIMIT`.
    pub(crate) machine_depth_high_water: usize,
    /// Map from source file absolute path to module ID.
    pub path_to_source_id: IndexMap<ModulePath, ModuleId>,
    /// Map from module ID to source file.
    pub id_to_source: IndexMap<ModuleId, ModuleSource>,
    /// Map from module ID to module info.
    pub module_infos: ModuleInfoMap,
    /// Module loader.
    pub mod_loader: ModuleLoader,
    /// Errors and warnings.
    pub issues: Vec<CompilationIssue>,
    /// If set, use this version only when deciding whether to emit
    /// `deprecated_since` warnings. Runtime behavior still uses the version
    /// declared by the KCL program.
    pub deprecation_version_override: Option<String>,
    /// The entry-point (root) module's declared kclVersion, or `None` when it
    /// declares none. When this is KCL 3.0 or later, this single version
    /// governs version-conditional runtime behavior for the whole execution --
    /// every module and every function body. Otherwise (1.0, 2.0, or
    /// undeclared) the legacy per-module lookup and its caller-version quirk
    /// apply, see [`ExecState::legacy_caller_kcl_version`], and no imported
    /// file may declare KCL 3.0 or later, see
    /// [`ExecState::check_imported_module_kcl_version`]. Assigned
    /// unconditionally at the start of every execution.
    pub entry_point_kcl_version: Option<KclVersion>,
    /// Global artifacts that represent the entire program.
    pub artifacts: ArtifactState,
    /// Artifacts for only the root module.
    pub root_module_artifacts: ModuleArtifactState,
    /// The segments that were edited that triggered this execution.
    pub segment_ids_edited: AhashIndexSet<ObjectId>,
    /// Segment-body drag anchors that temporarily pull a point on a segment toward the cursor.
    pub drag_anchors: Vec<SegmentDragAnchor>,
    /// True if this execution is sketch mode execution, executing a single
    /// sketch block. Unlike [`ModuleState::sketch_mode`], this is constant for
    /// the entire execution, including while executing the body of the sketch
    /// block being edited.
    pub sketch_mode: bool,
    /// True when the engine being used for execution is CPU only with no graphical environment
    pub geometry_only: bool,
}

impl GlobalState {
    pub(crate) fn operations_by_module(&self) -> OperationsByModule {
        let mut operations = OperationsByModule::default();
        operations.insert(ModuleId::default(), self.root_module_artifacts.operations.clone());

        for (module_id, module_info) in &self.module_infos {
            match &module_info.repr {
                ModuleRepr::Root => {}
                ModuleRepr::Kcl(_, Some(outcome)) => {
                    operations.insert(*module_id, outcome.artifacts.operations.clone());
                }
                ModuleRepr::Foreign(_, Some((_, artifacts))) => {
                    operations.insert(*module_id, artifacts.operations.clone());
                }
                ModuleRepr::Kcl(_, None) | ModuleRepr::Foreign(_, None) | ModuleRepr::Dummy => {}
            }
        }

        operations
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum ConstraintKey {
    LineCircle([usize; 10]),
    CircleCircle([usize; 12]),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TangencyMode {
    LineCircle(ezpz::LineSide),
    CircleCircle(ezpz::CircleSide),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ConstraintState {
    Tangency(TangencyMode),
}

#[derive(Debug, Clone, Default)]
pub(super) struct ArtifactState {
    /// Internal map of UUIDs to exec artifacts.  This needs to persist across
    /// executions to allow the graph building to refer to cached artifacts.
    pub artifacts: IndexMap<ArtifactId, Artifact>,
    /// Output artifact graph.
    pub graph: ArtifactGraph,
}

/// Which stdlib edge function produced this refactor metadata (for lint/code mod).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub enum EdgeRefactorStdlibFn {
    GetOppositeEdge,
    GetNextAdjacentEdge,
    GetPreviousAdjacentEdge,
    GetCommonEdge,
    EdgeId,
}

/// Metadata collected when a deprecated edge stdlib function runs, for refactor-to-edgeRefs lint/code mod.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub struct EdgeRefactorMeta {
    pub edge_id: Uuid,
    pub face_ids: [Uuid; 2],
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub end_face_ids: Vec<Uuid>,
    pub source_range: SourceRange,
    pub stdlib_fn: EdgeRefactorStdlibFn,
}

/// Metadata for a deprecated edge stdlib function whose edge ID was resolved,
/// but whose adjacent face IDs could not be recorded at the helper callsite.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PendingEdgeRefactorMeta {
    pub edge_id: Uuid,
    pub source_range: SourceRange,
    pub stdlib_fn: EdgeRefactorStdlibFn,
}

/// One tag entry in a fillet/chamfer call that used `tags` directly (for refactor to edgeRefs).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub struct DirectTagFilletTagEntry {
    pub tag_identifier: String,
    pub edge_id: Uuid,
    pub face_ids: [Uuid; 2],
}

/// Metadata for one fillet/chamfer call that used `tags` directly (no stdlib call).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub struct DirectTagFilletMeta {
    pub call_source_range: SourceRange,
    pub tags: Vec<DirectTagFilletTagEntry>,
}

/// Information needed to rewrite one legacy `angle` call while preserving its
/// currently solved directed-angle branch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub struct LegacyAngleRefactorMeta {
    pub source_range: SourceRange,
    pub sector: u8,
    pub inverse: bool,
}

/// Unified metadata stream for Z0006 and future execution-backed refactors.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
#[ts(export)]
#[serde(tag = "kind", content = "data", rename_all = "camelCase")]
pub enum RefactorMetadata {
    EdgeRefactor(Box<EdgeRefactorMeta>),
    DirectTagFillet(DirectTagFilletMeta),
    LegacyAngle(LegacyAngleRefactorMeta),
}

#[derive(Debug, Clone)]
pub(crate) struct PendingLegacyAngleRefactorMeta {
    pub source_range: SourceRange,
    pub lines: [ConstrainableLine2d; 2],
    pub desired_angle_radians: f64,
}

/// Artifact state for a single module.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
pub struct ModuleArtifactState {
    /// Internal map of UUIDs to exec artifacts.
    pub artifacts: IndexMap<ArtifactId, Artifact>,
    /// Outgoing engine commands that have not yet been processed and integrated
    /// into the artifact graph.
    #[serde(skip)]
    pub unprocessed_commands: Vec<ArtifactCommand>,
    /// Outgoing engine commands.
    pub commands: Vec<ArtifactCommand>,
    /// Incoming engine commands.
    #[cfg(feature = "snapshot-engine-responses")]
    pub responses: IndexMap<Uuid, kittycad_modeling_cmds::websocket::WebSocketResponse>,
    /// Operations that have been performed in execution order, for display in
    /// the Feature Tree.
    pub operations: Vec<Operation>,
    /// [`ObjectId`] generator.
    pub object_id_generator: IncIdGenerator<usize>,
    /// Objects in the scene, created from execution.
    pub scene_objects: Vec<Object>,
    /// Map from source range to object ID for lookup of objects by their source
    /// range.
    pub source_range_to_object: BTreeMap<SourceRange, ObjectId>,
    /// Map from artifact ID to object ID in the scene.
    pub artifact_id_to_scene_object: IndexMap<ArtifactId, ObjectId>,
    /// Solutions for sketch variables.
    pub var_solutions: Vec<(SourceRange, Option<NodePath>, Number)>,
    /// Metadata collected during execution for refactor lint/code-mod paths (Z0006 and future).
    pub refactor_metadata: Vec<RefactorMetadata>,
    /// Deprecated edge helper callsites that may be completed by a downstream
    /// operation that knows the target solid.
    #[serde(skip)]
    pub(crate) pending_edge_refactor_metadata: Vec<PendingEdgeRefactorMeta>,
}

#[derive(Debug, Clone)]
pub(super) struct ModuleState {
    /// The id of this module.
    pub module_id: ModuleId,
    /// The id generator for this module.
    pub id_generator: IdGenerator,
    pub stack: Stack,
    /// The size of the call stack. This is used to prevent stack overflows with
    /// recursive function calls. In general, this doesn't match `stack`'s size
    /// since it's conservative in reclaiming frames between executions.
    pub(super) call_stack_size: usize,
    /// Live call depth of the machine executor within this module, for its
    /// runaway-recursion guard. The machine's analog of `call_stack_size`.
    pub(crate) machine_call_depth: usize,
    /// The current value of the pipe operator returned from the previous
    /// expression.  If we're not currently in a pipeline, this will be None.
    pub pipe_value: Option<KclValue>,
    /// The closest variable declaration being executed in any parent node in the AST.
    /// This is used to provide better error messages, e.g. noticing when the user is trying
    /// to use the variable `length` inside the RHS of its own definition, like `length = tan(length)`.
    pub being_declared: Option<String>,
    /// Present if we're currently executing inside a sketch block.
    pub sketch_block: Option<SketchBlockState>,
    /// Tracks if KCL being executed is currently inside a stdlib function or not.
    /// This matters because e.g. we shouldn't emit artifacts from declarations declared inside a stdlib function.
    pub inside_stdlib: bool,
    /// The source range where we entered the standard library.
    pub stdlib_entry_source_range: Option<SourceRange>,
    /// Identifiers that have been exported from the current module.
    pub module_exports: Vec<String>,
    /// Settings specified from annotations.
    pub settings: MetaSettings,
    /// True if executing in sketch mode. Only a single sketch block will be
    /// executed. All other code is ignored.
    pub sketch_mode: bool,
    /// True to do more costly analysis of whether the sketch block segments are
    /// under-constrained. The only time we disable this is when a user is
    /// dragging segments.
    pub freedom_analysis: bool,
    pub(super) explicit_length_units: bool,
    pub(super) path: ModulePath,
    /// Artifacts for only this module.
    pub artifacts: ModuleArtifactState,
    /// Sticky per-constraint state persisted across sketch-mode mock solves.
    /// Maps from sketch block ID to a map for that sketch.
    /// Then the inner map is per constraint (in that sketch block) to its state.
    pub constraint_state: IndexMap<ObjectId, IndexMap<ConstraintKey, ConstraintState>>,

    pub(super) allowed_warnings: Vec<&'static str>,
    pub(super) denied_warnings: Vec<&'static str>,

    /// Map from consumed solid values to information about the operation that
    /// consumed them. Populated by operations that destroy their inputs so that
    /// subsequent attempts to use a consumed solid produce a clear KCL-level
    /// error rather than a cryptic engine error.
    pub(super) consumed_solids: AHashMap<ConsumedSolidKey, ConsumedSolidInfo>,
    /// Defensive map from consumed engine UUID to consumption info.
    /// Rust code may create a `Solid` with a consumed `engine_id` and a
    /// different `instance_id` that was not recorded in `consumed_solids`. When
    /// the exact key lookup misses, this map lets us reject that solid by
    /// `engine_id`, unless the key is a recorded operation output.
    pub(super) consumed_solid_ids: AHashMap<Uuid, ConsumedSolidInfo>,
    /// Region engine UUIDs consumed by successful modeling operations. Regions
    /// use the KCL `Sketch` representation, so this state keeps stale Region
    /// values from reaching an engine object that has become something else.
    pub(super) consumed_regions: AHashMap<Uuid, ConsumedRegionInfo>,
}

/// Information about the operation that consumed a Region.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ConsumedRegionInfo {
    operation: ConsumedRegionOperation,
}

impl ConsumedRegionInfo {
    pub(crate) fn new(operation: ConsumedRegionOperation) -> Self {
        Self { operation }
    }

    pub(crate) fn operation(self) -> ConsumedRegionOperation {
        self.operation
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ConsumedRegionOperation {
    Extrude,
    Revolve,
    Sweep,
    Delete,
}

impl std::fmt::Display for ConsumedRegionOperation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Extrude => f.write_str("extrude"),
            Self::Revolve => f.write_str("revolve"),
            Self::Sweep => f.write_str("sweep"),
            Self::Delete => f.write_str("delete"),
        }
    }
}

/// Internal identity for one runtime KCL solid value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct ConsumedSolidKey {
    /// The engine body UUID.
    engine_id: Uuid,
    /// Distinguishes this KCL runtime instance from other values that may reuse
    /// the same engine body UUID.
    instance_id: Uuid,
}

impl ConsumedSolidKey {
    pub(crate) fn new(engine_id: Uuid, instance_id: Uuid) -> Self {
        Self { engine_id, instance_id }
    }

    pub(crate) fn engine_id(&self) -> Uuid {
        self.engine_id
    }

    pub(crate) fn instance_id(&self) -> Uuid {
        self.instance_id
    }
}

/// Information about a solid value that was consumed by an operation.
/// Stored in `ModuleState.consumed_solids` so subsequent attempts to use the
/// solid produce a clear error pointing at the operation that consumed it.
#[derive(Debug, Clone)]
pub(crate) struct ConsumedSolidInfo {
    /// The operation that consumed the solid.
    operation: ConsumedSolidOperation,
    /// First returned solid value, used only for replacement suggestions in
    /// error messages. When present, this key is also included in
    /// `returned_solid_keys`.
    suggested_replacement_key: Option<ConsumedSolidKey>,
    /// All solid values returned by that operation. This is used as the
    /// allow-list for returned solids that reuse a consumed engine UUID.
    returned_solid_keys: Vec<ConsumedSolidKey>,
}

impl ConsumedSolidInfo {
    pub(crate) fn new(operation: ConsumedSolidOperation, returned_solid_keys: Vec<ConsumedSolidKey>) -> Self {
        Self {
            operation,
            suggested_replacement_key: returned_solid_keys.first().copied(),
            returned_solid_keys,
        }
    }

    pub(crate) fn operation(&self) -> ConsumedSolidOperation {
        self.operation
    }

    pub(crate) fn suggested_replacement_key(&self) -> Option<ConsumedSolidKey> {
        self.suggested_replacement_key
    }

    pub(crate) fn should_report_reused_engine_id_as_consumed(&self, key: ConsumedSolidKey) -> bool {
        !self.returned_solid_keys.contains(&key)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ConsumedSolidOperation {
    Union,
    Intersect,
    Subtract,
    Split,
    JoinSurfaces,
}

impl ConsumedSolidOperation {
    pub(crate) fn indefinite_article(self) -> &'static str {
        match self {
            Self::Intersect => "an",
            Self::Union | Self::Subtract | Self::Split | Self::JoinSurfaces => "a",
        }
    }
}

impl std::fmt::Display for ConsumedSolidOperation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Union => f.write_str("union"),
            Self::Intersect => f.write_str("intersect"),
            Self::Subtract => f.write_str("subtract"),
            Self::Split => f.write_str("split"),
            Self::JoinSurfaces => f.write_str("joinSurfaces"),
        }
    }
}

#[derive(Debug, Clone, Default)]
pub(crate) struct SketchBlockState {
    pub sketch_vars: Vec<KclValue>,
    pub sketch_id: Option<ObjectId>,
    pub sketch_constraints: Vec<ObjectId>,
    pub solver_constraints: Vec<ezpz::Constraint>,
    pub solver_optional_constraints: Vec<ezpz::Constraint>,
    pub needed_by_engine: Vec<UnsolvedSegment>,
    pub segment_tags: IndexMap<ObjectId, TagNode>,
    pub pending_legacy_angle_refactor_metadata: Vec<PendingLegacyAngleRefactorMeta>,
}

impl ExecState {
    pub fn new(exec_context: &super::ExecutorContext) -> Self {
        ExecState {
            execution_callbacks: exec_context.execution_callbacks.clone(),
            global: GlobalState::new(&exec_context.settings, Default::default()),
            mod_local: ModuleState::new(ModulePath::Main, ProgramMemory::new(), Default::default(), false, true),
        }
    }

    #[cfg(test)]
    pub(crate) fn new_with_memory_backend(exec_context: &super::ExecutorContext, backend: MemoryBackendKind) -> Self {
        ExecState {
            execution_callbacks: exec_context.execution_callbacks.clone(),
            global: GlobalState::new(&exec_context.settings, Default::default()),
            mod_local: ModuleState::new(
                ModulePath::Main,
                ProgramMemory::new_with_backend(backend),
                Default::default(),
                false,
                true,
            ),
        }
    }

    pub fn new_mock(exec_context: &super::ExecutorContext, mock_config: &MockConfig) -> Self {
        let segment_ids_edited = mock_config.segment_ids_edited.clone();
        let mut global = GlobalState::new(&exec_context.settings, segment_ids_edited);
        global.drag_anchors = mock_config.drag_anchors.clone();
        global.sketch_mode = mock_config.sketch_block_id.is_some();
        ExecState {
            execution_callbacks: exec_context.execution_callbacks.clone(),
            global,
            mod_local: ModuleState::new(
                ModulePath::Main,
                ProgramMemory::new(),
                Default::default(),
                mock_config.sketch_block_id.is_some(),
                mock_config.freedom_analysis,
            ),
        }
    }

    #[cfg(test)]
    pub(crate) fn new_mock_with_memory_backend(
        exec_context: &super::ExecutorContext,
        mock_config: &MockConfig,
        backend: MemoryBackendKind,
    ) -> Self {
        let segment_ids_edited = mock_config.segment_ids_edited.clone();
        let mut global = GlobalState::new(&exec_context.settings, segment_ids_edited);
        global.drag_anchors = mock_config.drag_anchors.clone();
        global.sketch_mode = mock_config.sketch_block_id.is_some();
        ExecState {
            execution_callbacks: exec_context.execution_callbacks.clone(),
            global,
            mod_local: ModuleState::new(
                ModulePath::Main,
                ProgramMemory::new_with_backend(backend),
                Default::default(),
                mock_config.sketch_block_id.is_some(),
                mock_config.freedom_analysis,
            ),
        }
    }

    pub(super) fn reset(&mut self, exec_context: &super::ExecutorContext) {
        let global = GlobalState::new(&exec_context.settings, Default::default());

        *self = ExecState {
            execution_callbacks: exec_context.execution_callbacks.clone(),
            global,
            mod_local: ModuleState::new(
                self.mod_local.path.clone(),
                ProgramMemory::new(),
                Default::default(),
                false,
                true,
            ),
        };
    }

    /// Log a non-fatal error.
    pub fn err(&mut self, e: CompilationIssue) {
        self.global.issues.push(e);
    }

    /// Log a warning.
    pub fn warn(&mut self, mut e: CompilationIssue, name: &'static str) {
        debug_assert!(annotations::WARN_VALUES.contains(&name));

        if self.mod_local.allowed_warnings.contains(&name) {
            return;
        }

        if self.mod_local.denied_warnings.contains(&name) {
            e.severity = Severity::Error;
        } else {
            e.severity = Severity::Warning;
        }

        self.global.issues.push(e);
    }

    pub fn warn_experimental(&mut self, feature_name: &str, source_range: SourceRange) {
        let Some(severity) = self.mod_local.settings.experimental_features.severity() else {
            return;
        };
        let error = CompilationIssue {
            source_range,
            message: format!("Use of {feature_name} is experimental and may change or be removed."),
            suggestion: None,
            severity,
            tag: crate::errors::Tag::None,
        };

        self.global.issues.push(error);
    }

    pub fn clear_units_warnings(&mut self, source_range: &SourceRange) {
        self.global.issues = std::mem::take(&mut self.global.issues)
            .into_iter()
            .filter(|e| {
                e.severity != Severity::Warning
                    || !source_range.contains_range(&e.source_range)
                    || e.tag != crate::errors::Tag::UnknownNumericUnits
            })
            .collect();
    }

    pub fn issues(&self) -> &[CompilationIssue] {
        &self.global.issues
    }

    pub(crate) fn deprecation_version(&self) -> &str {
        self.global
            .deprecation_version_override
            .as_deref()
            .unwrap_or(self.mod_local.settings.kcl_version.as_str())
    }

    #[cfg(test)]
    pub(crate) fn set_deprecation_version_override(&mut self, version: Option<&str>) {
        self.global.deprecation_version_override = version.map(str::to_owned);
    }

    #[cfg(test)]
    pub(crate) fn program_memory_for_tests(
        &self,
        main_ref: EnvironmentRef,
    ) -> Result<IndexMap<String, KclValue>, KclError> {
        self.mod_local.variables(main_ref)
    }

    /// Convert to execution outcome when running in WebAssembly.  We want to
    /// reduce the amount of data that crosses the WASM boundary as much as
    /// possible.
    pub async fn into_exec_outcome(
        self,
        main_ref: EnvironmentRef,
        ctx: &ExecutorContext,
    ) -> Result<ExecOutcome, KclError> {
        // Fields are opt-in so that we don't accidentally leak private internal
        // state when we add more to ExecState.
        let variables = self.mod_local.variables(main_ref)?;
        #[cfg(test)]
        let test_program_memory = variables.clone();
        let variables = variables
            .into_iter()
            .map(|(key, value)| (key, KclValueView::from(value)))
            .collect();
        Ok(ExecOutcome {
            variables,
            filenames: self.global.filenames(),
            operations: self.global.operations_by_module(),
            artifact_graph: self.global.artifacts.graph,
            scene_objects: self.global.root_module_artifacts.scene_objects,
            source_range_to_object: self.global.root_module_artifacts.source_range_to_object,
            var_solutions: self.global.root_module_artifacts.var_solutions,
            refactor_metadata: self.global.root_module_artifacts.refactor_metadata.clone(),
            issues: self.global.issues,
            source_files: self.global.id_to_source,
            default_planes: ctx.engine.get_default_planes().read().await.clone(),
            #[cfg(test)]
            test_program_memory,
        })
    }

    #[cfg(feature = "snapshot-engine-responses")]
    pub(crate) fn take_root_module_responses(
        &mut self,
    ) -> IndexMap<Uuid, kittycad_modeling_cmds::websocket::WebSocketResponse> {
        std::mem::take(&mut self.global.root_module_artifacts.responses)
    }

    pub(crate) fn geometry_only(&self) -> bool {
        self.global.geometry_only
    }

    pub(crate) fn stack(&self) -> &Stack {
        &self.mod_local.stack
    }

    pub(crate) fn mut_stack(&mut self) -> &mut Stack {
        &mut self.mod_local.stack
    }

    /// Increment the user-level call stack size, returning an error if it
    /// exceeds the maximum.
    pub(super) fn inc_call_stack_size(&mut self, range: SourceRange) -> Result<(), KclError> {
        // If you change this, make sure to test in WebAssembly in the app since
        // that's the limiting factor.
        const LIMIT: usize = 50;
        if self.mod_local.call_stack_size >= LIMIT {
            return Err(KclError::new_max_call_stack(KclErrorDetails::new(
                format!(
                    "Call depth limit ({LIMIT}) exceeded. This usually means a function is recursing without a base case."
                ),
                vec![range],
            )));
        }
        self.mod_local.call_stack_size += 1;
        Ok(())
    }

    /// Decrement the user-level call stack size, returning an error if it would
    /// go below zero.
    pub(super) fn dec_call_stack_size(&mut self, range: SourceRange) -> Result<(), KclError> {
        // Prevent underflow.
        if self.mod_local.call_stack_size == 0 {
            let message = "call stack size below zero".to_owned();
            debug_assert!(false, "{message}");
            return Err(KclError::new_internal(KclErrorDetails::new(message, vec![range])));
        }
        self.mod_local.call_stack_size -= 1;
        Ok(())
    }

    /// The deepest machine-executor call depth reached in this execution.
    /// The machine maintains the counter in all builds; today only the test
    /// harnesses' depth survey reads it.
    // Unused outside test builds, but kept available so release diagnostics
    // can read the counter the machine already maintains.
    #[allow(dead_code)]
    pub(crate) fn machine_depth_high_water(&self) -> usize {
        self.global.machine_depth_high_water
    }

    /// Returns true if we're executing in sketch mode for the current module.
    /// In sketch mode, we still want to execute the prelude and other stdlib
    /// modules as normal, so it can vary per module within a single overall
    /// execution.
    pub(crate) fn sketch_mode(&self) -> bool {
        self.mod_local.sketch_mode
            && match &self.mod_local.path {
                ModulePath::Main => true,
                ModulePath::Local { .. } => true,
                ModulePath::Std { .. } => false,
            }
    }

    /// Returns true if this execution is sketch mode execution, executing a
    /// single sketch block. Unlike [`Self::sketch_mode`], this doesn't vary
    /// during the execution.
    pub(crate) fn is_sketch_mode_execution(&self) -> bool {
        self.global.sketch_mode
    }

    pub fn next_object_id(&mut self) -> ObjectId {
        ObjectId(self.mod_local.artifacts.object_id_generator.next_id())
    }

    pub fn peek_object_id(&self) -> ObjectId {
        ObjectId(self.mod_local.artifacts.object_id_generator.peek_id())
    }

    pub(crate) fn constraint_state(&self, sketch_block_id: ObjectId, key: &ConstraintKey) -> Option<ConstraintState> {
        let map = self.mod_local.constraint_state.get(&sketch_block_id)?;
        map.get(key).copied()
    }

    pub(crate) fn set_constraint_state(
        &mut self,
        sketch_block_id: ObjectId,
        key: ConstraintKey,
        state: ConstraintState,
    ) {
        let map = self.mod_local.constraint_state.entry(sketch_block_id).or_default();
        map.insert(key, state);
    }

    pub fn add_scene_object(&mut self, obj: Object, source_range: SourceRange) -> ObjectId {
        let id = obj.id;
        debug_assert!(
            id.0 == self.mod_local.artifacts.scene_objects.len(),
            "Adding scene object with ID {} but next ID is {}",
            id.0,
            self.mod_local.artifacts.scene_objects.len()
        );
        let artifact_id = obj.artifact_id;
        self.mod_local.artifacts.scene_objects.push(obj);
        self.mod_local.artifacts.source_range_to_object.insert(source_range, id);
        self.mod_local
            .artifacts
            .artifact_id_to_scene_object
            .insert(artifact_id, id);
        id
    }

    /// Add a placeholder scene object. This is useful when we need to reserve
    /// an ID before we have all the information to create the full object.
    pub fn add_placeholder_scene_object(
        &mut self,
        id: ObjectId,
        source_range: SourceRange,
        node_path: Option<NodePath>,
    ) -> ObjectId {
        debug_assert!(id.0 == self.mod_local.artifacts.scene_objects.len());
        self.mod_local
            .artifacts
            .scene_objects
            .push(Object::placeholder(id, source_range, node_path));
        self.mod_local.artifacts.source_range_to_object.insert(source_range, id);
        id
    }

    /// Update a scene object. This is useful to replace a placeholder.
    pub fn set_scene_object(&mut self, object: Object) {
        let id = object.id;
        let artifact_id = object.artifact_id;
        self.mod_local.artifacts.scene_objects[id.0] = object;
        self.mod_local
            .artifacts
            .artifact_id_to_scene_object
            .insert(artifact_id, id);
    }

    pub fn scene_object_id_by_artifact_id(&self, artifact_id: ArtifactId) -> Option<ObjectId> {
        self.mod_local
            .artifacts
            .artifact_id_to_scene_object
            .get(&artifact_id)
            .cloned()
    }

    pub fn segment_ids_edited_contains(&self, object_id: &ObjectId) -> bool {
        self.global.segment_ids_edited.contains(object_id)
    }

    pub fn drag_anchor_target(&self, object_id: &ObjectId) -> Option<&crate::front::Point2d<crate::front::Number>> {
        self.global
            .drag_anchors
            .iter()
            .find(|anchor| &anchor.segment_id == object_id)
            .map(|anchor| &anchor.target)
    }

    pub(super) fn is_in_sketch_block(&self) -> bool {
        self.mod_local.sketch_block.is_some()
    }

    pub(crate) fn sketch_block_mut(&mut self) -> Option<&mut SketchBlockState> {
        self.mod_local.sketch_block.as_mut()
    }

    pub(crate) fn sketch_block(&mut self) -> Option<&SketchBlockState> {
        self.mod_local.sketch_block.as_ref()
    }

    pub fn next_uuid(&mut self) -> Uuid {
        self.mod_local.id_generator.next_uuid()
    }

    pub fn next_artifact_id(&mut self) -> ArtifactId {
        self.mod_local.id_generator.next_artifact_id()
    }

    pub fn id_generator(&mut self) -> &mut IdGenerator {
        &mut self.mod_local.id_generator
    }

    /// Record that a solid value has been consumed by a CSG boolean operation.
    pub(crate) fn mark_solid_consumed(&mut self, consumed_key: ConsumedSolidKey, info: ConsumedSolidInfo) {
        self.mod_local.consumed_solids.insert(consumed_key, info);
    }

    /// Record that an engine body UUID has been consumed by a CSG boolean
    /// operation.
    pub(crate) fn mark_solid_id_consumed(&mut self, consumed_id: Uuid, info: ConsumedSolidInfo) {
        self.mod_local.consumed_solid_ids.insert(consumed_id, info);
    }

    /// Look up whether a solid value was consumed by a previous CSG boolean
    /// operation.
    pub(crate) fn check_solid_consumed(&self, key: &ConsumedSolidKey) -> Option<&ConsumedSolidInfo> {
        self.mod_local.consumed_solids.get(key)
    }

    /// Look up whether an engine body UUID was consumed by a previous CSG
    /// boolean operation.
    pub(crate) fn check_solid_id_consumed(&self, id: &Uuid) -> Option<&ConsumedSolidInfo> {
        self.mod_local.consumed_solid_ids.get(id)
    }

    pub(crate) fn mark_region_consumed(&mut self, id: Uuid, info: ConsumedRegionInfo) {
        self.mod_local.consumed_regions.insert(id, info);
    }

    pub(crate) fn check_region_consumed(&self, id: &Uuid) -> Option<ConsumedRegionInfo> {
        self.mod_local.consumed_regions.get(id).copied()
    }

    /// Find the current variable containing a Region engine UUID. This runs
    /// only while constructing a diagnostic, so recursively searching arrays
    /// and objects is preferable to storing variable names in liveness state.
    pub(crate) fn find_var_name_for_region_id(&self, target_id: Uuid) -> Result<Option<String>, KclError> {
        fn contains_region_id(value: &KclValue, target_id: Uuid) -> bool {
            match value {
                KclValue::Sketch { value } => value.origin_sketch_id.is_some() && value.id == target_id,
                KclValue::HomArray { value, .. } | KclValue::Tuple { value, .. } => {
                    value.iter().any(|value| contains_region_id(value, target_id))
                }
                KclValue::Object { value, .. } => value.values().any(|value| contains_region_id(value, target_id)),
                _ => false,
            }
        }

        self.mod_local
            .stack
            .find_var_name_in_all_envs(|value| contains_region_id(value, target_id))
    }

    /// Follow direct replacement links until we find the latest known output.
    /// Used only on error paths so diagnostics can suggest the current solid.
    pub(crate) fn latest_consumed_output(
        &self,
        suggested_replacement_key: Option<ConsumedSolidKey>,
    ) -> Option<ConsumedSolidKey> {
        let mut latest = suggested_replacement_key?;
        let mut seen = AhashIndexSet::default();

        while seen.insert(latest) {
            let Some(next) = self
                .mod_local
                .consumed_solids
                .get(&latest)
                .and_then(|info| info.suggested_replacement_key())
            else {
                break;
            };
            latest = next;
        }

        Some(latest)
    }

    /// Search the live environment for the name of a variable holding a Solid
    /// (or an array of Solids) whose value identity matches `target_key`. Used only on
    /// error paths to recover variable names for diagnostics.
    pub(crate) fn find_var_name_for_solid_key(&self, target_key: ConsumedSolidKey) -> Result<Option<String>, KclError> {
        fn contains_solid_key(value: &KclValue, target_key: ConsumedSolidKey) -> bool {
            match value {
                KclValue::Solid { value } => {
                    value.id == target_key.engine_id() && value.value_id == target_key.instance_id()
                }
                KclValue::HomArray { value, .. } => value.iter().any(|v| contains_solid_key(v, target_key)),
                _ => false,
            }
        }
        self.mod_local
            .stack
            .find_var_name_in_all_envs(|value| contains_solid_key(value, target_key))
    }

    pub(crate) fn add_artifact(&mut self, artifact: Artifact) {
        let id = artifact.id();
        self.mod_local.artifacts.artifacts.insert(id, artifact);
    }

    /// The declaring module and display name of every named view registered so
    /// far. `view::named` needs these to reject a name that a view declared by
    /// the same module already uses.
    ///
    /// Both artifact maps are scanned, because incremental re-execution divides
    /// the views between them:
    /// - a run that clears the scene empties `global.artifacts` beforehand, so
    ///   every view it can see is one the current run registered into
    ///   `mod_local.artifacts`;
    /// - a run that only appends statements to an unchanged prefix does not
    ///   re-execute that prefix, so the views the prefix declared stay in
    ///   `global.artifacts` from the previous run while the appended
    ///   declarations register into `mod_local.artifacts`.
    ///
    /// Reading one map alone would accept a duplicate name on one of those
    /// paths and reject it on the other, which an author would see as the same
    /// file being accepted while typed and rejected after an unrelated edit.
    /// Neither path can report a view against its own earlier registration: a
    /// re-executed declaration is only reached after `global.artifacts` was
    /// cleared, and an appended declaration has no earlier registration.
    pub(crate) fn registered_named_views(&self) -> impl Iterator<Item = (ModuleId, &str)> {
        self.mod_local
            .artifacts
            .artifacts
            .values()
            .chain(self.global.artifacts.artifacts.values())
            .filter_map(|artifact| match artifact {
                Artifact::NamedView(view) => Some((view.code_ref.range.module_id(), view.name.as_str())),
                _ => None,
            })
    }

    pub(crate) fn artifact_mut(&mut self, id: ArtifactId) -> Option<&mut Artifact> {
        self.mod_local.artifacts.artifacts.get_mut(&id)
    }

    pub(crate) fn is_sketch_block_path(&self, path_id: ArtifactId) -> bool {
        self.mod_local
            .artifacts
            .artifacts
            .values()
            .chain(self.global.artifacts.artifacts.values())
            .any(|artifact| {
                matches!(artifact, Artifact::SketchBlock(sketch_block) if sketch_block.path_id == Some(path_id))
            })
    }

    pub(crate) fn push_op(&mut self, op: Operation) {
        let index = self.mod_local.artifacts.operations.len();
        self.mod_local.artifacts.operations.push(op);
        if let Some(operation) = self.mod_local.artifacts.operations.last().cloned()
            && let Some(callbacks) = &self.execution_callbacks
        {
            callbacks.on_operation(OperationCallbackArgs {
                module_id: self.mod_local.module_id,
                operation,
                index,
            });
        }
    }

    pub(crate) fn push_command(&mut self, command: ArtifactCommand) {
        self.mod_local.artifacts.unprocessed_commands.push(command);
    }

    pub(super) fn next_module_id(&self) -> ModuleId {
        ModuleId::from_usize(self.global.path_to_source_id.len())
    }

    pub(super) fn id_for_module(&self, path: &ModulePath) -> Option<ModuleId> {
        self.global.path_to_source_id.get(path).cloned()
    }

    pub(super) fn add_path_to_source_id(&mut self, path: ModulePath, id: ModuleId) {
        debug_assert!(!self.global.path_to_source_id.contains_key(&path));
        self.global.path_to_source_id.insert(path, id);
    }

    pub(crate) fn add_root_module_contents(&mut self, program: &crate::Program) {
        let root_id = ModuleId::default();
        // Get the path for the root module.
        let path = self
            .global
            .path_to_source_id
            .iter()
            .find(|(_, v)| **v == root_id)
            .unwrap()
            .0
            .clone();
        self.add_id_to_source(
            root_id,
            ModuleSource {
                path,
                source: program.original_file_contents.to_string(),
            },
        );
    }

    pub(super) fn add_id_to_source(&mut self, id: ModuleId, source: ModuleSource) {
        self.global.id_to_source.insert(id, source);
    }

    pub(super) fn add_module(&mut self, id: ModuleId, path: ModulePath, repr: ModuleRepr) {
        debug_assert!(self.global.path_to_source_id.contains_key(&path));
        let module_info = ModuleInfo { id, repr, path };
        self.global.module_infos.insert(id, module_info);
    }

    pub fn get_module(&mut self, id: ModuleId) -> Option<&ModuleInfo> {
        self.global.module_infos.get(&id)
    }

    #[cfg(test)]
    pub(crate) fn modules(&self) -> &ModuleInfoMap {
        &self.global.module_infos
    }

    #[cfg(test)]
    pub(crate) fn root_module_artifact_state(&self) -> &ModuleArtifactState {
        &self.global.root_module_artifacts
    }

    /// Record metadata from a deprecated edge stdlib call for the Z0006 refactor.
    pub(crate) fn record_edge_refactor_meta(&mut self, meta: EdgeRefactorMeta) {
        self.mod_local
            .artifacts
            .refactor_metadata
            .push(RefactorMetadata::EdgeRefactor(Box::new(meta)));
    }

    pub(crate) fn record_pending_edge_refactor_meta(&mut self, meta: PendingEdgeRefactorMeta) {
        self.mod_local.artifacts.pending_edge_refactor_metadata.push(meta);
    }

    pub(crate) fn pending_edge_refactor_meta(
        &self,
        edge_id: Uuid,
        argument_source_range: SourceRange,
    ) -> Option<PendingEdgeRefactorMeta> {
        if !crate::runtime_flags::z0006_refactor_metadata_enabled() {
            return None;
        }
        if let Some(pending) = self
            .mod_local
            .artifacts
            .pending_edge_refactor_metadata
            .iter()
            .find(|meta| meta.edge_id == edge_id && argument_source_range.contains_range(&meta.source_range))
        {
            return Some(pending.clone());
        }

        // A helper assigned to a variable is outside the argument's source
        // range. Fall back to the edge ID only when it identifies one helper.
        let mut matches = self
            .mod_local
            .artifacts
            .pending_edge_refactor_metadata
            .iter()
            .filter(|meta| meta.edge_id == edge_id);
        let pending = matches.next()?.clone();
        matches.next().is_none().then_some(pending)
    }

    pub(crate) fn record_edge_refactor_meta_from_pending(
        &mut self,
        edge_id: Uuid,
        source_range: SourceRange,
        face_ids: [Uuid; 2],
    ) -> bool {
        if self.mod_local.artifacts.refactor_metadata.iter().any(|meta| {
            matches!(
                meta,
                RefactorMetadata::EdgeRefactor(meta)
                    if meta.edge_id == edge_id && meta.source_range == source_range
            )
        }) {
            return true;
        }

        let exact_pending_meta = self
            .mod_local
            .artifacts
            .pending_edge_refactor_metadata
            .iter()
            .find(|meta| meta.edge_id == edge_id && meta.source_range == source_range)
            .cloned();

        let edge_pending_meta = || {
            let mut matches = self
                .mod_local
                .artifacts
                .pending_edge_refactor_metadata
                .iter()
                .filter(|meta| meta.edge_id == edge_id);
            let pending_meta = matches.next()?.clone();
            matches.next().is_none().then_some(pending_meta)
        };

        let Some(pending_meta) = exact_pending_meta.or_else(edge_pending_meta) else {
            return false;
        };

        self.record_edge_refactor_meta(EdgeRefactorMeta {
            edge_id,
            face_ids,
            end_face_ids: Vec::new(),
            source_range: pending_meta.source_range,
            stdlib_fn: pending_meta.stdlib_fn,
        });

        true
    }

    /// Record metadata from a fillet/chamfer call that used `tags` directly.
    pub(crate) fn record_direct_tag_fillet_meta(&mut self, meta: DirectTagFilletMeta) {
        self.mod_local
            .artifacts
            .refactor_metadata
            .push(RefactorMetadata::DirectTagFillet(meta));
    }

    /// Refactor metadata collected when deprecated edge stdlib functions run (for tests and lint).
    pub fn edge_refactor_metadata(&self) -> Vec<EdgeRefactorMeta> {
        self.global
            .root_module_artifacts
            .refactor_metadata
            .iter()
            .filter_map(|m| match m {
                RefactorMetadata::EdgeRefactor(meta) => Some(meta.as_ref().clone()),
                RefactorMetadata::DirectTagFillet(_) | RefactorMetadata::LegacyAngle(_) => None,
            })
            .collect()
    }

    /// Direct-tag fillet/chamfer metadata (for Z0006 code mod).
    pub fn direct_tag_fillet_metadata(&self) -> Vec<DirectTagFilletMeta> {
        self.global
            .root_module_artifacts
            .refactor_metadata
            .iter()
            .filter_map(|m| match m {
                RefactorMetadata::EdgeRefactor(_) | RefactorMetadata::LegacyAngle(_) => None,
                RefactorMetadata::DirectTagFillet(meta) => Some(meta.clone()),
            })
            .collect()
    }

    pub fn current_default_units(&self) -> NumericType {
        NumericType::Default {
            len: self.length_unit(),
            angle: self.angle_unit(),
        }
    }

    pub fn length_unit(&self) -> UnitLength {
        self.mod_local.settings.default_length_units
    }

    pub fn angle_unit(&self) -> UnitAngle {
        self.mod_local.settings.default_angle_units
    }

    pub(super) fn circular_import_error(&self, path: &ModulePath, source_range: SourceRange) -> KclError {
        KclError::new_import_cycle(KclErrorDetails::new(
            format!(
                "circular import of modules is not allowed: {} -> {}",
                self.global
                    .mod_loader
                    .import_stack
                    .iter()
                    .map(|p| p.to_string_lossy())
                    .collect::<Vec<_>>()
                    .join(" -> "),
                path,
            ),
            vec![source_range],
        ))
    }

    pub(crate) fn pipe_value(&self) -> Option<&KclValue> {
        self.mod_local.pipe_value.as_ref()
    }

    pub(crate) fn error_with_outputs(
        &self,
        error: KclError,
        main_ref: Option<EnvironmentRef>,
        default_planes: Option<DefaultPlanes>,
    ) -> KclErrorWithOutputs {
        let module_id_to_module_path: IndexMap<ModuleId, ModulePath> = self
            .global
            .path_to_source_id
            .iter()
            .map(|(k, v)| ((*v), k.clone()))
            .collect();

        KclErrorWithOutputs::new(
            error,
            self.issues().to_vec(),
            main_ref
                .and_then(|main_ref| self.mod_local.variables(main_ref).ok())
                .unwrap_or_default(),
            self.global.operations_by_module(),
            Default::default(),
            self.global.artifacts.graph.clone(),
            self.global.root_module_artifacts.scene_objects.clone(),
            self.global.root_module_artifacts.source_range_to_object.clone(),
            self.global.root_module_artifacts.var_solutions.clone(),
            self.global.root_module_artifacts.refactor_metadata.clone(),
            module_id_to_module_path,
            self.global.id_to_source.clone(),
            default_planes,
        )
    }

    pub(crate) fn build_program_lookup(
        &self,
        current: crate::parsing::ast::types::Node<crate::parsing::ast::types::Program>,
    ) -> ProgramLookup {
        ProgramLookup::new(current, self.global.module_infos.clone())
    }

    pub(crate) async fn build_artifact_graph(
        &mut self,
        engine: &Arc<EngineManager>,
        program: NodeRef<'_, crate::parsing::ast::types::Program>,
    ) -> Result<(), KclError> {
        let mut new_commands = Vec::new();
        let mut new_exec_artifacts = IndexMap::new();
        for module in self.global.module_infos.values_mut() {
            match &mut module.repr {
                ModuleRepr::Kcl(_, Some(outcome)) => {
                    new_commands.extend(outcome.artifacts.process_commands());
                    new_exec_artifacts.extend(outcome.artifacts.artifacts.clone());
                }
                ModuleRepr::Foreign(_, Some((_, module_artifacts))) => {
                    new_commands.extend(module_artifacts.process_commands());
                    new_exec_artifacts.extend(module_artifacts.artifacts.clone());
                }
                ModuleRepr::Root | ModuleRepr::Kcl(_, None) | ModuleRepr::Foreign(_, None) | ModuleRepr::Dummy => {}
            }
        }
        // Take from the module artifacts so that we don't try to process them
        // again next time due to execution caching.
        new_commands.extend(self.global.root_module_artifacts.process_commands());
        // Note: These will get re-processed, but since we're just adding them
        // to a map, it's fine.
        new_exec_artifacts.extend(self.global.root_module_artifacts.artifacts.clone());
        let new_responses = engine.take_responses().await;

        // Move the artifacts into ExecState global to simplify cache
        // management.
        for (id, exec_artifact) in new_exec_artifacts {
            // Only insert if it wasn't already present. We don't want to
            // overwrite what was previously there. We haven't filled in node
            // paths yet.
            self.global.artifacts.artifacts.entry(id).or_insert(exec_artifact);
        }

        let initial_graph = self.global.artifacts.graph.clone();

        // Build the artifact graph.
        let programs = self.build_program_lookup(program.clone());
        let graph_result = crate::execution::artifact::build_artifact_graph(
            &new_commands,
            &new_responses,
            program,
            &mut self.global.artifacts.artifacts,
            initial_graph,
            &programs,
            &self.global.module_infos,
        );

        #[cfg(feature = "snapshot-engine-responses")]
        {
            // Store engine responses for debugging.
            self.global.root_module_artifacts.responses.extend(new_responses);
        }

        let artifact_graph = graph_result?;
        self.global.artifacts.graph = artifact_graph;

        Ok(())
    }

    /// The KCL version governing version-conditional runtime behavior.
    ///
    /// If the entry-point module declared kclVersion 3.0-preview (or later),
    /// that single version governs the entire execution -- all modules and
    /// all function bodies. Otherwise, falls back to the legacy per-module
    /// lookup; see [`Self::legacy_caller_kcl_version`].
    pub(crate) fn kcl_version(&self) -> KclVersion {
        match self.global.entry_point_kcl_version {
            Some(version) if version >= KclVersion::V3Preview => version,
            _ => self.legacy_caller_kcl_version(),
        }
    }

    /// The legacy kclVersion lookup: the current module-local settings.
    ///
    /// Quirk (fixed when the entry point declares 3.0-preview or later):
    /// `mod_local` is swapped only around module top-level execution, never
    /// around function calls, so module-level code sees its own module's
    /// declared version, but a function body sees the CALLING module's
    /// version -- a function defined in a 1.0 module but called from a 2.0
    /// module observes 2.0 here.
    pub(crate) fn legacy_caller_kcl_version(&self) -> KclVersion {
        self.mod_local.settings.kcl_version
    }

    /// Gate for behaviors introduced in KCL 3.0. True only when the entry-point
    /// module of this execution declares KCL 3.0 or later. This never looks at
    /// [`Self::legacy_caller_kcl_version()`] so that behavior never varies
    /// within a single execution.
    pub(crate) fn entry_point_version_is_v3_or_higher(&self) -> bool {
        self.global
            .entry_point_kcl_version
            .is_some_and(|v| v >= KclVersion::V3Preview)
    }

    /// Record the entry-point program's declared kclVersion for this
    /// execution, or `None` when it declares no kclVersion. Must be assigned
    /// unconditionally at the start of every execution since the state may be
    /// reused across executions whose programs declare different versions.
    pub(crate) fn set_entry_point_kcl_version(&mut self, program: &crate::Program) {
        self.global.entry_point_kcl_version = declared_kcl_version(&program.ast)
            .ok()
            .flatten()
            .map(|(version, _)| version);
    }

    /// KCL 3.0: the entry point's declared kclVersion decides which kclVersion
    /// an imported file may declare, so that KCL 3.0 semantics never apply to
    /// only part of a program.
    ///
    /// - When the entry point declares 3.0-preview or later, that version
    ///   governs the whole execution (see [`Self::kcl_version`]), and an
    ///   imported file may not declare a different one.
    /// - Otherwise (1.0, 2.0, or undeclared), the legacy per-module lookup
    ///   applies, and an imported file may not declare 3.0-preview or later,
    ///   which the legacy lookup would honor for that file only. Mixing 1.0
    ///   and 2.0 remains allowed, as it always has been.
    ///
    /// A file that declares no kclVersion is always fine: it runs under the
    /// version the lookup gives it, as it always has. Only user files (local
    /// imports) are checked. Standard library modules are exempt: they ship
    /// with the interpreter, always run under the entry point's pinned
    /// version, and the user cannot edit them to resolve a mismatch. Foreign
    /// imports carry no KCL settings.
    ///
    /// `import_range` is the import statement when the check runs at the
    /// import site, which is included in the error.
    pub(crate) fn check_imported_module_kcl_version(
        &self,
        path: &ModulePath,
        program: &Node<Program>,
        import_range: Option<SourceRange>,
    ) -> Result<(), KclError> {
        if !path.is_local() {
            // stdlib is exempt from the restriction, and `Main` is the version
            // we're checking against.
            return Ok(());
        }
        let Some((declared, declared_range)) = declared_kcl_version(program)? else {
            return Ok(());
        };
        let entry_point_version = self.global.entry_point_kcl_version;
        let allowed = if self.entry_point_version_is_v3_or_higher() {
            Some(declared) == entry_point_version
        } else {
            declared < KclVersion::V3Preview
        };
        if allowed {
            return Ok(());
        }

        // The root module's path is the executor's current file, which is
        // empty when execution was started without one.
        let entry_point = match self
            .global
            .module_infos
            .get(&ModuleId::default())
            .map(|info| &info.path)
        {
            Some(root @ ModulePath::Local { .. }) if !root.to_string().is_empty() => {
                format!("The entry point `{root}`")
            }
            _ => "The entry point".to_owned(),
        };
        let (entry_point_declares, fix) = match entry_point_version {
            Some(version) => (
                format!("declares kclVersion {}", version.as_str()),
                "Update the kclVersion setting in one of these files to match the other.",
            ),
            None => (
                "does not declare a kclVersion".to_owned(),
                "Declare the same kclVersion in the entry point, or update the setting in the imported file.",
            ),
        };
        let mut source_ranges = vec![declared_range];
        source_ranges.extend(import_range);
        Err(KclError::new_semantic(KclErrorDetails::new(
            format!(
                "Mixing KCL versions in a single program is not allowed. {entry_point} {entry_point_declares}, but the imported file `{path}` declares kclVersion {}. {fix}",
                declared.as_str(),
            ),
            source_ranges,
        )))
    }
}

/// The kclVersion that a program's `@settings` annotations declare, with the
/// source range of the declaring property, or `None` when the program does not
/// declare one. The last declaration wins, as in
/// [`MetaSettings::update_from_annotation`], so this searches from the end and
/// stops at the first match.
pub(crate) fn declared_kcl_version(program: &Node<Program>) -> Result<Option<(KclVersion, SourceRange)>, KclError> {
    let Some(property) = program
        .inner_attrs
        .iter()
        .rev()
        .filter(|annotation| annotation.name() == Some(annotations::SETTINGS))
        .find_map(|annotation| {
            annotation
                .properties
                .as_deref()
                .unwrap_or_default()
                .iter()
                .rev()
                .find(|property| &*property.inner.key.name == annotations::SETTINGS_VERSION)
        })
    else {
        return Ok(None);
    };
    let value = annotations::expect_kcl_version(&property.inner.value)?;
    let version = value.parse::<KclVersion>().map_err(|err| {
        KclError::new_semantic(KclErrorDetails::new(err.to_string(), vec![property.as_source_range()]))
    })?;
    Ok(Some((version, property.as_source_range())))
}

impl GlobalState {
    fn new(settings: &ExecutorSettings, segment_ids_edited: AhashIndexSet<ObjectId>) -> Self {
        let mut global = GlobalState {
            machine_depth_high_water: 0,
            path_to_source_id: Default::default(),
            module_infos: Default::default(),
            artifacts: Default::default(),
            root_module_artifacts: Default::default(),
            mod_loader: Default::default(),
            issues: Default::default(),
            deprecation_version_override: None,
            entry_point_kcl_version: None,
            id_to_source: Default::default(),
            segment_ids_edited,
            drag_anchors: Vec::new(),
            sketch_mode: false,
            geometry_only: settings.geometry_only,
        };

        let root_id = ModuleId::default();
        let root_path = settings.current_file.clone().unwrap_or_default();
        global.module_infos.insert(
            root_id,
            ModuleInfo {
                id: root_id,
                path: ModulePath::Local {
                    value: root_path.clone(),
                    original_import_path: None,
                },
                repr: ModuleRepr::Root,
            },
        );
        global.path_to_source_id.insert(
            ModulePath::Local {
                value: root_path,
                original_import_path: None,
            },
            root_id,
        );
        global
    }

    pub(super) fn filenames(&self) -> IndexMap<ModuleId, ModulePath> {
        self.path_to_source_id.iter().map(|(k, v)| ((*v), k.clone())).collect()
    }

    pub(super) fn get_source(&self, id: ModuleId) -> Option<&ModuleSource> {
        self.id_to_source.get(&id)
    }
}

impl ArtifactState {
    pub fn cached_body_items(&self) -> usize {
        self.graph.item_count()
    }

    pub(crate) fn clear(&mut self) {
        self.artifacts.clear();
        self.graph.clear();
    }
}

impl ModuleArtifactState {
    pub fn legacy_angle_refactor_metadata(&self) -> Vec<LegacyAngleRefactorMeta> {
        self.refactor_metadata
            .iter()
            .filter_map(|metadata| match metadata {
                RefactorMetadata::LegacyAngle(metadata) => Some(*metadata),
                RefactorMetadata::EdgeRefactor(_) | RefactorMetadata::DirectTagFillet(_) => None,
            })
            .collect()
    }

    pub(crate) fn clear(&mut self) {
        self.artifacts.clear();
        self.unprocessed_commands.clear();
        self.commands.clear();
        self.operations.clear();
        self.refactor_metadata.clear();
    }

    pub(crate) fn restore_scene_objects(&mut self, scene_objects: &[Object]) {
        self.scene_objects = scene_objects.to_vec();
        self.object_id_generator = IncIdGenerator::new(self.scene_objects.len());
        self.source_range_to_object.clear();
        self.artifact_id_to_scene_object.clear();

        for (expected_id, object) in self.scene_objects.iter().enumerate() {
            debug_assert_eq!(
                object.id.0, expected_id,
                "Restored cached scene object ID {} does not match its position {}",
                object.id.0, expected_id
            );

            match &object.kind {
                ObjectKind::Wall(wall) => {
                    self.source_range_to_object.insert(wall.source.solid.range, object.id);
                }
                ObjectKind::Cap(cap) => {
                    self.source_range_to_object.insert(cap.source.solid.range, object.id);
                }
                _ => match &object.source {
                    crate::front::SourceRef::Simple { range, node_path: _ } => {
                        self.source_range_to_object.insert(*range, object.id);
                    }
                    crate::front::SourceRef::BackTrace { ranges } => {
                        // Don't map the entire backtrace, only the most specific
                        // range.
                        if let Some((range, _)) = ranges.first() {
                            self.source_range_to_object.insert(*range, object.id);
                        }
                    }
                },
            }

            // Ignore placeholder artifacts.
            if object.artifact_id != ArtifactId::placeholder() {
                self.artifact_id_to_scene_object.insert(object.artifact_id, object.id);
            }
        }
    }

    /// When self is a cached state, extend it with new state.
    pub(crate) fn extend(&mut self, other: ModuleArtifactState) {
        self.artifacts.extend(other.artifacts);
        self.unprocessed_commands.extend(other.unprocessed_commands);
        self.commands.extend(other.commands);
        self.operations.extend(other.operations);
        if other.scene_objects.len() > self.scene_objects.len() {
            self.scene_objects
                .extend(other.scene_objects[self.scene_objects.len()..].iter().cloned());
        }
        self.source_range_to_object.extend(other.source_range_to_object);
        self.artifact_id_to_scene_object
            .extend(other.artifact_id_to_scene_object);
        self.var_solutions.extend(other.var_solutions);
        self.refactor_metadata.extend(other.refactor_metadata);
    }

    // Move unprocessed artifact commands so that we don't try to process them
    // again next time due to execution caching.  Returns a clone of the
    // commands that were moved.
    pub(crate) fn process_commands(&mut self) -> Vec<ArtifactCommand> {
        let unprocessed = std::mem::take(&mut self.unprocessed_commands);
        let new_module_commands = unprocessed.clone();
        self.commands.extend(unprocessed);
        new_module_commands
    }

    pub(crate) fn scene_object_by_id(&self, id: ObjectId) -> Option<&Object> {
        debug_assert!(
            id.0 < self.scene_objects.len(),
            "Requested object ID {} but only have {} objects",
            id.0,
            self.scene_objects.len()
        );
        self.scene_objects.get(id.0)
    }

    pub(crate) fn scene_object_by_id_mut(&mut self, id: ObjectId) -> Option<&mut Object> {
        debug_assert!(
            id.0 < self.scene_objects.len(),
            "Requested object ID {} but only have {} objects",
            id.0,
            self.scene_objects.len()
        );
        self.scene_objects.get_mut(id.0)
    }
}

impl ModuleState {
    pub(super) fn new(
        path: ModulePath,
        memory: Arc<ProgramMemory>,
        module_id: Option<ModuleId>,
        sketch_mode: bool,
        freedom_analysis: bool,
    ) -> Self {
        let state_module_id = module_id.unwrap_or_default();
        ModuleState {
            module_id: state_module_id,
            id_generator: IdGenerator::new(module_id),
            stack: memory.new_stack(),
            call_stack_size: 0,
            machine_call_depth: 0,
            pipe_value: Default::default(),
            being_declared: Default::default(),
            sketch_block: Default::default(),
            stdlib_entry_source_range: Default::default(),
            module_exports: Default::default(),
            explicit_length_units: false,
            path,
            settings: Default::default(),
            sketch_mode,
            freedom_analysis,
            artifacts: Default::default(),
            constraint_state: Default::default(),
            allowed_warnings: Vec::new(),
            denied_warnings: Vec::new(),
            consumed_solids: AHashMap::default(),
            consumed_solid_ids: AHashMap::default(),
            consumed_regions: AHashMap::default(),
            inside_stdlib: false,
        }
    }

    pub(super) fn variables(&self, main_ref: EnvironmentRef) -> Result<IndexMap<String, KclValue>, KclError> {
        self.stack.find_all_in_env_owned(main_ref)
    }
}

impl SketchBlockState {
    pub(crate) fn next_sketch_var_id(&self) -> SketchVarId {
        SketchVarId(self.sketch_vars.len())
    }

    /// Given a solve outcome, return the solutions for the sketch variables and
    /// enough information to update them in the source.
    pub(crate) fn var_solutions(
        &self,
        solve_outcome: &Solved,
        solution_ty: NumericType,
        sketch_block_range: SourceRange,
    ) -> Result<Vec<(SourceRange, Option<NodePath>, Number)>, KclError> {
        self.sketch_vars
            .iter()
            .map(|v| {
                let Some(sketch_var) = v.as_sketch_var() else {
                    return Err(KclError::new_internal(KclErrorDetails::new(
                        "Expected sketch variable".to_owned(),
                        vec![sketch_block_range],
                    )));
                };
                let var_index = sketch_var.id.0;
                let solved_n = solve_outcome.final_values.get(var_index).ok_or_else(|| {
                    let message = format!("No solution for sketch variable with id {}", var_index);
                    debug_assert!(false, "{}", &message);
                    KclError::new_internal(KclErrorDetails::new(
                        message,
                        sketch_var.meta.iter().map(|m| m.source_range).collect(),
                    ))
                })?;
                let solved_value = Number {
                    value: *solved_n,
                    units: solution_ty.try_into().map_err(|_| {
                        KclError::new_internal(KclErrorDetails::new(
                            "Failed to convert numeric type to units".to_owned(),
                            vec![sketch_block_range],
                        ))
                    })?,
                };
                let Some(source_range) = sketch_var.meta.first().map(|m| m.source_range) else {
                    return Ok(None);
                };
                Ok(Some((source_range, sketch_var.node_path.clone(), solved_value)))
            })
            .filter_map(Result::transpose)
            .collect::<Result<Vec<_>, KclError>>()
    }
}

#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, ts_rs::TS)]
#[ts(export)]
#[serde(rename_all = "camelCase")]
pub struct MetaSettings {
    pub default_length_units: UnitLength,
    pub default_angle_units: UnitAngle,
    pub experimental_features: annotations::WarningLevel,
    pub kcl_version: KclVersion,
}

impl Default for MetaSettings {
    fn default() -> Self {
        MetaSettings {
            default_length_units: UnitLength::Millimeters,
            default_angle_units: UnitAngle::Degrees,
            experimental_features: annotations::WarningLevel::Deny,
            kcl_version: KclVersion::default(),
        }
    }
}

impl MetaSettings {
    pub(crate) fn update_from_annotation(
        &mut self,
        annotation: &crate::parsing::ast::types::Node<Annotation>,
    ) -> Result<(bool, bool), KclError> {
        let properties = annotations::expect_properties(annotations::SETTINGS, annotation)?;

        let mut updated_len = false;
        let mut updated_angle = false;
        for p in properties {
            match &*p.inner.key.name {
                annotations::SETTINGS_UNIT_LENGTH => {
                    let value = annotations::expect_ident(&p.inner.value)?;
                    let value = super::types::length_from_str(value, annotation.as_source_range())?;
                    self.default_length_units = value;
                    updated_len = true;
                }
                annotations::SETTINGS_UNIT_ANGLE => {
                    let value = annotations::expect_ident(&p.inner.value)?;
                    let value = super::types::angle_from_str(value, annotation.as_source_range())?;
                    self.default_angle_units = value;
                    updated_angle = true;
                }
                annotations::SETTINGS_VERSION => {
                    let value = annotations::expect_kcl_version(&p.inner.value)?;
                    self.kcl_version = value.parse()?;
                }
                annotations::SETTINGS_EXPERIMENTAL_FEATURES => {
                    let value = annotations::expect_ident(&p.inner.value)?;
                    let value = annotations::WarningLevel::from_str(value).map_err(|_| {
                        KclError::new_semantic(KclErrorDetails::new(
                            format!(
                                "Invalid value for {} settings property, expected one of: {}",
                                annotations::SETTINGS_EXPERIMENTAL_FEATURES,
                                annotations::WARN_LEVELS.join(", ")
                            ),
                            annotation.as_source_ranges(),
                        ))
                    })?;
                    self.experimental_features = value;
                }
                name => {
                    return Err(KclError::new_semantic(KclErrorDetails::new(
                        format!(
                            "Unexpected settings key: `{name}`; expected one of `{}`, `{}`",
                            annotations::SETTINGS_UNIT_LENGTH,
                            annotations::SETTINGS_UNIT_ANGLE
                        ),
                        vec![annotation.as_source_range()],
                    )));
                }
            }
        }

        Ok((updated_len, updated_angle))
    }
}

#[cfg(test)]
mod tests {

    use uuid::Uuid;

    use super::KclVersion;
    use super::ModuleArtifactState;
    use crate::NodePath;
    use crate::NodePathExt;
    use crate::SourceRange;
    use crate::execution::ArtifactId;
    use crate::front::Object;
    use crate::front::ObjectId;
    use crate::front::ObjectKind;
    use crate::front::Plane;
    use crate::front::SourceRef;

    #[test]
    fn declared_kcl_version_finds_the_setting_and_its_range() {
        let parse = |code: &str| crate::parsing::top_level_parse(code).unwrap();

        assert_eq!(super::declared_kcl_version(&parse("x = 1\n")).unwrap(), None);
        assert_eq!(
            super::declared_kcl_version(&parse("@settings(defaultLengthUnit = in)\nx = 1\n")).unwrap(),
            None
        );

        let code = "@settings(defaultLengthUnit = in, kclVersion = 2.0)\nx = 1\n";
        let (version, range) = super::declared_kcl_version(&parse(code)).unwrap().unwrap();
        assert_eq!(version, KclVersion::V2);
        let start = code.find("kclVersion").unwrap();
        assert_eq!((range.start(), range.end()), (start, start + "kclVersion = 2.0".len()));

        let (version, _) = super::declared_kcl_version(&parse("@settings(kclVersion = \"3.0-preview\")\n"))
            .unwrap()
            .unwrap();
        assert_eq!(version, KclVersion::V3Preview);

        // The last declaration wins, whether it is in a later annotation or
        // later within the same annotation.
        let code = "@settings(kclVersion = 1.0)\n@settings(defaultLengthUnit = in)\n@settings(kclVersion = 2.0, kclVersion = \"3.0-preview\")\n";
        let (version, range) = super::declared_kcl_version(&parse(code)).unwrap().unwrap();
        assert_eq!(version, KclVersion::V3Preview);
        let start = code.rfind("kclVersion").unwrap();
        assert_eq!(
            (range.start(), range.end()),
            (start, start + "kclVersion = \"3.0-preview\"".len())
        );

        // An unknown version is an error located at the setting.
        let code = "@settings(kclVersion = 9.0)\n";
        let error = super::declared_kcl_version(&parse(code)).unwrap_err();
        let start = code.find("kclVersion").unwrap();
        assert_eq!(
            error.source_ranges().first().map(|range| (range.start(), range.end())),
            Some((start, start + "kclVersion = 9.0".len()))
        );
    }

    #[test]
    fn kcl_version_serializes_as_canonical_setting_value() {
        assert_eq!(serde_json::to_string(&KclVersion::V1).unwrap(), r#""1.0""#);
        assert_eq!(serde_json::to_string(&KclVersion::V2).unwrap(), r#""2.0""#);
        assert_eq!(
            serde_json::to_string(&KclVersion::V3Preview).unwrap(),
            r#""3.0-preview""#
        );
    }

    #[test]
    fn restore_scene_objects_rebuilds_lookup_maps() {
        let plane_artifact_id = ArtifactId::new(Uuid::from_u128(1));
        let sketch_artifact_id = ArtifactId::new(Uuid::from_u128(2));
        let plane_range = SourceRange::from([1, 4, 0]);
        let plane_node_path = Some(NodePath::placeholder());
        let sketch_ranges = vec![
            (SourceRange::from([5, 9, 0]), None),
            (SourceRange::from([10, 12, 0]), None),
        ];
        let cached_objects = vec![
            Object {
                id: ObjectId(0),
                kind: ObjectKind::Plane(Plane::Object(ObjectId(0))),
                label: Default::default(),
                comments: Default::default(),
                artifact_id: plane_artifact_id,
                source: SourceRef::new(plane_range, plane_node_path),
            },
            Object {
                id: ObjectId(1),
                kind: ObjectKind::Nil,
                label: Default::default(),
                comments: Default::default(),
                artifact_id: sketch_artifact_id,
                source: SourceRef::BackTrace {
                    ranges: sketch_ranges.clone(),
                },
            },
            Object::placeholder(ObjectId(2), SourceRange::from([13, 14, 0]), None),
        ];

        let mut artifacts = ModuleArtifactState::default();
        artifacts.restore_scene_objects(&cached_objects);

        assert_eq!(artifacts.scene_objects, cached_objects);
        assert_eq!(
            artifacts.artifact_id_to_scene_object.get(&plane_artifact_id),
            Some(&ObjectId(0))
        );
        assert_eq!(
            artifacts.artifact_id_to_scene_object.get(&sketch_artifact_id),
            Some(&ObjectId(1))
        );
        assert_eq!(
            artifacts.artifact_id_to_scene_object.get(&ArtifactId::placeholder()),
            None
        );
        assert_eq!(artifacts.source_range_to_object.get(&plane_range), Some(&ObjectId(0)));
        assert_eq!(
            artifacts.source_range_to_object.get(&sketch_ranges[0].0),
            Some(&ObjectId(1))
        );
        // We don't map all the ranges in a backtrace.
        assert_eq!(artifacts.source_range_to_object.get(&sketch_ranges[1].0), None);
    }
}