neovm-core 0.0.2

Core runtime structures for NeoVM
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
//! Emacs-compatible threading primitives for the Elisp VM.
//!
//! Emacs threading is cooperative: only one thread runs at a time, yielding at
//! certain well-defined points.  Since our VM is single-threaded, threads are
//! *simulated* — `make-thread` stores the function and runs it immediately.
//! The key goal is API compatibility so that Elisp packages using threads,
//! mutexes, and condition variables continue to work without error.
//!
//! Provided primitives:
//! - Threads: `make-thread`, `thread-join`, `thread-yield`, `thread-name`,
//!   `thread-live-p`, `threadp`, `thread-signal`, `current-thread`,
//!   `all-threads`, `thread-last-error`
//! - Mutexes: `make-mutex`, `mutexp`, `mutex-name`, `mutex-lock`, `mutex-unlock`
//! - Condition variables: `make-condition-variable`, `condition-variable-p`,
//!   `condition-wait`, `condition-notify`
//! - Special form: `with-mutex`

use std::collections::HashMap;

use super::error::{
    EvalResult, Flow, make_signal_binding_value, signal, signal_from_binding_value,
    signal_with_data,
};
use super::value::{Value, ValueKind, eq_value};
use crate::gc_trace::GcTrace;
use crate::heap_types::LispString;

// ---------------------------------------------------------------------------
// Thread state
// ---------------------------------------------------------------------------

/// Status of a simulated thread.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ThreadStatus {
    /// Thread has been created but not yet run.
    Created,
    /// Thread is currently running (in our model, at most one can be Running).
    Running,
    /// Thread has finished successfully.
    Finished,
    /// Thread was terminated by an error / signal.
    Signaled,
}

/// Per-thread bookkeeping.
#[derive(Clone, Debug)]
pub struct ThreadState {
    /// Unique thread id.  0 is always the main thread.
    pub id: u64,
    /// Optional human-readable name.
    pub name: Option<LispString>,
    /// The function to invoke (value passed to `make-thread`).
    pub function: Value,
    /// Current status.
    pub status: ThreadStatus,
    /// Return value after the thread finishes (or nil).
    pub result: Value,
    /// Last error that occurred in this thread, if any.
    pub last_error: Option<Value>,
    /// Whether this thread has already been joined at least once.
    pub joined: bool,
    /// What should happen if this thread's current buffer is killed.
    pub buffer_disposition: Value,
    /// Current buffer owned by this thread.
    pub current_buffer: Option<crate::buffer::BufferId>,
    /// Object this thread is currently blocked on.
    pub event_object: Value,
    /// Pending or terminal signal symbol for this thread.
    pub error_symbol: Value,
    /// Pending or terminal signal data for this thread.
    pub error_data: Value,
}

// ---------------------------------------------------------------------------
// Mutex state
// ---------------------------------------------------------------------------

/// A cooperative mutex.  Since the VM is single-threaded, lock/unlock are
/// effectively no-ops, but we still track ownership for diagnostics and to
/// match the Emacs API.
#[derive(Clone, Debug)]
pub struct MutexState {
    pub id: u64,
    pub name: Option<LispString>,
    /// Id of the thread that currently holds the lock, or `None`.
    pub owner: Option<u64>,
    /// Recursive lock count.
    pub lock_count: u32,
}

// ---------------------------------------------------------------------------
// Condition variable state
// ---------------------------------------------------------------------------

/// A condition variable bound to a particular mutex.
#[derive(Clone, Debug)]
pub struct ConditionVarState {
    pub id: u64,
    pub name: Option<LispString>,
    /// The mutex id this condition variable is associated with.
    pub mutex_id: u64,
}

// ---------------------------------------------------------------------------
// ThreadManager
// ---------------------------------------------------------------------------

/// Central registry for threads, mutexes, and condition variables.
pub struct ThreadManager {
    threads: HashMap<u64, ThreadState>,
    next_id: u64,
    current_thread: u64, // ID of currently running thread (0 = main)
    thread_handles: HashMap<u64, Value>,
    mutexes: HashMap<u64, MutexState>,
    next_mutex_id: u64,
    mutex_handles: HashMap<u64, Value>,
    condition_vars: HashMap<u64, ConditionVarState>,
    next_cv_id: u64,
    condition_var_handles: HashMap<u64, Value>,
    /// Global last-error value (returned by `thread-last-error`).
    last_error: Option<Value>,
}

impl ThreadManager {
    /// Create a new manager with the main thread pre-registered.
    pub fn new() -> Self {
        let mut threads = HashMap::new();
        threads.insert(
            0,
            ThreadState {
                id: 0,
                name: None,
                function: Value::NIL,
                status: ThreadStatus::Running,
                result: Value::NIL,
                last_error: None,
                joined: false,
                buffer_disposition: Value::NIL,
                current_buffer: None,
                event_object: Value::NIL,
                error_symbol: Value::NIL,
                error_data: Value::NIL,
            },
        );
        let mut thread_handles = HashMap::new();
        thread_handles.insert(0, tagged_object_value("thread", 0));
        Self {
            threads,
            next_id: 1,
            current_thread: 0,
            thread_handles,
            mutexes: HashMap::new(),
            next_mutex_id: 1,
            mutex_handles: HashMap::new(),
            condition_vars: HashMap::new(),
            next_cv_id: 1,
            condition_var_handles: HashMap::new(),
            last_error: None,
        }
    }

    // -- Thread operations --------------------------------------------------

    /// Create a new thread.  Returns the id.
    pub fn create_thread(&mut self, function: Value, name: Option<LispString>) -> u64 {
        let id = self.next_id;
        self.next_id += 1;
        self.threads.insert(
            id,
            ThreadState {
                id,
                name,
                function,
                status: ThreadStatus::Created,
                result: Value::NIL,
                last_error: None,
                joined: false,
                buffer_disposition: Value::NIL,
                current_buffer: None,
                event_object: Value::NIL,
                error_symbol: Value::NIL,
                error_data: Value::NIL,
            },
        );
        self.thread_handles
            .insert(id, tagged_object_value("thread", id));
        id
    }

    /// Mark a thread as Running.
    pub fn start_thread(&mut self, id: u64) {
        if let Some(t) = self.threads.get_mut(&id) {
            t.status = ThreadStatus::Running;
        }
    }

    /// Set the currently running thread and return the previous thread id.
    pub fn enter_thread(&mut self, id: u64) -> u64 {
        let saved = self.current_thread;
        self.current_thread = id;
        saved
    }

    /// Restore the previously running thread id.
    pub fn restore_thread(&mut self, id: u64) {
        self.current_thread = id;
    }

    /// Mark a thread as Finished with the given result.
    pub fn finish_thread(&mut self, id: u64, result: Value) {
        if let Some(t) = self.threads.get_mut(&id) {
            t.status = ThreadStatus::Finished;
            t.result = result;
        }
    }

    /// Mark a thread as Signaled with an error value.
    pub fn signal_thread(&mut self, id: u64, error: Value) {
        if let Some(t) = self.threads.get_mut(&id) {
            t.status = ThreadStatus::Signaled;
            t.last_error = Some(error);
            if let Some((symbol, data)) = split_signal_binding_value(error) {
                t.error_symbol = symbol;
                t.error_data = data;
            } else {
                t.error_symbol = Value::NIL;
                t.error_data = Value::NIL;
            }
        }
    }

    /// Publish an error value for `thread-last-error`.
    pub fn record_last_error(&mut self, error: Value) {
        self.last_error = Some(error);
    }

    /// Get the id of the currently running thread.
    pub fn current_thread_id(&self) -> u64 {
        self.current_thread
    }

    /// Look up a thread by id.
    pub fn get_thread(&self, id: u64) -> Option<&ThreadState> {
        self.threads.get(&id)
    }

    /// Check if a thread is alive (Created or Running).
    pub fn thread_alive_p(&self, id: u64) -> bool {
        self.threads
            .get(&id)
            .is_some_and(|t| t.status == ThreadStatus::Created || t.status == ThreadStatus::Running)
    }

    /// Get thread name.
    pub fn thread_name(&self, id: u64) -> Option<&LispString> {
        self.threads.get(&id).and_then(|t| t.name.as_ref())
    }

    /// Check if a value represents a known thread id.
    pub fn is_thread(&self, id: u64) -> bool {
        self.threads.contains_key(&id)
    }

    /// Return canonical handle object for thread id.
    pub fn thread_handle(&self, id: u64) -> Option<Value> {
        self.thread_handles.get(&id).cloned()
    }

    /// Return the thread id iff VALUE is the canonical thread handle object.
    pub fn thread_id_from_handle(&self, value: &Value) -> Option<u64> {
        canonical_handle_id(&self.thread_handles, value, "thread")
    }

    /// Return all thread ids.
    pub fn all_thread_ids(&self) -> Vec<u64> {
        self.threads
            .iter()
            .filter_map(|(id, thread)| self.thread_alive_p(*id).then_some(*id))
            .collect()
    }

    /// Return thread result (for join).
    pub fn thread_result(&self, id: u64) -> Value {
        self.threads
            .get(&id)
            .map(|t| t.result)
            .unwrap_or(Value::NIL)
    }

    /// Mark a thread as joined and return its terminal error, if any.
    pub fn join_thread(&mut self, id: u64) -> Option<Value> {
        let thread = self.threads.get_mut(&id)?;
        thread.joined = true;
        thread.last_error
    }

    /// Get and optionally clear the global last-error.
    pub fn last_error(&mut self, cleanup: bool) -> Value {
        let val = self.last_error.unwrap_or(Value::NIL);
        if cleanup {
            self.last_error = None;
        }
        val
    }

    pub fn thread_buffer_disposition(&self, id: u64) -> Option<Value> {
        self.threads
            .get(&id)
            .map(|thread| thread.buffer_disposition)
    }

    pub fn set_thread_buffer_disposition(&mut self, id: u64, value: Value) -> bool {
        let Some(thread) = self.threads.get_mut(&id) else {
            return false;
        };
        thread.buffer_disposition = value;
        true
    }

    pub fn thread_current_buffer(&self, id: u64) -> Option<crate::buffer::BufferId> {
        self.threads
            .get(&id)
            .and_then(|thread| thread.current_buffer)
    }

    pub fn set_thread_current_buffer(
        &mut self,
        id: u64,
        buffer_id: Option<crate::buffer::BufferId>,
    ) -> bool {
        let Some(thread) = self.threads.get_mut(&id) else {
            return false;
        };
        thread.current_buffer = buffer_id;
        true
    }

    pub fn thread_blocker(&self, id: u64) -> Option<Value> {
        self.threads.get(&id).map(|thread| thread.event_object)
    }

    pub fn set_thread_blocker(&mut self, id: u64, blocker: Value) -> bool {
        let Some(thread) = self.threads.get_mut(&id) else {
            return false;
        };
        thread.event_object = blocker;
        true
    }

    pub fn clear_thread_blocker(&mut self, id: u64) -> bool {
        self.set_thread_blocker(id, Value::NIL)
    }

    // -- Mutex operations ---------------------------------------------------

    /// Create a new mutex.  Returns the id.
    pub fn create_mutex(&mut self, name: Option<LispString>) -> u64 {
        let id = self.next_mutex_id;
        self.next_mutex_id += 1;
        self.mutexes.insert(
            id,
            MutexState {
                id,
                name,
                owner: None,
                lock_count: 0,
            },
        );
        self.mutex_handles
            .insert(id, tagged_object_value("mutex", id));
        id
    }

    /// Lock a mutex (on behalf of the current thread).
    /// In single-threaded mode this always succeeds.
    pub fn mutex_lock(&mut self, mutex_id: u64) -> bool {
        let current = self.current_thread;
        if let Some(m) = self.mutexes.get_mut(&mutex_id) {
            match m.owner {
                None => {
                    m.owner = Some(current);
                    m.lock_count = 1;
                    true
                }
                Some(owner) if owner == current => {
                    // Recursive lock.
                    m.lock_count += 1;
                    true
                }
                Some(_) => {
                    // In a real multi-threaded implementation this would block.
                    // In our single-threaded sim it should not happen, but we
                    // handle it gracefully by allowing the lock anyway.
                    m.owner = Some(current);
                    m.lock_count = 1;
                    true
                }
            }
        } else {
            false
        }
    }

    /// Unlock a mutex.  Returns false if the mutex doesn't exist or is
    /// not held by the current thread.
    pub fn mutex_unlock(&mut self, mutex_id: u64) -> bool {
        let current = self.current_thread;
        if let Some(m) = self.mutexes.get_mut(&mutex_id) {
            if m.owner == Some(current) {
                m.lock_count = m.lock_count.saturating_sub(1);
                if m.lock_count == 0 {
                    m.owner = None;
                }
                true
            } else {
                // Not locked by current thread — still succeed for compatibility
                true
            }
        } else {
            false
        }
    }

    /// Check if a value represents a known mutex id.
    pub fn is_mutex(&self, id: u64) -> bool {
        self.mutexes.contains_key(&id)
    }

    /// Return canonical handle object for mutex id.
    pub fn mutex_handle(&self, id: u64) -> Option<Value> {
        self.mutex_handles.get(&id).cloned()
    }

    /// Return the mutex id iff VALUE is the canonical mutex handle object.
    pub fn mutex_id_from_handle(&self, value: &Value) -> Option<u64> {
        canonical_handle_id(&self.mutex_handles, value, "mutex")
    }

    /// Get mutex name.
    pub fn mutex_name(&self, id: u64) -> Option<&LispString> {
        self.mutexes.get(&id).and_then(|m| m.name.as_ref())
    }

    /// Return true when MUTEX-ID is owned by the current thread.
    pub fn mutex_owned_by_current_thread(&self, mutex_id: u64) -> bool {
        self.mutexes
            .get(&mutex_id)
            .is_some_and(|m| m.owner == Some(self.current_thread))
    }

    // -- Condition variable operations --------------------------------------

    /// Create a condition variable associated with the given mutex.
    pub fn create_condition_variable(
        &mut self,
        mutex_id: u64,
        name: Option<LispString>,
    ) -> Option<u64> {
        if !self.mutexes.contains_key(&mutex_id) {
            return None;
        }
        let id = self.next_cv_id;
        self.next_cv_id += 1;
        self.condition_vars
            .insert(id, ConditionVarState { id, name, mutex_id });
        self.condition_var_handles
            .insert(id, tagged_object_value("condition-variable", id));
        Some(id)
    }

    /// Check if a value represents a known condition variable id.
    pub fn is_condition_variable(&self, id: u64) -> bool {
        self.condition_vars.contains_key(&id)
    }

    /// Return canonical handle object for condition variable id.
    pub fn condition_variable_handle(&self, id: u64) -> Option<Value> {
        self.condition_var_handles.get(&id).cloned()
    }

    /// Return the condition variable id iff VALUE is the canonical handle.
    pub fn condition_variable_id_from_handle(&self, value: &Value) -> Option<u64> {
        canonical_handle_id(&self.condition_var_handles, value, "condition-variable")
    }

    /// Get condition variable name.
    pub fn condition_variable_name(&self, id: u64) -> Option<&LispString> {
        self.condition_vars.get(&id).and_then(|cv| cv.name.as_ref())
    }

    /// Get the mutex associated with a condition variable.
    pub fn condition_variable_mutex(&self, cv_id: u64) -> Option<u64> {
        self.condition_vars.get(&cv_id).map(|cv| cv.mutex_id)
    }
}

impl Default for ThreadManager {
    fn default() -> Self {
        Self::new()
    }
}

impl GcTrace for ThreadManager {
    fn trace_roots(&self, roots: &mut Vec<Value>) {
        for thread in self.threads.values() {
            roots.push(thread.function);
            roots.push(thread.result);
            roots.push(thread.buffer_disposition);
            roots.push(thread.event_object);
            roots.push(thread.error_symbol);
            roots.push(thread.error_data);
            if let Some(buffer_id) = thread.current_buffer {
                roots.push(Value::make_buffer(buffer_id));
            }
            if let Some(ref err) = thread.last_error {
                roots.push(*err);
            }
        }
        for value in self.thread_handles.values() {
            roots.push(*value);
        }
        for value in self.mutex_handles.values() {
            roots.push(*value);
        }
        for value in self.condition_var_handles.values() {
            roots.push(*value);
        }
        if let Some(ref err) = self.last_error {
            roots.push(*err);
        }
    }
}

// ===========================================================================
// Argument helpers
// ===========================================================================

fn expect_args(name: &str, args: &[Value], n: usize) -> Result<(), Flow> {
    if args.len() != n {
        Err(signal(
            "wrong-number-of-arguments",
            vec![Value::symbol(name), Value::fixnum(args.len() as i64)],
        ))
    } else {
        Ok(())
    }
}

fn expect_min_args(name: &str, args: &[Value], min: usize) -> Result<(), Flow> {
    if args.len() < min {
        Err(signal(
            "wrong-number-of-arguments",
            vec![Value::symbol(name), Value::fixnum(args.len() as i64)],
        ))
    } else {
        Ok(())
    }
}

fn expect_args_range(name: &str, args: &[Value], min: usize, max: usize) -> Result<(), Flow> {
    if args.len() < min || args.len() > max {
        Err(signal(
            "wrong-number-of-arguments",
            vec![Value::symbol(name), Value::fixnum(args.len() as i64)],
        ))
    } else {
        Ok(())
    }
}

fn tagged_object_value(tag: &str, id: u64) -> Value {
    Value::cons(Value::symbol(tag), Value::fixnum(id as i64))
}

fn tagged_object_id(value: &Value, expected_tag: &str) -> Option<u64> {
    if !value.is_cons() {
        return None;
    };
    let pair_car = value.cons_car();
    let pair_cdr = value.cons_cdr();
    if pair_car.as_symbol_name() != Some(expected_tag) {
        return None;
    }
    match pair_cdr.kind() {
        ValueKind::Fixnum(n) if n >= 0 => Some(n as u64),
        _ => None,
    }
}

fn canonical_handle_id(handles: &HashMap<u64, Value>, value: &Value, tag: &str) -> Option<u64> {
    let id = tagged_object_id(value, tag)?;
    let canonical = handles.get(&id)?;
    if eq_value(canonical, value) {
        Some(id)
    } else {
        None
    }
}

fn split_signal_binding_value(value: Value) -> Option<(Value, Value)> {
    if !value.is_cons() {
        return None;
    };
    let pair_car = value.cons_car();
    let pair_cdr = value.cons_cdr();
    pair_car.as_symbol_name()?;
    Some((pair_car, pair_cdr))
}

/// Extract a thread id from a canonical thread handle object.
fn expect_thread_id(manager: &ThreadManager, value: &Value) -> Result<u64, Flow> {
    match manager.thread_id_from_handle(value) {
        Some(id) => Ok(id),
        None => Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("threadp"), *value],
        )),
    }
}

/// Extract a mutex id from a canonical mutex handle object.
fn expect_mutex_id(manager: &ThreadManager, value: &Value) -> Result<u64, Flow> {
    match manager.mutex_id_from_handle(value) {
        Some(id) => Ok(id),
        None => Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("mutexp"), *value],
        )),
    }
}

/// Extract a condition variable id from a canonical handle object.
fn expect_cv_id(manager: &ThreadManager, value: &Value) -> Result<u64, Flow> {
    match manager.condition_variable_id_from_handle(value) {
        Some(id) => Ok(id),
        None => Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("condition-variable-p"), *value],
        )),
    }
}

// ===========================================================================
// Thread builtins
// ===========================================================================

/// `(make-thread FUNCTION &optional NAME)` -- create a thread.
///
/// In our single-threaded simulation the function is executed immediately.
/// Returns a `(thread . ID)` object.
pub(crate) fn builtin_make_thread(eval: &mut super::eval::Context, args: Vec<Value>) -> EvalResult {
    let (thread_id, function) = prepare_make_thread(&mut eval.threads, &args)?;
    eval.threads
        .set_thread_current_buffer(thread_id, eval.buffers.current_buffer_id());
    let runtime_state = enter_thread_runtime(eval, thread_id)?;
    let result = eval.apply(function, vec![]);
    exit_thread_runtime(eval, thread_id, runtime_state);
    finish_make_thread_result(&mut eval.threads, thread_id, result)
}

pub(crate) fn prepare_make_thread(
    threads: &mut ThreadManager,
    args: &[Value],
) -> Result<(u64, Value), Flow> {
    expect_args_range("make-thread", args, 1, 3)?;

    let function = args[0];
    let name = if args.len() > 1 {
        match args[1].kind() {
            ValueKind::String => Some(args[1].as_lisp_string().expect("string").clone()),
            ValueKind::Nil => None,
            other => {
                return Err(signal(
                    "wrong-type-argument",
                    vec![Value::symbol("stringp"), args[1]],
                ));
            }
        }
    } else {
        None
    };
    let buffer_disposition = args.get(2).copied().unwrap_or(Value::NIL);

    let thread_id = threads.create_thread(function, name);
    threads.set_thread_buffer_disposition(thread_id, buffer_disposition);
    threads.start_thread(thread_id);
    Ok((thread_id, function))
}

pub(crate) fn finish_make_thread_in_eval(
    eval: &mut super::eval::Context,
    thread_id: u64,
    function: Value,
) -> EvalResult {
    eval.threads
        .set_thread_current_buffer(thread_id, eval.buffers.current_buffer_id());
    let runtime_state = enter_thread_runtime(eval, thread_id)?;
    let result = eval.apply(function, vec![]);
    exit_thread_runtime(eval, thread_id, runtime_state);
    finish_make_thread_result(&mut eval.threads, thread_id, result)
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct ThreadRuntimeState {
    previous_thread_id: u64,
    previous_buffer_id: Option<crate::buffer::BufferId>,
}

pub(crate) fn enter_thread_runtime(
    eval: &mut super::eval::Context,
    thread_id: u64,
) -> Result<ThreadRuntimeState, Flow> {
    let previous_thread_id = eval.threads.enter_thread(thread_id);
    let previous_buffer_id = eval
        .threads
        .thread_current_buffer(previous_thread_id)
        .or_else(|| eval.buffers.current_buffer_id());
    if let Some(thread_buffer_id) = eval.threads.thread_current_buffer(thread_id) {
        if eval.buffers.current_buffer_id() != Some(thread_buffer_id) {
            eval.switch_current_buffer(thread_buffer_id)?;
        } else {
            eval.sync_current_thread_buffer_state();
        }
    } else {
        eval.sync_current_thread_buffer_state();
    }
    Ok(ThreadRuntimeState {
        previous_thread_id,
        previous_buffer_id,
    })
}

pub(crate) fn exit_thread_runtime(
    eval: &mut super::eval::Context,
    thread_id: u64,
    runtime_state: ThreadRuntimeState,
) {
    eval.threads
        .set_thread_current_buffer(thread_id, eval.buffers.current_buffer_id());
    eval.threads
        .restore_thread(runtime_state.previous_thread_id);
    if let Some(previous_buffer_id) = runtime_state.previous_buffer_id {
        eval.restore_current_buffer_if_live(previous_buffer_id);
    }
    eval.sync_current_thread_buffer_state();
}

pub(crate) fn finish_make_thread_result(
    threads: &mut ThreadManager,
    thread_id: u64,
    result: EvalResult,
) -> EvalResult {
    match result {
        Ok(val) => {
            threads.finish_thread(thread_id, val);
        }
        Err(Flow::Signal(ref sig)) => {
            let error_val = make_signal_binding_value(sig);
            threads.signal_thread(thread_id, error_val);
            // GNU publishes thread-last-error when the thread dies, not when
            // another thread joins it later.
            threads.record_last_error(error_val);
        }
        Err(Flow::Throw { ref tag, ref value }) => {
            let error_val = Value::list(vec![Value::symbol("no-catch"), *tag, *value]);
            threads.signal_thread(thread_id, error_val);
            threads.record_last_error(error_val);
        }
    }

    Ok(threads
        .thread_handle(thread_id)
        .unwrap_or_else(|| tagged_object_value("thread", thread_id)))
}

/// `(thread-join THREAD)` -- wait for thread completion.
///
/// Since all threads run synchronously at creation time, they are already
/// finished by the time anyone can call join. Returns the thread's result, or
/// re-signals the thread's terminal error the GNU way.
pub(crate) fn builtin_thread_join(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("thread-join", &args, 1)?;
    let id = expect_thread_id(&ctx.threads, &args[0])?;
    if !ctx.threads.is_thread(id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("threadp"), args[0]],
        ));
    }
    if id == ctx.threads.current_thread_id() {
        return Err(signal(
            "error",
            vec![Value::string("Cannot join current thread")],
        ));
    }
    if let Some(error) = ctx.threads.join_thread(id)
        && let Some(flow) = signal_from_binding_value(error)
    {
        return Err(flow);
    }
    Ok(ctx.threads.thread_result(id))
}

/// `(thread-yield)` -- yield the current thread.
///
/// No-op in our single-threaded simulation.
pub(crate) fn builtin_thread_yield(
    _ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("thread-yield", &args, 0)?;
    Ok(Value::NIL)
}

/// `(thread-name THREAD)` -- return the thread's name or nil.
pub(crate) fn builtin_thread_name(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("thread-name", &args, 1)?;
    let id = expect_thread_id(&ctx.threads, &args[0])?;
    if !ctx.threads.is_thread(id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("threadp"), args[0]],
        ));
    }
    match ctx.threads.thread_name(id) {
        Some(name) => Ok(Value::heap_string(name.clone())),
        None => Ok(Value::NIL),
    }
}

/// `(thread-live-p THREAD)` -- check if the thread is alive.
pub(crate) fn builtin_thread_live_p(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("thread-live-p", &args, 1)?;
    let id = expect_thread_id(&ctx.threads, &args[0])?;
    if !ctx.threads.is_thread(id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("threadp"), args[0]],
        ));
    }
    Ok(Value::bool_val(ctx.threads.thread_alive_p(id)))
}

/// `(threadp OBJ)` -- type predicate.
///
/// Returns t if OBJ is a known thread object.
pub(crate) fn builtin_threadp(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("threadp", &args, 1)?;
    Ok(Value::bool_val(
        ctx.threads.thread_id_from_handle(&args[0]).is_some(),
    ))
}

/// `(thread-signal THREAD ERROR-SYMBOL DATA)` -- send a signal to a thread.
///
/// In our simulation this records the pending error on the target thread.
pub(crate) fn builtin_thread_signal(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("thread-signal", &args, 3)?;
    let id = expect_thread_id(&ctx.threads, &args[0])?;
    if !ctx.threads.is_thread(id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("threadp"), args[0]],
        ));
    }
    let error_symbol = args[1];
    let Some(error_name) = error_symbol.as_symbol_name() else {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("symbolp"), error_symbol],
        ));
    };
    let data = args[2];
    if id == ctx.threads.current_thread_id() {
        return Err(signal_with_data(error_name, data));
    }
    ctx.threads
        .signal_thread(id, Value::cons(error_symbol, data));
    Ok(Value::NIL)
}

/// `(current-thread)` -- return the current thread object.
pub(crate) fn builtin_current_thread(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("current-thread", &args, 0)?;
    let id = ctx.threads.current_thread_id();
    Ok(ctx
        .threads
        .thread_handle(id)
        .unwrap_or_else(|| tagged_object_value("thread", id)))
}

/// `(all-threads)` -- return a list of all thread objects.
pub(crate) fn builtin_all_threads(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("all-threads", &args, 0)?;
    let mut ids = ctx.threads.all_thread_ids();
    ids.sort_unstable();
    let objects: Vec<Value> = ids
        .into_iter()
        .map(|id| {
            ctx.threads
                .thread_handle(id)
                .unwrap_or_else(|| tagged_object_value("thread", id))
        })
        .collect();
    Ok(Value::list(objects))
}

/// `(thread-last-error &optional CLEANUP)` -- return the last error.
///
/// If CLEANUP is non-nil, clear the stored error after returning it.
pub(crate) fn builtin_thread_last_error(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    if args.len() > 1 {
        return Err(signal(
            "wrong-number-of-arguments",
            vec![
                Value::symbol("thread-last-error"),
                Value::fixnum(args.len() as i64),
            ],
        ));
    }
    let cleanup = args.first().is_some_and(|v| v.is_truthy());
    Ok(ctx.threads.last_error(cleanup))
}

/// `(thread--blocker THREAD)` -- return the object THREAD is waiting on.
pub(crate) fn builtin_thread_blocker(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("thread--blocker", &args, 1)?;
    let id = expect_thread_id(&ctx.threads, &args[0])?;
    Ok(ctx.threads.thread_blocker(id).unwrap_or(Value::NIL))
}

/// `(thread-buffer-disposition THREAD)` -- return THREAD's buffer disposition.
pub(crate) fn builtin_thread_buffer_disposition(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("thread-buffer-disposition", &args, 1)?;
    let id = expect_thread_id(&ctx.threads, &args[0])?;
    Ok(ctx
        .threads
        .thread_buffer_disposition(id)
        .unwrap_or(Value::NIL))
}

/// `(thread-set-buffer-disposition THREAD VALUE)` -- set THREAD's buffer disposition.
pub(crate) fn builtin_thread_set_buffer_disposition(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("thread-set-buffer-disposition", &args, 2)?;
    let id = expect_thread_id(&ctx.threads, &args[0])?;
    let value = args[1];
    if id == 0 && !value.is_nil() {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("null"), value],
        ));
    }
    ctx.threads.set_thread_buffer_disposition(id, value);
    Ok(value)
}

// ===========================================================================
// Mutex builtins
// ===========================================================================

/// `(make-mutex &optional NAME)` -- create a mutex.
pub(crate) fn builtin_make_mutex(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    if args.len() > 1 {
        return Err(signal(
            "wrong-number-of-arguments",
            vec![
                Value::symbol("make-mutex"),
                Value::fixnum(args.len() as i64),
            ],
        ));
    }
    let name = if let Some(v) = args.first() {
        match v.kind() {
            ValueKind::String => Some(v.as_lisp_string().expect("string").clone()),
            ValueKind::Nil => None,
            other => {
                return Err(signal(
                    "wrong-type-argument",
                    vec![Value::symbol("stringp"), *v],
                ));
            }
        }
    } else {
        None
    };
    let id = ctx.threads.create_mutex(name);
    Ok(ctx
        .threads
        .mutex_handle(id)
        .unwrap_or_else(|| tagged_object_value("mutex", id)))
}

/// `(mutexp OBJ)` -- type predicate for mutexes.
pub(crate) fn builtin_mutexp(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("mutexp", &args, 1)?;
    Ok(Value::bool_val(
        ctx.threads.mutex_id_from_handle(&args[0]).is_some(),
    ))
}

/// `(mutex-name MUTEX)` -- return the mutex's name or nil.
pub(crate) fn builtin_mutex_name(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("mutex-name", &args, 1)?;
    let id = expect_mutex_id(&ctx.threads, &args[0])?;
    if !ctx.threads.is_mutex(id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("mutexp"), args[0]],
        ));
    }
    match ctx.threads.mutex_name(id) {
        Some(name) => Ok(Value::heap_string(name.clone())),
        None => Ok(Value::NIL),
    }
}

/// `(mutex-lock MUTEX)` -- lock a mutex.
///
/// In single-threaded mode, this always succeeds immediately.
pub(crate) fn builtin_mutex_lock(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("mutex-lock", &args, 1)?;
    let id = expect_mutex_id(&ctx.threads, &args[0])?;
    if !ctx.threads.is_mutex(id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("mutexp"), args[0]],
        ));
    }
    ctx.threads.mutex_lock(id);
    Ok(Value::NIL)
}

/// `(mutex-unlock MUTEX)` -- unlock a mutex.
pub(crate) fn builtin_mutex_unlock(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("mutex-unlock", &args, 1)?;
    let id = expect_mutex_id(&ctx.threads, &args[0])?;
    if !ctx.threads.is_mutex(id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("mutexp"), args[0]],
        ));
    }
    ctx.threads.mutex_unlock(id);
    Ok(Value::NIL)
}

// ===========================================================================
// Condition variable builtins
// ===========================================================================

/// `(make-condition-variable MUTEX &optional NAME)` -- create a condition variable.
pub(crate) fn builtin_make_condition_variable(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_min_args("make-condition-variable", &args, 1)?;
    if args.len() > 2 {
        return Err(signal(
            "wrong-number-of-arguments",
            vec![
                Value::symbol("make-condition-variable"),
                Value::fixnum(args.len() as i64),
            ],
        ));
    }
    let mutex_id = expect_mutex_id(&ctx.threads, &args[0])?;
    if !ctx.threads.is_mutex(mutex_id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("mutexp"), args[0]],
        ));
    }
    let name = if args.len() > 1 {
        match args[1].kind() {
            ValueKind::String => Some(args[1].as_lisp_string().expect("string").clone()),
            ValueKind::Nil => None,
            other => {
                return Err(signal(
                    "wrong-type-argument",
                    vec![Value::symbol("stringp"), args[1]],
                ));
            }
        }
    } else {
        None
    };
    match ctx.threads.create_condition_variable(mutex_id, name) {
        Some(id) => Ok(ctx
            .threads
            .condition_variable_handle(id)
            .unwrap_or_else(|| tagged_object_value("condition-variable", id))),
        None => Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("mutexp"), args[0]],
        )),
    }
}

/// `(condition-variable-p OBJ)` -- type predicate.
pub(crate) fn builtin_condition_variable_p(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("condition-variable-p", &args, 1)?;
    Ok(Value::bool_val(
        ctx.threads
            .condition_variable_id_from_handle(&args[0])
            .is_some(),
    ))
}

/// `(condition-name COND)` -- return COND's name string, or nil when unnamed.
pub(crate) fn builtin_condition_name(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("condition-name", &args, 1)?;
    let id = expect_cv_id(&ctx.threads, &args[0])?;
    if !ctx.threads.is_condition_variable(id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("condition-variable-p"), args[0]],
        ));
    }
    match ctx.threads.condition_variable_name(id) {
        Some(name) => Ok(Value::heap_string(name.clone())),
        None => Ok(Value::NIL),
    }
}

/// `(condition-mutex COND)` -- return COND's associated mutex object.
pub(crate) fn builtin_condition_mutex(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("condition-mutex", &args, 1)?;
    let id = expect_cv_id(&ctx.threads, &args[0])?;
    if !ctx.threads.is_condition_variable(id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("condition-variable-p"), args[0]],
        ));
    }
    let Some(mutex_id) = ctx.threads.condition_variable_mutex(id) else {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("condition-variable-p"), args[0]],
        ));
    };
    ctx.threads.mutex_handle(mutex_id).ok_or_else(|| {
        signal(
            "wrong-type-argument",
            vec![Value::symbol("condition-variable-p"), args[0]],
        )
    })
}

/// `(condition-wait COND)` -- wait on a condition variable.
///
/// In single-threaded mode this is a no-op.
pub(crate) fn builtin_condition_wait(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_args("condition-wait", &args, 1)?;
    let id = expect_cv_id(&ctx.threads, &args[0])?;
    if !ctx.threads.is_condition_variable(id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("condition-variable-p"), args[0]],
        ));
    }
    let Some(mutex_id) = ctx.threads.condition_variable_mutex(id) else {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("condition-variable-p"), args[0]],
        ));
    };
    if !ctx.threads.mutex_owned_by_current_thread(mutex_id) {
        return Err(signal(
            "error",
            vec![Value::string(
                "Condition variable's mutex is not held by current thread",
            )],
        ));
    }
    Ok(Value::NIL)
}

/// `(condition-notify COND &optional ALL)` -- notify on a condition variable.
///
/// No-op in single-threaded mode.
pub(crate) fn builtin_condition_notify(
    ctx: &mut crate::emacs_core::eval::Context,
    args: Vec<Value>,
) -> EvalResult {
    expect_min_args("condition-notify", &args, 1)?;
    if args.len() > 2 {
        return Err(signal(
            "wrong-number-of-arguments",
            vec![
                Value::symbol("condition-notify"),
                Value::fixnum(args.len() as i64),
            ],
        ));
    }
    let id = expect_cv_id(&ctx.threads, &args[0])?;
    if !ctx.threads.is_condition_variable(id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("condition-variable-p"), args[0]],
        ));
    }
    let Some(mutex_id) = ctx.threads.condition_variable_mutex(id) else {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("condition-variable-p"), args[0]],
        ));
    };
    if !ctx.threads.mutex_owned_by_current_thread(mutex_id) {
        return Err(signal(
            "error",
            vec![Value::string(
                "Condition variable's mutex is not held by current thread",
            )],
        ));
    }
    Ok(Value::NIL)
}

// ===========================================================================
// Special form: with-mutex
// ===========================================================================

/// `(with-mutex MUTEX BODY...)` -- execute BODY with MUTEX locked.
///
/// This is a special form: MUTEX is evaluated, the lock is acquired, BODY is
/// executed as an implicit progn, and the lock is released on exit
/// (even if BODY signals an error).
pub(crate) fn sf_with_mutex(eval: &mut super::eval::Context, tail: &[Value]) -> EvalResult {
    if tail.is_empty() {
        return Err(signal(
            "wrong-number-of-arguments",
            vec![
                Value::cons(Value::fixnum(1), Value::fixnum(1)),
                Value::fixnum(0),
            ],
        ));
    }
    let mutex_val = eval.eval_sub(tail[0])?;
    let mutex_id = expect_mutex_id(&eval.threads, &mutex_val)?;
    if !eval.threads.is_mutex(mutex_id) {
        return Err(signal(
            "wrong-type-argument",
            vec![Value::symbol("mutexp"), mutex_val],
        ));
    }

    eval.threads.mutex_lock(mutex_id);
    let mut result: EvalResult = Ok(Value::NIL);
    for form in &tail[1..] {
        result = eval.eval_sub(*form);
        if result.is_err() {
            break;
        }
    }
    eval.threads.mutex_unlock(mutex_id);
    result
}

// ===========================================================================
// Tests
// ===========================================================================
#[cfg(test)]
#[path = "threads_test.rs"]
mod tests;