From e963868aa7cc92da1215930098da1763b70dfcb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emmanuel=20Beno=C3=AEt?= Date: Sun, 8 Jan 2023 11:42:08 +0100 Subject: [PATCH] Interpreter - Value helper methods to run code against instances --- src/interpreter/value.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/interpreter/value.rs b/src/interpreter/value.rs index 0680d1a..14572b1 100644 --- a/src/interpreter/value.rs +++ b/src/interpreter/value.rs @@ -58,6 +58,40 @@ impl Value { Object::Instance(_) => ferr(), } } + + /// Run some code against an instance value. If the value does not + /// contain an instance, an error function will be called instead. + pub fn with_instance(&self, fok: Fok, ferr: Ferr) -> Rt + where + Fok: FnOnce(&Instance) -> Rt, + Ferr: FnOnce() -> Rt, + { + let obj = match self { + Value::Object(obj_ref) => obj_ref.borrow(), + _ => return ferr(), + }; + match &*obj { + Object::Instance(inst) => fok(inst), + _ => ferr(), + } + } + + /// Run some code against a mutable instance value. If the value does + /// not contain an instance, an error function will be called instead. + pub fn with_instance_mut(&self, fok: Fok, ferr: Ferr) -> Rt + where + Fok: FnOnce(&mut Instance) -> Rt, + Ferr: FnOnce() -> Rt, + { + let mut obj = match self { + Value::Object(obj_ref) => obj_ref.borrow_mut(), + _ => return ferr(), + }; + match &mut *obj { + Object::Instance(inst) => fok(inst), + _ => ferr(), + } + } } impl PartialEq for Value {