Interpreter - Default environment includes native functions
This commit is contained in:
parent
24b57d35d0
commit
9d555acae0
1 changed files with 9 additions and 2 deletions
|
@ -2,7 +2,7 @@ use std::{cell::RefCell, collections::HashMap, rc::Rc};
|
||||||
|
|
||||||
use crate::{errors::InterpreterError, tokens::Token};
|
use crate::{errors::InterpreterError, tokens::Token};
|
||||||
|
|
||||||
use super::Value;
|
use super::{native_fn, CallableRef, Value};
|
||||||
|
|
||||||
/// A mutable reference to an environment.
|
/// A mutable reference to an environment.
|
||||||
pub type EnvironmentRef = Rc<RefCell<Environment>>;
|
pub type EnvironmentRef = Rc<RefCell<Environment>>;
|
||||||
|
@ -20,10 +20,11 @@ pub struct Environment {
|
||||||
impl Default for Environment {
|
impl Default for Environment {
|
||||||
/// Create the default global environment. This includes native functions.
|
/// Create the default global environment. This includes native functions.
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
let env = Self {
|
let mut env = Self {
|
||||||
enclosing: None,
|
enclosing: None,
|
||||||
values: HashMap::new(),
|
values: HashMap::new(),
|
||||||
};
|
};
|
||||||
|
env.add_default_fun("clock", native_fn::clock());
|
||||||
env
|
env
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -37,6 +38,12 @@ impl Environment {
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Add a default function to the environment.
|
||||||
|
fn add_default_fun(&mut self, name: &str, fun: CallableRef) {
|
||||||
|
let value = Some(Value::Callable(fun));
|
||||||
|
self.values.insert(name.to_owned(), value);
|
||||||
|
}
|
||||||
|
|
||||||
/// Define a new variable.
|
/// Define a new variable.
|
||||||
pub fn define(&mut self, name: &Token, value: Variable) -> Result<(), InterpreterError> {
|
pub fn define(&mut self, name: &Token, value: Variable) -> Result<(), InterpreterError> {
|
||||||
if self.values.contains_key(&name.lexeme as &str) {
|
if self.values.contains_key(&name.lexeme as &str) {
|
||||||
|
|
Loading…
Reference in a new issue