about summary refs log tree commit diff
diff options
context:
space:
mode:
-rw-r--r--users/tazjin/rlox/src/interpreter.rs24
-rw-r--r--users/tazjin/rlox/src/interpreter/builtins.rs25
2 files changed, 49 insertions, 0 deletions
diff --git a/users/tazjin/rlox/src/interpreter.rs b/users/tazjin/rlox/src/interpreter.rs
index b59034ea970c..5e2eba02d460 100644
--- a/users/tazjin/rlox/src/interpreter.rs
+++ b/users/tazjin/rlox/src/interpreter.rs
@@ -5,8 +5,32 @@ use std::collections::HashMap;
 use std::rc::Rc;
 use std::sync::RwLock;
 
+// Implementation of built-in functions.
+mod builtins;
+
 // Tree-walk interpreter
 
+// Representation of all callables, including builtins & user-defined
+// functions.
+#[derive(Clone, Debug)]
+pub enum Callable {
+    Builtin(&'static dyn builtins::Builtin),
+}
+
+impl Callable {
+    fn arity(&self) -> usize {
+        match self {
+            Callable::Builtin(builtin) => builtin.arity(),
+        }
+    }
+
+    fn call(&self, args: Vec<Value>) -> Result<Value, Error> {
+        match self {
+            Callable::Builtin(builtin) => builtin.call(args),
+        }
+    }
+}
+
 // Representation of an in-language value.
 #[derive(Clone, Debug)]
 enum Value {
diff --git a/users/tazjin/rlox/src/interpreter/builtins.rs b/users/tazjin/rlox/src/interpreter/builtins.rs
new file mode 100644
index 000000000000..6ed9f07c3ffa
--- /dev/null
+++ b/users/tazjin/rlox/src/interpreter/builtins.rs
@@ -0,0 +1,25 @@
+use std::fmt;
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use crate::errors::Error;
+use crate::interpreter::Value;
+use crate::parser::Literal;
+
+pub trait Builtin: fmt::Debug {
+    fn arity(&self) -> usize;
+    fn call(&self, args: Vec<Value>) -> Result<Value, Error>;
+}
+
+// Builtin to return the current timestamp.
+#[derive(Debug)]
+pub struct Clock {}
+impl Builtin for Clock {
+    fn arity(&self) -> usize {
+        0
+    }
+
+    fn call(&self, _args: Vec<Value>) -> Result<Value, Error> {
+        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
+        Ok(Value::Literal(Literal::Number(now.as_secs() as f64)))
+    }
+}