From fa0da150a5a481be3d1de448edb6f23c170da9a9 Mon Sep 17 00:00:00 2001 From: Cody Date: Fri, 14 Apr 2023 00:04:46 -0500 Subject: Improved VM. Started work on std --- crates/sloth_vm/src/sloth_std/stdio.rs | 51 ++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 crates/sloth_vm/src/sloth_std/stdio.rs (limited to 'crates/sloth_vm/src/sloth_std/stdio.rs') diff --git a/crates/sloth_vm/src/sloth_std/stdio.rs b/crates/sloth_vm/src/sloth_std/stdio.rs new file mode 100644 index 0000000..a743ad1 --- /dev/null +++ b/crates/sloth_vm/src/sloth_std/stdio.rs @@ -0,0 +1,51 @@ +use std::io::{stdin, BufRead}; + +use crate::native::{self, NativeFunction, NativeFunctionResult}; +use crate::value::{Object, ObjectType, Primitive}; +use crate::VM; + +fn write(vm: &mut VM, args: &[Primitive]) -> NativeFunctionResult { + let Some(Primitive::Object(ptr)) = args.get(0).cloned() else { + return Err(native::Error::InvalidArgument); + }; + + let object = vm + .objects() + .get(ptr as usize) + .ok_or(native::Error::InvalidArgument)?; + + let ObjectType::String(str) = &object.typ else { + return Err(native::Error::InvalidArgument); + }; + + println!("{str}"); + + Ok(Primitive::Empty) +} + +pub const WRITE_FUNCTION: NativeFunction = NativeFunction { + name: "write", + function: write, + arity: 1, + returns_value: false, +}; + +fn read(vm: &mut VM, _args: &[Primitive]) -> NativeFunctionResult { + let mut line = String::new(); + stdin() + .lock() + .read_line(&mut line) + .map_err(|it| native::Error::Unknown(it.to_string()))?; + + let object = Object::new(ObjectType::String(line)); + let ptr = vm.objects_mut().allocate(object); + + Ok(Primitive::Object(ptr as u32)) +} + +pub const READ_FUNCTION: NativeFunction = NativeFunction { + name: "read", + function: read, + arity: 0, + returns_value: true, +}; -- cgit v1.2.3