-
Notifications
You must be signed in to change notification settings - Fork 145
/
value.rs
1460 lines (1318 loc) · 45.7 KB
/
value.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
use std::collections::hash_map::Entry;
use std::fmt;
use std::mem::size_of;
use std::result::Result as StdResult;
use itertools::Itertools;
use pretty::{Arena, DocAllocator, DocBuilder};
use base::symbol::Symbol;
use base::types::{ArcType, Type, TypeEnv};
use types::*;
use base::fnv::FnvMap;
use base::types::pretty_print::ident as pretty_ident;
use interner::InternedStr;
use compiler::DebugInfo;
use gc::{DataDef, Gc, GcPtr, Generation, Move, Traverseable, WriteOnly};
use array::Array;
use thread::{Status, Thread};
use {Error, Result, Variants};
use self::Value::{Closure, Float, Function, Int, PartialApplication, String};
mopafy!(Userdata);
pub trait Userdata: ::mopa::Any + Traverseable + fmt::Debug + Send + Sync {
fn deep_clone(&self, deep_cloner: &mut Cloner) -> Result<GcPtr<Box<Userdata>>> {
let _ = deep_cloner;
Err(Error::Message("Userdata cannot be cloned".into()))
}
}
impl PartialEq for Userdata {
fn eq(&self, other: &Userdata) -> bool {
self as *const _ == other as *const _
}
}
#[derive(Debug, PartialEq)]
#[repr(C)]
pub struct ClosureData {
pub function: GcPtr<BytecodeFunction>,
pub upvars: Array<Value>,
}
impl Traverseable for ClosureData {
fn traverse(&self, gc: &mut Gc) {
self.function.traverse(gc);
self.upvars.traverse(gc);
}
}
pub struct ClosureDataDef<'b>(pub GcPtr<BytecodeFunction>, pub &'b [Value]);
impl<'b> Traverseable for ClosureDataDef<'b> {
fn traverse(&self, gc: &mut Gc) {
self.0.traverse(gc);
self.1.traverse(gc);
}
}
unsafe impl<'b> DataDef for ClosureDataDef<'b> {
type Value = ClosureData;
fn size(&self) -> usize {
size_of::<GcPtr<BytecodeFunction>>() + Array::<Value>::size_of(self.1.len())
}
fn initialize<'w>(self, mut result: WriteOnly<'w, ClosureData>) -> &'w mut ClosureData {
unsafe {
let result = &mut *result.as_mut_ptr();
result.function = self.0;
result.upvars.initialize(self.1.iter().cloned());
result
}
}
}
pub struct ClosureInitDef(pub GcPtr<BytecodeFunction>, pub usize);
impl Traverseable for ClosureInitDef {
fn traverse(&self, gc: &mut Gc) {
self.0.traverse(gc);
}
}
unsafe impl DataDef for ClosureInitDef {
type Value = ClosureData;
fn size(&self) -> usize {
size_of::<GcPtr<BytecodeFunction>>() + Array::<Value>::size_of(self.1)
}
fn initialize<'w>(self, mut result: WriteOnly<'w, ClosureData>) -> &'w mut ClosureData {
use std::ptr;
unsafe {
let result = &mut *result.as_mut_ptr();
result.function = self.0;
result.upvars.set_len(self.1);
for var in &mut result.upvars {
ptr::write(var, Int(0));
}
result
}
}
}
#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "serde_derive", derive(DeserializeState, SerializeState))]
#[cfg_attr(feature = "serde_derive", serde(deserialize_state = "::serialization::DeSeed"))]
#[cfg_attr(feature = "serde_derive", serde(serialize_state = "::serialization::SeSeed"))]
pub struct BytecodeFunction {
#[cfg_attr(feature = "serde_derive", serde(state_with = "::serialization::symbol"))]
pub name: Symbol,
pub args: VmIndex,
pub max_stack_size: VmIndex,
pub instructions: Vec<Instruction>,
#[cfg_attr(feature = "serde_derive", serde(state))]
pub inner_functions: Vec<GcPtr<BytecodeFunction>>,
#[cfg_attr(feature = "serde_derive", serde(state))] pub strings: Vec<InternedStr>,
#[cfg_attr(feature = "serde_derive", serde(state))] pub records: Vec<Vec<InternedStr>>,
#[cfg_attr(feature = "serde_derive", serde(state))] pub debug_info: DebugInfo,
}
impl Traverseable for BytecodeFunction {
fn traverse(&self, gc: &mut Gc) {
self.inner_functions.traverse(gc);
}
}
#[derive(Debug)]
#[repr(C)]
pub struct DataStruct {
tag: VmTag,
pub fields: Array<Value>,
}
impl Traverseable for DataStruct {
fn traverse(&self, gc: &mut Gc) {
self.fields.traverse(gc);
}
}
impl PartialEq for DataStruct {
fn eq(&self, other: &DataStruct) -> bool {
self.tag == other.tag && self.fields == other.fields
}
}
impl DataStruct {
pub fn record_bit() -> VmTag {
1 << ((size_of::<VmTag>() * 8) - 1)
}
pub fn tag(&self) -> VmTag {
self.tag & !Self::record_bit()
}
pub fn is_record(&self) -> bool {
(self.tag & Self::record_bit()) != 0
}
}
impl GcPtr<DataStruct> {
pub fn get(&self, vm: &Thread, field: &str) -> Result<Option<&Value>> {
use thread::ThreadInternal;
let field = vm.global_env().intern(field)?;
Ok(self.get_field(field))
}
pub fn get_field(&self, field: InternedStr) -> Option<&Value> {
self.field_map()
.get(&field)
.map(|offset| &self.fields[*offset as usize])
}
}
/// Definition for data values in the VM
pub struct Def<'b> {
pub tag: VmTag,
pub elems: &'b [Value],
}
unsafe impl<'b> DataDef for Def<'b> {
type Value = DataStruct;
fn size(&self) -> usize {
size_of::<usize>() + Array::<Value>::size_of(self.elems.len())
}
fn initialize<'w>(self, mut result: WriteOnly<'w, DataStruct>) -> &'w mut DataStruct {
unsafe {
let result = &mut *result.as_mut_ptr();
result.tag = self.tag;
result.fields.initialize(self.elems.iter().cloned());
result
}
}
}
impl<'b> Traverseable for Def<'b> {
fn traverse(&self, gc: &mut Gc) {
self.elems.traverse(gc);
}
}
pub struct RecordDef<'b> {
pub elems: &'b [Value],
pub fields: &'b [InternedStr],
}
unsafe impl<'b> DataDef for RecordDef<'b> {
type Value = DataStruct;
fn size(&self) -> usize {
size_of::<usize>() + Array::<Value>::size_of(self.elems.len())
}
fn initialize<'w>(self, mut result: WriteOnly<'w, DataStruct>) -> &'w mut DataStruct {
unsafe {
let result = &mut *result.as_mut_ptr();
result.tag = 1 << ((size_of::<VmTag>() * 8) - 1);
result.fields.initialize(self.elems.iter().cloned());
result
}
}
fn fields(&self) -> Option<&[InternedStr]> {
Some(self.fields)
}
}
impl<'b> Traverseable for RecordDef<'b> {
fn traverse(&self, gc: &mut Gc) {
self.elems.traverse(gc);
}
}
mod gc_str {
use super::ValueArray;
use gc::{Gc, GcPtr, Generation, Traverseable};
use std::fmt;
use std::str;
use std::ops::Deref;
#[derive(Copy, Clone, PartialEq)]
pub struct GcStr(GcPtr<ValueArray>);
impl fmt::Debug for GcStr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("GcStr").field(&&**self).finish()
}
}
impl Eq for GcStr {}
impl GcStr {
pub fn from_utf8(array: GcPtr<ValueArray>) -> Result<GcStr, ()> {
unsafe {
if array
.as_slice::<u8>()
.and_then(|bytes| str::from_utf8(bytes).ok())
.is_some()
{
Ok(GcStr::from_utf8_unchecked(array))
} else {
Err(())
}
}
}
pub unsafe fn from_utf8_unchecked(array: GcPtr<ValueArray>) -> GcStr {
GcStr(array)
}
pub fn into_inner(self) -> GcPtr<ValueArray> {
self.0
}
pub fn generation(&self) -> Generation {
self.0.generation()
}
}
impl Deref for GcStr {
type Target = str;
fn deref(&self) -> &str {
unsafe { str::from_utf8_unchecked(self.0.as_slice::<u8>().unwrap()) }
}
}
impl Traverseable for GcStr {
fn traverse(&self, gc: &mut Gc) {
self.0.traverse(gc)
}
}
}
pub use self::gc_str::GcStr;
#[derive(Copy, Clone, PartialEq)]
#[cfg_attr(feature = "serde_derive", derive(DeserializeState, SerializeState))]
#[cfg_attr(feature = "serde_derive", serde(deserialize_state = "::serialization::DeSeed"))]
#[cfg_attr(feature = "serde_derive", serde(serialize_state = "::serialization::SeSeed"))]
pub enum Value {
Byte(u8),
Int(VmInt),
Float(f64),
String(#[cfg_attr(feature = "serde_derive", serde(deserialize_state))] GcStr),
Tag(VmTag),
Data(
#[cfg_attr(feature = "serde_derive",
serde(deserialize_state_with = "::serialization::gc::deserialize_data"))]
#[cfg_attr(feature = "serde_derive", serde(serialize_state))]
GcPtr<DataStruct>,
),
Array(
#[cfg_attr(feature = "serde_derive",
serde(deserialize_state_with = "::serialization::gc::deserialize_array"))]
#[cfg_attr(feature = "serde_derive", serde(serialize_state))]
GcPtr<ValueArray>,
),
Function(#[cfg_attr(feature = "serde_derive", serde(state))] GcPtr<ExternFunction>),
Closure(
#[cfg_attr(feature = "serde_derive", serde(state_with = "::serialization::closure"))]
GcPtr<ClosureData>,
),
PartialApplication(
#[cfg_attr(feature = "serde_derive",
serde(deserialize_state_with = "::serialization::deserialize_application"))]
#[cfg_attr(feature = "serde_derive", serde(serialize_state))]
GcPtr<PartialApplicationData>,
),
// TODO Implement serializing of userdata
#[cfg_attr(feature = "serde_derive", serde(skip_deserializing))]
Userdata(
#[cfg_attr(feature = "serde_derive",
serde(serialize_with = "::serialization::serialize_userdata"))]
GcPtr<Box<Userdata>>,
),
#[cfg_attr(feature = "serde_derive", serde(skip_deserializing))]
#[cfg_attr(feature = "serde_derive", serde(skip_serializing))]
Thread(#[cfg_attr(feature = "serde_derive", serde(deserialize_state))] GcPtr<Thread>),
}
impl Value {
pub fn generation(self) -> Generation {
match self {
String(p) => p.generation(),
Value::Data(p) => p.generation(),
Function(p) => p.generation(),
Closure(p) => p.generation(),
Value::Array(p) => p.generation(),
PartialApplication(p) => p.generation(),
Value::Userdata(p) => p.generation(),
Value::Thread(p) => p.generation(),
Value::Tag(_) | Value::Byte(_) | Int(_) | Float(_) => Generation::default(),
}
}
}
#[derive(PartialEq, Copy, Clone, PartialOrd)]
enum Prec {
Top,
Constructor,
}
use self::Prec::*;
pub struct ValuePrinter<'a> {
pub typ: &'a ArcType,
pub env: &'a TypeEnv,
pub value: Value,
pub max_level: i32,
pub width: usize,
}
impl<'t> ValuePrinter<'t> {
pub fn new(env: &'t TypeEnv, typ: &'t ArcType, value: Value) -> ValuePrinter<'t> {
ValuePrinter {
typ: typ,
env: env,
value: value,
max_level: 50,
width: 80,
}
}
pub fn max_level(&mut self, max_level: i32) -> &mut ValuePrinter<'t> {
self.max_level = max_level;
self
}
pub fn width(&mut self, width: usize) -> &mut ValuePrinter<'t> {
self.width = width;
self
}
}
const INDENT: usize = 4;
struct InternalPrinter<'a, 't> {
typ: &'t ArcType,
env: &'t TypeEnv,
arena: &'a Arena<'a>,
prec: Prec,
level: i32,
}
impl<'a> fmt::Display for ValuePrinter<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let arena = Arena::new();
let mut s = Vec::new();
InternalPrinter {
typ: self.typ,
env: self.env,
arena: &arena,
prec: Top,
level: self.max_level,
}.pretty(self.value)
.group()
.1
.render(self.width, &mut s)
.map_err(|_| fmt::Error)?;
write!(f, "{}", ::std::str::from_utf8(&s).expect("utf-8"))
}
}
impl<'a, 't> InternalPrinter<'a, 't> {
fn pretty(&self, value: Value) -> DocBuilder<'a, Arena<'a>> {
use std::iter;
let arena = self.arena;
match value {
_ if self.level == 0 => arena.text(".."),
Value::String(s) => arena.text(format!("{:?}", &s[..])),
Value::Data(ref data) => self.pretty_data(data.tag, data.fields.iter().cloned()),
Value::Tag(tag) => self.pretty_data(tag, iter::empty()),
Value::Function(ref function) => chain![arena;
"<extern ",
function.id.declared_name().to_string(),
">"
],
Value::Closure(ref closure) => chain![arena;
"<",
arena.text(closure.function.name.declared_name().to_string()),
arena.concat(closure.upvars.iter().zip(&closure.function.debug_info.upvars)
.map(|(field, info)| {
chain![arena;
arena.space(),
info.name.clone(),
":",
arena.space(),
self.p(&info.typ, Top).pretty(*field)
]
}).intersperse(arena.text(","))).nest(INDENT),
">"
],
Value::Array(ref array) => chain![arena;
"[",
arena.concat(array.iter().map(|field| {
match **self.typ {
Type::App(_, ref args) => self.p(&args[0], Top).pretty(field),
_ => arena.text(format!("{:?}", field)),
}
}).intersperse(arena.text(",").append(arena.space())))
.nest(INDENT),
"]"
],
Value::PartialApplication(p) => arena.text(format!("{:?}", p)),
Value::Userdata(ref data) => arena.text(format!("{:?}", data)),
Value::Thread(thread) => arena.text(format!("{:?}", thread)),
Value::Byte(b) => arena.text(format!("{}", b)),
Value::Int(i) => {
use base::types::BuiltinType;
match **self.typ {
Type::Builtin(BuiltinType::Int) => arena.text(format!("{}", i)),
Type::Builtin(BuiltinType::Char) => match ::std::char::from_u32(i as u32) {
Some('"') => arena.text(format!("'{}'", '"')),
Some(c) => arena.text(format!("'{}'", c.escape_default())),
None => ice!(
"Invalid character (code point {}) passed to pretty printing",
i
),
},
_ => arena.text(format!("{}", i)),
}
}
Value::Float(f) => arena.text(format!("{}", f)),
}
}
fn pretty_data<I>(&self, tag: VmTag, fields: I) -> DocBuilder<'a, Arena<'a>>
where
I: IntoIterator<Item = Value>,
{
fn enclose<'a>(
p: Prec,
limit: Prec,
arena: &'a Arena<'a>,
doc: DocBuilder<'a, Arena<'a>>,
) -> DocBuilder<'a, Arena<'a>> {
if p >= limit {
chain![arena; "(", doc, ")"]
} else {
doc
}
}
use base::resolve::remove_aliases_cow;
use base::types::arg_iter;
let typ = remove_aliases_cow(self.env, self.typ);
let arena = self.arena;
match **typ {
Type::Record(ref row) => {
let mut is_empty = true;
let fields_doc = arena.concat(
fields
.into_iter()
.zip(row.row_iter())
.map(|(field, type_field)| {
is_empty = false;
chain![arena;
pretty_ident(arena, type_field.name.declared_name().to_string()),
":",
chain![arena;
arena.space(),
self.p(&type_field.typ, Top).pretty(field),
arena.text(",")
].nest(INDENT)
].group()
})
.intersperse(arena.space()),
);
chain![arena;
"{",
chain![arena;
arena.space(),
fields_doc
].nest(INDENT),
if is_empty {
arena.nil()
} else {
arena.space()
},
"}"
]
}
Type::Variant(ref row) => {
let type_field = row.row_iter()
.nth(tag as usize)
.expect("Variant tag is out of bounds");
let mut empty = true;
let doc = chain![arena;
type_field.name.declared_name().to_string(),
arena.concat(fields.into_iter().zip(arg_iter(&type_field.typ))
.map(|(field, typ)| {
empty = false;
arena.space().append(self.p(typ, Constructor).pretty(field))
}))
.nest(INDENT)
];
if empty {
doc
} else {
enclose(self.prec, Constructor, arena, doc)
}
}
_ => chain![arena;
"{",
arena.concat(fields.into_iter().map(|field| {
arena.space().append(self.p(&Type::hole(), Top).pretty(field))
}).intersperse(arena.text(",")))
.nest(INDENT),
arena.space(),
"}"
],
}
}
fn p(&self, typ: &'t ArcType, prec: Prec) -> InternalPrinter<'a, 't> {
InternalPrinter {
typ: typ,
env: self.env,
arena: self.arena,
prec: prec,
level: self.level - 1,
}
}
}
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "serde_derive", derive(DeserializeState, SerializeState))]
#[cfg_attr(feature = "serde_derive", serde(deserialize_state = "::serialization::DeSeed"))]
#[cfg_attr(feature = "serde_derive", serde(serialize_state = "::serialization::SeSeed"))]
pub enum Callable {
Closure(
#[cfg_attr(feature = "serde_derive", serde(state_with = "::serialization::closure"))]
GcPtr<ClosureData>,
),
Extern(#[cfg_attr(feature = "serde_derive", serde(state))] GcPtr<ExternFunction>),
}
impl Callable {
pub fn name(&self) -> &Symbol {
match *self {
Callable::Closure(ref closure) => &closure.function.name,
Callable::Extern(ref ext) => &ext.id,
}
}
pub fn args(&self) -> VmIndex {
match *self {
Callable::Closure(ref closure) => closure.function.args,
Callable::Extern(ref ext) => ext.args,
}
}
}
impl PartialEq for Callable {
fn eq(&self, _: &Callable) -> bool {
false
}
}
impl Traverseable for Callable {
fn traverse(&self, gc: &mut Gc) {
match *self {
Callable::Closure(ref closure) => closure.traverse(gc),
Callable::Extern(ref ext) => ext.traverse(gc),
}
}
}
#[derive(Debug)]
#[repr(C)]
#[cfg_attr(feature = "serde_derive", derive(SerializeState))]
#[cfg_attr(feature = "serde_derive", serde(serialize_state = "::serialization::SeSeed"))]
pub struct PartialApplicationData {
#[cfg_attr(feature = "serde_derive", serde(serialize_state))] pub function: Callable,
#[cfg_attr(feature = "serde_derive", serde(serialize_state))] pub args: Array<Value>,
}
impl PartialEq for PartialApplicationData {
fn eq(&self, _: &PartialApplicationData) -> bool {
false
}
}
impl Traverseable for PartialApplicationData {
fn traverse(&self, gc: &mut Gc) {
self.function.traverse(gc);
self.args.traverse(gc);
}
}
pub struct PartialApplicationDataDef<'b>(pub Callable, pub &'b [Value]);
impl<'b> Traverseable for PartialApplicationDataDef<'b> {
fn traverse(&self, gc: &mut Gc) {
self.0.traverse(gc);
self.1.traverse(gc);
}
}
unsafe impl<'b> DataDef for PartialApplicationDataDef<'b> {
type Value = PartialApplicationData;
fn size(&self) -> usize {
use std::mem::size_of;
size_of::<Callable>() + Array::<Value>::size_of(self.1.len())
}
fn initialize<'w>(
self,
mut result: WriteOnly<'w, PartialApplicationData>,
) -> &'w mut PartialApplicationData {
unsafe {
let result = &mut *result.as_mut_ptr();
result.function = self.0;
result.args.initialize(self.1.iter().cloned());
result
}
}
}
impl Traverseable for Value {
fn traverse(&self, gc: &mut Gc) {
match *self {
String(ref data) => data.traverse(gc),
Value::Data(ref data) => data.traverse(gc),
Value::Array(ref data) => data.traverse(gc),
Function(ref data) => data.traverse(gc),
Closure(ref data) => data.traverse(gc),
Value::Userdata(ref data) => data.traverse(gc),
PartialApplication(ref data) => data.traverse(gc),
Value::Thread(ref thread) => thread.traverse(gc),
Value::Tag(_) | Value::Byte(_) | Int(_) | Float(_) => (),
}
}
}
impl fmt::Debug for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
struct Level<'b>(i32, &'b Value);
struct LevelSlice<'b>(i32, &'b [Value]);
impl<'b> fmt::Debug for LevelSlice<'b> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let level = self.0;
if level <= 0 || self.1.is_empty() {
return Ok(());
}
write!(f, "{:?}", Level(level - 1, &self.1[0]))?;
for v in &self.1[1..] {
write!(f, ", {:?}", Level(level - 1, v))?;
}
Ok(())
}
}
impl<'b> fmt::Debug for Level<'b> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let level = self.0;
if level <= 0 {
return Ok(());
}
match *self.1 {
Value::Byte(i) => write!(f, "{:?}b", i),
Int(i) => write!(f, "{:?}", i),
Float(x) => write!(f, "{:?}f", x),
String(x) => write!(f, "{:?}", &*x),
Value::Tag(tag) => write!(f, "{{{:?}: }}", tag),
Value::Data(ref data) => write!(
f,
"{{{:?}: {:?}}}",
data.tag,
LevelSlice(level - 1, &data.fields)
),
Value::Array(ref array) => {
let mut first = true;
write!(f, "[")?;
for value in array.iter() {
if !first {
write!(f, ", ")?;
}
first = false;
write!(f, "{:?}", Level(level - 1, &value))?;
}
write!(f, "]")
}
Function(ref func) => write!(f, "<EXTERN {:?}>", &**func),
Closure(ref closure) => {
let p: *const _ = &*closure.function;
write!(f, "<{:?} {:?}>", closure.function.name, p)
}
PartialApplication(ref app) => {
let name = match app.function {
Callable::Closure(_) => "<CLOSURE>",
Callable::Extern(_) => "<EXTERN>",
};
write!(f, "<App {:?}{:?}>", name, LevelSlice(level - 1, &app.args))
}
Value::Userdata(ref data) => write!(f, "<Userdata {:?}>", &**data),
Value::Thread(_) => write!(f, "<thread>"),
}
}
}
write!(f, "{:?}", Level(7, self))
}
}
#[cfg_attr(feature = "serde_derive", derive(SerializeState))]
#[cfg_attr(feature = "serde_derive", serde(serialize_state = "::serialization::SeSeed"))]
pub struct ExternFunction {
#[cfg_attr(feature = "serde_derive",
serde(serialize_state_with = "::serialization::symbol::serialize"))]
pub id: Symbol,
pub args: VmIndex,
#[cfg_attr(feature = "serde_derive", serde(skip_serializing))]
pub function: extern "C" fn(&Thread) -> Status,
}
impl Clone for ExternFunction {
fn clone(&self) -> ExternFunction {
ExternFunction {
id: self.id.clone(),
args: self.args,
function: self.function,
}
}
}
impl PartialEq for ExternFunction {
fn eq(&self, other: &ExternFunction) -> bool {
self.id == other.id && self.args == other.args
&& self.function as usize == other.function as usize
}
}
impl fmt::Debug for ExternFunction {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// read the v-table pointer of the Fn(..) type and print that
let p: *const () = unsafe { ::std::mem::transmute(self.function) };
write!(f, "{} {:?}", self.id, p)
}
}
impl Traverseable for ExternFunction {
fn traverse(&self, _: &mut Gc) {}
}
/// Representation of values which can be stored directly in an array
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Repr {
Byte,
Int,
Float,
String,
Array,
Unknown,
Userdata,
Thread,
}
pub unsafe trait ArrayRepr {
fn matches(repr: Repr) -> bool;
}
macro_rules! impl_repr {
($($id: ty, $repr: path),*) => {
$(
unsafe impl ArrayRepr for $id {
fn matches(repr: Repr) -> bool { repr == $repr }
}
unsafe impl<'a> DataDef for &'a [$id] {
type Value = ValueArray;
fn size(&self) -> usize {
use std::mem::size_of;
size_of::<ValueArray>() + self.len() * size_of::<$id>()
}
fn initialize<'w>(self, mut result: WriteOnly<'w, ValueArray>) -> &'w mut ValueArray {
unsafe {
let result = &mut *result.as_mut_ptr();
result.set_repr($repr);
result.unsafe_array_mut::<$id>().initialize(self.iter().cloned());
result
}
}
}
unsafe impl DataDef for Vec<$id> {
type Value = ValueArray;
fn size(&self) -> usize {
DataDef::size(&&self[..])
}
fn initialize<'w>(self, result: WriteOnly<'w, ValueArray>) -> &'w mut ValueArray {
DataDef::initialize(&self[..], result)
}
}
)*
impl Repr {
fn size_of(self) -> usize {
use std::mem::size_of;
match self {
$(
$repr => size_of::<$id>(),
)*
}
}
}
}
}
impl_repr! {
u8, Repr::Byte,
VmInt, Repr::Int,
f64, Repr::Float,
GcStr, Repr::String,
GcPtr<ValueArray>, Repr::Array,
Value, Repr::Unknown,
GcPtr<Box<Userdata>>, Repr::Userdata,
GcPtr<Thread>, Repr::Thread
}
impl Repr {
fn from_value(value: Value) -> Repr {
match value {
Value::Byte(_) => Repr::Byte,
Value::Int(_) => Repr::Int,
Value::Float(_) => Repr::Float,
Value::String(_) => Repr::String,
Value::Array(_) => Repr::Array,
Value::Data(_)
| Value::Tag(_)
| Value::Function(_)
| Value::Closure(_)
| Value::PartialApplication(_) => Repr::Unknown,
Value::Userdata(_) => Repr::Userdata,
Value::Thread(_) => Repr::Thread,
}
}
}
macro_rules! on_array {
($array: expr, $f: expr) => {
{
let ref array = $array;
unsafe {
match array.repr() {
Repr::Byte => $f(array.unsafe_array::<u8>()),
Repr::Int => $f(array.unsafe_array::<VmInt>()),
Repr::Float => $f(array.unsafe_array::<f64>()),
Repr::String => $f(array.unsafe_array::<GcStr>()),
Repr::Array => $f(array.unsafe_array::<GcPtr<ValueArray>>()),
Repr::Unknown => $f(array.unsafe_array::<Value>()),
Repr::Userdata => $f(array.unsafe_array::<GcPtr<Box<Userdata>>>()),
Repr::Thread => $f(array.unsafe_array::<GcPtr<Thread>>()),
}
}
}
}
}
#[repr(C)]
pub struct ValueArray {
repr: Repr,
array: Array<()>,
}
impl fmt::Debug for ValueArray {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ValueArray")
.field("repr", &self.repr)
.field("array", on_array!(self, |x| x as &fmt::Debug))
.finish()
}
}
impl PartialEq for ValueArray {
fn eq(&self, other: &ValueArray) -> bool {
self.repr == other.repr && self.iter().zip(other.iter()).all(|(l, r)| l == r)
}
}
pub struct Iter<'a> {
array: &'a ValueArray,
index: usize,
}
impl<'a> Iterator for Iter<'a> {
type Item = Value;
fn next(&mut self) -> Option<Value> {
if self.index < self.array.len() {
let value = self.array.get(self.index);
self.index += 1;
Some(value)
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let i = self.array.len() - self.index;
(i, Some(i))
}
}
pub struct VariantIter<'a> {
array: &'a ValueArray,
index: usize,
}
impl<'a> Iterator for VariantIter<'a> {
type Item = Variants<'a>;
fn next(&mut self) -> Option<Self::Item> {
if self.index < self.array.len() {
let value = self.array.get(self.index);
self.index += 1;
Some(unsafe { Variants::with_root(value, self.array) })
} else {
None
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let i = self.array.len() - self.index;
(i, Some(i))
}
}
impl Traverseable for ValueArray {
fn traverse(&self, gc: &mut Gc) {
on_array!(*self, |array: &Array<_>| array.traverse(gc))
}
}
impl ValueArray {
pub fn get(&self, index: usize) -> Value {
unsafe {
match self.repr {
Repr::Byte => Value::Byte(self.unsafe_get(index)),
Repr::Int => Value::Int(self.unsafe_get(index)),
Repr::Float => Value::Float(self.unsafe_get(index)),
Repr::String => Value::String(self.unsafe_get(index)),
Repr::Array => Value::Array(self.unsafe_get(index)),
Repr::Unknown => self.unsafe_get(index),
Repr::Userdata => Value::Userdata(self.unsafe_get(index)),
Repr::Thread => Value::Thread(self.unsafe_get(index)),
}
}
}
pub fn is_empty(&self) -> bool {