Skip to content

Commit

Permalink
Merge #142
Browse files Browse the repository at this point in the history
142: Add the 'fields' primitive. r=ptersilie a=ltratt

This returns a class's fields. However, SOM's semantics on this are currently unclear (see SOM-st/SOM#40). Although we allow users to mutate the 'methods' array, this is less sensible with fields in my opinion, since it would turn SOM from a statically into a dynamically scoped language. Thus, each time you call 'fields' you get a fresh array back such that any mutations made are ignored (see the `mutate_fields` test).

Co-authored-by: Laurence Tratt <[email protected]>
  • Loading branch information
bors[bot] and ltratt authored Jun 8, 2020
2 parents be0bfc0 + 2a9d5c9 commit 07bdc9f
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 2 deletions.
19 changes: 19 additions & 0 deletions lang_tests/instance_fields.som
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"
VM:
status: success
stdout:
instance of Array
true
true
"

instance_fields = (
| x y |
run = (
| fds |
fds := instance_fields fields.
fds println.
(fds contains: #x) println.
(fds contains: #y) println.
)
)
29 changes: 29 additions & 0 deletions lang_tests/mutate_fields.som
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"
VM:
status: success
stdout:
true
true
true
true
false
"

mutate_fields = (
| x y |
run = (
| fds |
fds := mutate_fields fields.
(fds contains: #x) println.
(fds contains: #y) println.
fds at: 1 put: #z.
fds := mutate_fields fields.
(fds contains: #x) println.
(fds contains: #y) println.
(fds contains: #z) println.
)

find: sym = (
method_holder methods do: [:e | ((e signature) == sym) ifTrue: [ ^e ]].
)
)
6 changes: 5 additions & 1 deletion src/lib/vm/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -717,7 +717,11 @@ impl VM {
))
}
}
Primitive::Fields => todo!(),
Primitive::Fields => {
let fields = stry!(rcv.downcast::<Class>(self)).fields(self);
self.stack.push(fields);
SendReturn::Val
}
Primitive::FromString => todo!(),
Primitive::FullGC => todo!(),
Primitive::Global => {
Expand Down
11 changes: 10 additions & 1 deletion src/lib/vm/objects/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use rboehm::Gc;
use crate::vm::{
core::VM,
error::{VMError, VMErrorKind},
objects::{Array, Method, MethodsArray, Obj, ObjType, StaticObjType, String_},
objects::{Array, Method, MethodsArray, NormalArray, Obj, ObjType, StaticObjType, String_},
val::{NotUnboxable, Val, ValKind},
};

Expand Down Expand Up @@ -164,6 +164,15 @@ impl Class {
}
}

pub fn fields(&self, vm: &mut VM) -> Val {
let field_strs = self
.inst_vars_map
.keys()
.map(|k| String_::new_sym(vm, k.clone()))
.collect();
NormalArray::from_vec(vm, field_strs)
}

pub fn methods(&self, _: &VM) -> Val {
self.methods
}
Expand Down

0 comments on commit 07bdc9f

Please sign in to comment.