/
thread.rs
1563 lines (1420 loc) · 54.4 KB
/
thread.rs
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
//! The thread/vm type
use std::any::Any;
use std::sync::{Mutex, RwLock, RwLockWriteGuard, RwLockReadGuard, MutexGuard};
use std::cmp::Ordering;
use std::fmt;
use std::mem;
use std::ops::{Add, Sub, Mul, Div, Deref, DerefMut};
use std::string::String as StdString;
use std::result::Result as StdResult;
use std::sync::Arc;
use std::usize;
use base::metadata::Metadata;
use base::pos::Line;
use base::symbol::Symbol;
use base::types::ArcType;
use base::types;
use {Variants, Error, Result};
use field_map::FieldMap;
use interner::InternedStr;
use macros::MacroEnv;
use api::{Getable, Pushable, VmType};
use compiler::CompiledFunction;
use gc::{DataDef, Gc, GcPtr, Generation, Move};
use source_map::LocalIter;
use stack::{Frame, Stack, StackFrame, State};
use types::*;
use vm::{GlobalVmState, VmEnv};
use value::{Value, ClosureData, ClosureInitDef, ClosureDataDef, Def, ExternFunction, GcStr,
BytecodeFunction, Callable, PartialApplicationDataDef, Userdata};
use value::Value::{Int, Float, String, Data, Function, PartialApplication, Closure};
pub use gc::Traverseable;
/// Enum signaling a successful or unsuccess ful call to an extern function.
/// If an error occured the error message is expected to be on the top of the stack.
#[derive(Eq, PartialEq)]
#[repr(C)]
pub enum Status {
Ok,
Yield,
Error,
}
/// A rooted value
#[derive(Clone, PartialEq)]
pub struct RootedValue<T>
where T: Deref<Target = Thread>,
{
vm: T,
value: Value,
}
impl<T> Drop for RootedValue<T>
where T: Deref<Target = Thread>,
{
fn drop(&mut self) {
// TODO not safe if the root changes order of being dropped with another root
self.vm.rooted_values.write().unwrap().pop();
}
}
impl<T> fmt::Debug for RootedValue<T>
where T: Deref<Target = Thread>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.value)
}
}
impl<T> Deref for RootedValue<T>
where T: Deref<Target = Thread>,
{
type Target = Value;
fn deref(&self) -> &Value {
&self.value
}
}
impl<T> RootedValue<T>
where T: Deref<Target = Thread>,
{
pub fn vm(&self) -> &Thread {
&self.vm
}
}
impl<'vm> RootedValue<&'vm Thread> {
pub fn vm_(&self) -> &'vm Thread {
self.vm
}
}
/// A rooted userdata value
pub struct Root<'vm, T: ?Sized + 'vm> {
roots: &'vm RwLock<Vec<GcPtr<Traverseable + Send + Sync>>>,
ptr: *const T,
}
impl<'vm, T: ?Sized> Drop for Root<'vm, T> {
fn drop(&mut self) {
// TODO not safe if the root changes order of being dropped with another root
self.roots.write().unwrap().pop();
}
}
impl<'vm, T: ?Sized> Deref for Root<'vm, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.ptr }
}
}
/// A rooted string
pub struct RootStr<'vm>(Root<'vm, str>);
impl<'vm> Deref for RootStr<'vm> {
type Target = str;
fn deref(&self) -> &str {
&self.0
}
}
struct Roots<'b> {
vm: GcPtr<Thread>,
stack: &'b Stack,
}
impl<'b> Traverseable for Roots<'b> {
fn traverse(&self, gc: &mut Gc) {
// Since this vm's stack is already borrowed in self we need to manually mark it to prevent
// it from being traversed normally
gc.mark(self.vm);
self.stack.get_values().traverse(gc);
// Traverse the vm's fields, avoiding the stack which is traversed above
self.vm.traverse_fields_except_stack(gc);
}
}
// All threads MUST be allocated in the garbage collected heap. This is necessary as a thread
// calling collect need to mark itself if it is on the garbage collected heap and it has no way of
// knowing wheter it is or not. So the only way of allowing it to mark itself is to disallow it to
// be allocated anywhere else.
/// Representation of the virtual machine
pub struct Thread {
global_state: Arc<GlobalVmState>,
// The parent of this thread, if it exists must live at least as long as this thread as this
// thread can refer to any value in the parent thread
parent: Option<RootedThread>,
roots: RwLock<Vec<GcPtr<Traverseable + Send + Sync>>>,
rooted_values: RwLock<Vec<Value>>,
/// All threads which this thread have spawned in turn. Necessary as this thread needs to scan
/// the roots of all its children as well since those may contain references to this threads
/// garbage collected values
child_threads: RwLock<Vec<GcPtr<Thread>>>,
context: Mutex<Context>,
}
impl fmt::Debug for Thread {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Thread({:p})", self)
}
}
impl Userdata for Thread {}
impl VmType for Thread {
type Type = Self;
}
impl Traverseable for Thread {
fn traverse(&self, gc: &mut Gc) {
self.traverse_fields_except_stack(gc);
self.context.lock().unwrap().stack.get_values().traverse(gc);
self.child_threads.read().unwrap().traverse(gc);
}
}
impl PartialEq for Thread {
fn eq(&self, other: &Thread) -> bool {
self as *const _ == other as *const _
}
}
impl VmType for RootedThread {
type Type = Thread;
}
impl<'vm> Pushable<'vm> for RootedThread {
fn push(self, _vm: &'vm Thread, context: &mut Context) -> Result<()> {
context.stack.push(Value::Thread(self.0));
Ok(())
}
}
/// An instance of `Thread` which is rooted. See the `Thread` type for documentation on interacting
/// with the type.
#[derive(Debug)]
pub struct RootedThread(GcPtr<Thread>);
impl Drop for RootedThread {
fn drop(&mut self) {
let is_empty = {
let mut roots = self.parent_threads();
let index = roots.iter()
.position(|p| &**p as *const Thread == &*self.0 as *const Thread)
.expect("VM ptr");
roots.swap_remove(index);
roots.is_empty()
};
if self.parent.is_none() && is_empty {
// The last RootedThread was dropped, there is no way to refer to the global state any
// longer so drop everything
let mut gc_ref = self.0.global_state.gc.lock().unwrap();
let gc_to_drop = ::std::mem::replace(&mut *gc_ref, Gc::new(Generation::default(), 0));
// Make sure that the RefMut is dropped before the Gc itself as the RwLock is dropped
// when the Gc is dropped
drop(gc_ref);
drop(gc_to_drop);
}
}
}
impl Deref for RootedThread {
type Target = Thread;
fn deref(&self) -> &Thread {
&self.0
}
}
impl Clone for RootedThread {
fn clone(&self) -> RootedThread {
self.root_thread()
}
}
impl Traverseable for RootedThread {
fn traverse(&self, gc: &mut Gc) {
self.0.traverse(gc);
}
}
impl RootedThread {
/// Creates a new virtual machine with an empty global environment
pub fn new() -> RootedThread {
let thread = Thread {
global_state: Arc::new(GlobalVmState::new()),
parent: None,
context: Mutex::new(Context::new(Gc::new(Generation::default(), usize::MAX))),
roots: RwLock::new(Vec::new()),
rooted_values: RwLock::new(Vec::new()),
child_threads: RwLock::new(Vec::new()),
};
let mut gc = Gc::new(Generation::default(), usize::MAX);
let vm =
gc.alloc(Move(thread)).expect("Not enough memory to allocate thread").root_thread();
*vm.global_state.gc.lock().unwrap() = gc;
// Enter the top level scope
{
let mut context = vm.context.lock().unwrap();
StackFrame::frame(&mut context.stack, 0, State::Unknown);
}
vm
}
/// Converts a `RootedThread` into a raw pointer allowing to be passed through a C api.
/// The reference count for the thread is not modified
pub fn into_raw(self) -> *const Thread {
let ptr: *const Thread = &*self.0;
::std::mem::forget(self);
ptr
}
/// Converts a raw pointer into a `RootedThread`.
/// The reference count for the thread is not modified so it is up to the caller to ensure that
/// the count is correct.
pub unsafe fn from_raw(ptr: *const Thread) -> RootedThread {
RootedThread(GcPtr::from_raw(ptr))
}
}
impl Thread {
/// Spawns a new gluon thread with its own stack and heap but while still sharing the same
/// global environment
pub fn new_thread(&self) -> Result<RootedThread> {
let vm = Thread {
global_state: self.global_state.clone(),
parent: Some(self.root_thread()),
context: Mutex::new(Context::new(self.current_context().gc.new_child_gc())),
roots: RwLock::new(Vec::new()),
rooted_values: RwLock::new(Vec::new()),
child_threads: RwLock::new(Vec::new()),
};
// Enter the top level scope
{
let mut context = vm.current_context();
StackFrame::frame(&mut context.stack, 0, State::Unknown);
}
let ptr = self.context().alloc(Move(vm))?;
Ok(ptr.root_thread())
}
/// Roots `self`, extending the lifetime of this thread until at least the returned
/// `RootedThread` is droppped
pub fn root_thread(&self) -> RootedThread {
unsafe {
let vm = RootedThread(GcPtr::from_raw(self));
vm.parent_threads().push(vm.0);
vm
}
}
/// Creates a new global value at `name`.
/// Fails if a global called `name` already exists.
pub fn define_global<'vm, T>(&'vm self, name: &str, value: T) -> Result<()>
where T: Pushable<'vm> + VmType,
{
let value = {
let mut context = self.context();
value.push(self, &mut context)?;
context.stack.pop()
};
self.set_global(Symbol::from(name),
T::make_type(self),
Metadata::default(),
value)
}
/// Retrieves the global called `name`.
/// Fails if the global does not exist or it does not have the correct type.
pub fn get_global<'vm, T>(&'vm self, name: &str) -> Result<T>
where T: Getable<'vm> + VmType,
{
use check::check_signature;
let env = self.get_env();
let (value, actual) = env.get_binding(name)?;
// Finally check that type of the returned value is correct
let expected = T::make_type(self);
if check_signature(&*env, &expected, &actual) {
T::from_value(self, Variants(&value))
.ok_or_else(|| Error::UndefinedBinding(name.into()))
} else {
Err(Error::WrongType(expected, actual.into_owned()))
}
}
/// Retrieves type information about the type `name`. Types inside records can be accessed
/// using dot notation (std.prelude.Option)
pub fn find_type_info(&self, name: &str) -> Result<types::Alias<Symbol, ArcType>> {
let env = self.get_env();
env.find_type_info(name)
.map(|alias| alias.into_owned())
}
/// Returns the gluon type that was bound to `T`
pub fn get_type<T: ?Sized + Any>(&self) -> ArcType {
self.global_env().get_type::<T>()
}
/// Registers the type `T` as being a gluon type called `name` with generic arguments `args`
pub fn register_type<T: ?Sized + Any>(&self, name: &str, args: &[&str]) -> Result<ArcType> {
self.global_env().register_type::<T>(name, args)
}
/// Locks and retrieves the global environment of the vm
pub fn get_env<'b>(&'b self) -> RwLockReadGuard<'b, VmEnv> {
self.global_env().get_env()
}
/// Retrieves the macros defined for this vm
pub fn get_macros(&self) -> &MacroEnv {
self.global_env().get_macros()
}
/// Runs a garbage collection.
pub fn collect(&self) {
let mut context = self.current_context();
self.with_roots(&mut context, |gc, roots| {
unsafe {
gc.collect(roots);
}
})
}
/// Pushes a value to the top of the stack
pub fn push<'vm, T>(&'vm self, v: T) -> Result<()>
where T: Pushable<'vm>,
{
let mut context = self.current_context();
v.push(self, &mut context)
}
/// Removes the top value from the stack
pub fn pop(&self) {
self.current_context()
.stack
.pop();
}
pub fn set_memory_limit(&self, memory_limit: usize) {
self.current_context().gc.set_memory_limit(memory_limit)
}
fn current_context(&self) -> OwnedContext {
OwnedContext {
thread: self,
context: self.context.lock().unwrap(),
}
}
fn traverse_fields_except_stack(&self, gc: &mut Gc) {
self.global_state.traverse(gc);
self.roots.read().unwrap().traverse(gc);
self.rooted_values.read().unwrap().traverse(gc);
}
fn parent_threads(&self) -> RwLockWriteGuard<Vec<GcPtr<Thread>>> {
match self.parent {
Some(ref parent) => parent.child_threads.write().unwrap(),
None => self.global_state.generation_0_threads.write().unwrap(),
}
}
fn with_roots<F, R>(&self, context: &mut Context, f: F) -> R
where F: for<'b> FnOnce(&mut Gc, Roots<'b>) -> R,
{
// For this to be safe we require that the received stack is the same one that is in this
// VM
assert!(unsafe {
context as *const _ as usize >= &self.context as *const _ as usize &&
context as *const _ as usize <= (&self.context as *const _).offset(1) as usize
});
let roots = Roots {
vm: unsafe {
// Threads must only be on the garbage collectors heap which makes this safe
GcPtr::from_raw(self)
},
stack: &context.stack,
};
f(&mut context.gc, roots)
}
fn call_context<'b>(&'b self,
mut context: OwnedContext<'b>,
args: VmIndex)
-> Result<Option<OwnedContext<'b>>> {
context.borrow_mut().do_call(args)?;
context.execute()
}
}
/// Internal functions for interacting with threads. These functions should be considered both
/// unsafe and unstable.
pub trait ThreadInternal {
/// Locks and retrives this threads stack
fn context(&self) -> OwnedContext;
/// Roots a userdata
fn root<'vm, T: Userdata>(&'vm self, v: GcPtr<Box<Userdata>>) -> Option<Root<'vm, T>>;
/// Roots a string
fn root_string<'vm>(&'vm self, ptr: GcStr) -> RootStr<'vm>;
/// Roots a value
fn root_value(&self, value: Value) -> RootedValue<RootedThread>;
/// Roots a value
fn root_value_ref(&self, value: Value) -> RootedValue<&Thread>;
fn add_bytecode(&self,
name: &str,
typ: ArcType,
args: VmIndex,
instructions: Vec<Instruction>)
-> Result<()>;
/// Evaluates a zero argument function (a thunk)
fn call_thunk(&self, closure: GcPtr<ClosureData>) -> Result<Value>;
/// Executes an `IO` action
fn execute_io(&self, value: Value) -> Result<Value>;
/// Calls a function on the stack.
/// When this function is called it is expected that the function exists at
/// `stack.len() - args - 1` and that the arguments are of the correct type
fn call_function<'b>(&'b self,
stack: OwnedContext<'b>,
args: VmIndex)
-> Result<Option<OwnedContext<'b>>>;
fn resume(&self) -> Result<()>;
fn global_env(&self) -> &Arc<GlobalVmState>;
fn set_global(&self,
name: Symbol,
typ: ArcType,
metadata: Metadata,
value: Value)
-> Result<()>;
/// `owner` is theread that owns `value` which is not necessarily the same as `self`
fn deep_clone_value(&self, owner: &Thread, value: Value) -> Result<Value>;
fn can_share_values_with(&self, gc: &mut Gc, other: &Thread) -> bool;
}
impl ThreadInternal for Thread {
fn context(&self) -> OwnedContext {
OwnedContext {
thread: self,
context: self.context.lock().unwrap(),
}
}
/// Roots a userdata
fn root<'vm, T: Userdata>(&'vm self, v: GcPtr<Box<Userdata>>) -> Option<Root<'vm, T>> {
v.downcast_ref::<T>()
.map(|ptr| {
self.roots.write().unwrap().push(v.as_traverseable());
Root {
roots: &self.roots,
ptr: ptr,
}
})
}
/// Roots a string
fn root_string<'vm>(&'vm self, ptr: GcStr) -> RootStr<'vm> {
self.roots.write().unwrap().push(ptr.into_inner().as_traverseable());
RootStr(Root {
roots: &self.roots,
ptr: &*ptr,
})
}
/// Roots a value
fn root_value(&self, value: Value) -> RootedValue<RootedThread> {
self.rooted_values.write().unwrap().push(value);
RootedValue {
vm: self.root_thread(),
value: value,
}
}
/// Roots a value
fn root_value_ref(&self, value: Value) -> RootedValue<&Thread> {
self.rooted_values.write().unwrap().push(value);
RootedValue {
vm: self,
value: value,
}
}
fn add_bytecode(&self,
name: &str,
typ: ArcType,
args: VmIndex,
instructions: Vec<Instruction>)
-> Result<()> {
let id = Symbol::from(name);
let mut compiled_fn = CompiledFunction::new(args, id.clone(), typ.clone(), "".into());
compiled_fn.instructions = instructions;
let closure = self.global_env().new_global_thunk(compiled_fn)?;
self.set_global(id, typ, Metadata::default(), Closure(closure)).unwrap();
Ok(())
}
fn call_thunk(&self, closure: GcPtr<ClosureData>) -> Result<Value> {
let mut context = self.current_context();
context.stack.push(Closure(closure));
context.borrow_mut().enter_scope(0, State::Closure(closure));
context.execute()?;
Ok(self.current_context().stack.pop())
}
/// Calls a module, allowed to to run IO expressions
fn execute_io(&self, value: Value) -> Result<Value> {
debug!("Run IO {:?}", value);
let mut context = OwnedContext {
thread: self,
context: self.context.lock().unwrap(),
};
// Dummy value to fill the place of the function for TailCall
context.stack.push(Int(0));
context.stack.push(value);
context.stack.push(Int(0));
context.borrow_mut().enter_scope(2, State::Unknown);
context = self.call_context(context, 1)?
.expect("call_module to have the stack remaining");
let result = context.stack.pop();
{
let mut context = context.borrow_mut();
while context.stack.len() > 0 {
context.stack.pop();
}
}
let _ = context.exit_scope();
Ok(result)
}
/// Calls a function on the stack.
/// When this function is called it is expected that the function exists at
/// `stack.len() - args - 1` and that the arguments are of the correct type
fn call_function<'b>(&'b self,
context: OwnedContext<'b>,
args: VmIndex)
-> Result<Option<OwnedContext<'b>>> {
self.call_context(context, args)
}
fn resume(&self) -> Result<()> {
let context = self.current_context();
if context.stack.get_frames().len() == 1 {
// Only the top level frame left means that the thread has finished
return Err(Error::Dead);
}
context.execute()
.map(|_| ())
}
fn global_env(&self) -> &Arc<GlobalVmState> {
&self.global_state
}
fn set_global(&self,
name: Symbol,
typ: ArcType,
metadata: Metadata,
value: Value)
-> Result<()> {
let value = ::value::Cloner::new(self, &mut self.global_env().gc.lock().unwrap()).deep_clone(value)?;
self.global_env().set_global(name, typ, metadata, value)
}
fn deep_clone_value(&self, owner: &Thread, value: Value) -> Result<Value> {
let mut context = self.current_context();
let full_clone = !self.can_share_values_with(&mut context.gc, owner);
let mut cloner = ::value::Cloner::new(self, &mut context.gc);
if full_clone {
cloner.force_full_clone();
}
cloner.deep_clone(value)
}
fn can_share_values_with(&self, gc: &mut Gc, other: &Thread) -> bool {
if self as *const Thread == other as *const Thread {
return true;
}
// If the threads do not share the same global state then they are disjoint and can't share
// values
if &*self.global_state as *const GlobalVmState !=
&*other.global_state as *const GlobalVmState {
return false;
}
// Otherwise the threads might be able to share values but only if they are on the same
// of the generation tree (see src/gc.rs)
// Search from the thread which MAY be a child to the parent. If `parent` could not be
// found then the threads must be in different branches of the tree
let self_gen = gc.generation();
let other_gen = other.context.lock().unwrap().gc.generation();
let (parent, mut child) = if self_gen.is_parent_of(other_gen) {
(self, other)
} else {
(other, self)
};
while let Some(ref next) = child.parent {
if &**next as *const Thread == parent as *const Thread {
return true;
}
child = next;
}
false
}
}
pub type HookFn = Box<FnMut(&Thread, DebugInfo) -> Result<()> + Send + Sync>;
pub struct DebugInfo<'a> {
stack: &'a Stack,
state: HookFlags,
}
pub struct StackInfo<'a> {
info: &'a DebugInfo<'a>,
index: usize,
}
impl<'a> DebugInfo<'a> {
/// Returns the reason for the hook being called
pub fn state(&self) -> HookFlags {
self.state
}
/// Returns a struct which can be queried about information about the stack
/// at a specific level where `0` is the currently executing frame.
pub fn stack_info(&self, level: usize) -> Option<StackInfo> {
let frames = self.stack.get_frames();
if level < frames.len() {
Some(StackInfo {
info: self,
index: frames.len() - level - 1,
})
} else {
None
}
}
}
impl<'a> StackInfo<'a> {
fn frame(&self) -> &Frame {
&self.info.stack.get_frames()[self.index]
}
/// Returns the line which create the current instruction of this frame
pub fn line(&self) -> Option<Line> {
let frame = self.frame();
match frame.state {
State::Closure(ref closure) => {
closure.function.source_map.line(frame.instruction_index)
}
_ => None,
}
}
/// Returns the name of the source which defined the funtion executing at this frame
pub fn source_name(&self) -> &str {
match self.frame().state {
State::Closure(ref closure) => &closure.function.source_name,
_ => "<unknown>",
}
}
/// Returns the name of the function executing at this frame
pub fn function_name(&self) -> Option<&str> {
match self.frame().state {
State::Unknown | State::Lock | State::Excess => None,
State::Closure(ref closure) => Some(closure.function.name.declared_name()),
State::Extern(ref function) => Some(function.id.declared_name()),
}
}
/// Returns an iterator over all locals available at the current executing instruction
pub fn locals(&self) -> LocalIter {
let frame = self.frame();
match frame.state {
State::Closure(ref closure) => {
closure.function.local_map.locals(frame.instruction_index)
}
_ => LocalIter::empty(),
}
}
pub fn upvars(&self) -> &[StdString] {
match self.frame().state {
State::Closure(ref closure) => &closure.function.upvar_names,
_ => panic!("Attempted to access upvar in non closure function"),
}
}
}
bitflags! {
pub flags HookFlags: u8 {
/// Call the hook when execution moves to a new line
const LINE_FLAG = 0b01,
/// Call the hook when a function is called
const CALL_FLAG = 0b10,
}
}
struct Hook {
function: Option<HookFn>,
flags: HookFlags,
// The index of the last executed instruction
previous_instruction_index: usize,
}
pub struct Context {
// FIXME It is dangerous to write to gc and stack
pub stack: Stack,
pub gc: Gc,
record_map: FieldMap,
hook: Hook,
max_stack_size: VmIndex,
}
impl Context {
fn new(gc: Gc) -> Context {
Context {
gc: gc,
stack: Stack::new(),
record_map: FieldMap::new(),
hook: Hook {
function: None,
flags: HookFlags::empty(),
previous_instruction_index: usize::max_value(),
},
max_stack_size: VmIndex::max_value(),
}
}
pub fn new_data(&mut self, thread: &Thread, tag: VmTag, fields: &[Value]) -> Result<Value> {
self.alloc_with(thread,
Def {
tag: tag,
elems: fields,
})
.map(Value::Data)
}
pub fn alloc_with<D>(&mut self, thread: &Thread, data: D) -> Result<GcPtr<D::Value>>
where D: DataDef + Traverseable,
D::Value: Sized + Any,
{
alloc(&mut self.gc, thread, &self.stack, data)
}
pub fn alloc_ignore_limit<D>(&mut self, data: D) -> GcPtr<D::Value>
where D: DataDef + Traverseable,
D::Value: Sized + Any,
{
self.gc.alloc_ignore_limit(data)
}
pub fn set_hook(&mut self, hook: Option<HookFn>) -> Option<HookFn> {
mem::replace(&mut self.hook.function, hook)
}
pub fn set_hook_mask(&mut self, flags: HookFlags) {
self.hook.flags = flags;
}
pub fn set_max_stack_size(&mut self, limit: VmIndex) {
self.max_stack_size = limit;
}
}
impl<'b> OwnedContext<'b> {
pub fn alloc<D>(&mut self, data: D) -> Result<GcPtr<D::Value>>
where D: DataDef + Traverseable,
D::Value: Sized + Any,
{
let Context { ref mut gc, ref stack, .. } = **self;
alloc(gc, self.thread, &stack, data)
}
pub fn debug_info(&self) -> DebugInfo {
DebugInfo {
stack: &self.stack,
state: HookFlags::empty(),
}
}
}
pub fn alloc<D>(gc: &mut Gc, thread: &Thread, stack: &Stack, def: D) -> Result<GcPtr<D::Value>>
where D: DataDef + Traverseable,
D::Value: Sized + Any,
{
let roots = Roots {
vm: unsafe {
// Threads must only be on the garbage collectors heap which makes this safe
GcPtr::from_raw(thread)
},
stack: stack,
};
unsafe { gc.alloc_and_collect(roots, def) }
}
pub struct OwnedContext<'b> {
thread: &'b Thread,
context: MutexGuard<'b, Context>,
}
impl<'b> Deref for OwnedContext<'b> {
type Target = Context;
fn deref(&self) -> &Context {
&self.context
}
}
impl<'b> DerefMut for OwnedContext<'b> {
fn deref_mut(&mut self) -> &mut Context {
&mut self.context
}
}
impl<'b> OwnedContext<'b> {
fn exit_scope(mut self) -> StdResult<OwnedContext<'b>, ()> {
let exists = StackFrame::current(&mut self.stack).exit_scope().is_ok();
if exists { Ok(self) } else { Err(()) }
}
fn execute(self) -> Result<Option<OwnedContext<'b>>> {
let mut maybe_context = Some(self);
while let Some(mut context) = maybe_context {
debug!("STACK\n{:?}", context.stack.get_frames());
let state = context.borrow_mut().stack.frame.state;
let instruction_index = context.borrow_mut().stack.frame.instruction_index;
if instruction_index == 0 && context.hook.flags.contains(CALL_FLAG) {
match state {
State::Extern(_) |
State::Closure(_) => {
let thread = context.thread;
let context = &mut *context;
if let Some(ref mut hook) = context.hook.function {
let info = DebugInfo {
stack: &context.stack,
state: CALL_FLAG,
};
hook(thread, info)?
}
}
_ => (),
}
}
maybe_context = match state {
State::Lock | State::Unknown => return Ok(Some(context)),
State::Excess => context.exit_scope().ok(),
State::Extern(ext) => {
let instruction_index = context.borrow_mut().stack.frame.instruction_index;
if instruction_index != 0 {
// This function was already called
return Ok(Some(context));
} else {
context.borrow_mut().stack.frame.instruction_index = 1;
Some(context.execute_function(&ext)?)
}
}
State::Closure(closure) => {
let max_stack_size = context.max_stack_size;
// Tail calls into extern functions at the top level will drop the last
// stackframe so just return immedietly
enum State {
Exists,
DoesNotExist,
ReturnContext,
}
let state = {
let mut context = context.borrow_mut();
let instruction_index = context.stack.frame.instruction_index;
let function_size = closure.function.max_stack_size;
// Before entering a function check that the stack cannot exceed `max_stack_size`
if instruction_index == 0 {
if context.stack.stack.len() + function_size > max_stack_size {
return Err(Error::StackOverflow(max_stack_size));
}
}
if context.stack.stack.get_frames().len() == 0 {
State::ReturnContext
} else {
debug!("Continue with {}\nAt: {}/{}",
closure.function.name,
instruction_index,
closure.function.instructions.len());
let new_context = context.execute_(instruction_index,
&closure.function
.instructions,
&closure.function)?;
if new_context.is_some() {
State::Exists
} else {
State::DoesNotExist
}
}
};
match state {
State::Exists => Some(context),
State::DoesNotExist => None,
State::ReturnContext => return Ok(Some(context)),
}
}
};
}
Ok(maybe_context)
}
fn execute_function(mut self, function: &ExternFunction) -> Result<OwnedContext<'b>> {
debug!("CALL EXTERN {} {:?}", function.id, self.stack);
// Make sure that the stack is not borrowed during the external function call
// Necessary since we do not know what will happen during the function call
let thread = self.thread;
drop(self);
let status = (function.function)(thread);
self = thread.current_context();
let result = self.stack.pop();
{
let mut stack = self.stack.current_frame();
while stack.len() > 0 {