2024-03-01 03:04:45 +00:00
|
|
|
//! Walks a Conlang AST, interpreting it as a program.
|
|
|
|
#![warn(clippy::all)]
|
2024-02-29 23:51:38 +00:00
|
|
|
#![feature(decl_macro)]
|
2023-10-26 19:48:44 +00:00
|
|
|
|
2024-04-25 00:34:29 +00:00
|
|
|
use cl_ast::Sym;
|
2024-01-05 23:48:19 +00:00
|
|
|
use env::Environment;
|
2023-10-30 04:47:00 +00:00
|
|
|
use error::{Error, IResult};
|
2024-01-21 11:32:18 +00:00
|
|
|
use interpret::Interpret;
|
2023-10-26 19:48:44 +00:00
|
|
|
use temp_type_impl::ConValue;
|
|
|
|
|
2023-10-30 04:47:00 +00:00
|
|
|
/// Callable types can be called from within a Conlang program
|
|
|
|
pub trait Callable: std::fmt::Debug {
|
2024-01-06 04:47:16 +00:00
|
|
|
/// Calls this [Callable] in the provided [Environment], with [ConValue] args \
|
2023-10-30 04:47:00 +00:00
|
|
|
/// The Callable is responsible for checking the argument count and validating types
|
2024-01-05 23:48:19 +00:00
|
|
|
fn call(&self, interpreter: &mut Environment, args: &[ConValue]) -> IResult<ConValue>;
|
2023-10-30 04:47:00 +00:00
|
|
|
/// Returns the common name of this identifier.
|
2024-04-25 00:34:29 +00:00
|
|
|
fn name(&self) -> Sym;
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// [BuiltIn]s are [Callable]s with bespoke definitions
|
2024-02-29 22:48:09 +00:00
|
|
|
pub trait BuiltIn: std::fmt::Debug + Callable {
|
|
|
|
fn description(&self) -> &str;
|
|
|
|
}
|
2023-10-30 04:47:00 +00:00
|
|
|
|
2023-10-26 19:48:44 +00:00
|
|
|
pub mod temp_type_impl {
|
2023-10-26 19:51:13 +00:00
|
|
|
//! Temporary implementations of Conlang values
|
2023-10-30 04:47:00 +00:00
|
|
|
//!
|
|
|
|
//! The most permanent fix is a temporary one.
|
2024-04-25 00:34:29 +00:00
|
|
|
use cl_ast::Sym;
|
|
|
|
|
2023-10-30 04:47:00 +00:00
|
|
|
use super::{
|
|
|
|
error::{Error, IResult},
|
|
|
|
function::Function,
|
2024-01-05 23:48:19 +00:00
|
|
|
BuiltIn, Callable, Environment,
|
2023-10-30 04:47:00 +00:00
|
|
|
};
|
2024-04-19 15:49:25 +00:00
|
|
|
use std::{ops::*, rc::Rc};
|
2024-02-26 21:32:49 +00:00
|
|
|
|
|
|
|
type Integer = isize;
|
|
|
|
|
2023-10-26 19:48:44 +00:00
|
|
|
/// A Conlang value
|
|
|
|
///
|
2023-10-30 04:47:00 +00:00
|
|
|
/// This is a hack to work around the fact that Conlang doesn't
|
|
|
|
/// have a functioning type system yet :(
|
2023-10-29 06:13:48 +00:00
|
|
|
#[derive(Clone, Debug, Default)]
|
2023-10-26 19:48:44 +00:00
|
|
|
pub enum ConValue {
|
|
|
|
/// The empty/unit `()` type
|
2023-10-29 06:13:48 +00:00
|
|
|
#[default]
|
2023-10-26 19:48:44 +00:00
|
|
|
Empty,
|
|
|
|
/// An integer
|
2024-02-26 21:32:49 +00:00
|
|
|
Int(Integer),
|
2023-10-26 19:48:44 +00:00
|
|
|
/// A boolean
|
|
|
|
Bool(bool),
|
|
|
|
/// A unicode character
|
|
|
|
Char(char),
|
|
|
|
/// A string
|
2024-04-25 00:34:29 +00:00
|
|
|
String(Sym),
|
2024-04-19 15:49:25 +00:00
|
|
|
/// A reference
|
|
|
|
Ref(Rc<ConValue>),
|
2024-01-21 11:32:18 +00:00
|
|
|
/// An Array
|
2024-04-19 15:49:25 +00:00
|
|
|
Array(Rc<[ConValue]>),
|
2023-10-30 04:47:00 +00:00
|
|
|
/// A tuple
|
2024-04-19 15:49:25 +00:00
|
|
|
Tuple(Rc<[ConValue]>),
|
2023-10-27 02:51:18 +00:00
|
|
|
/// An exclusive range
|
2024-02-26 21:32:49 +00:00
|
|
|
RangeExc(Integer, Integer),
|
2023-10-27 02:51:18 +00:00
|
|
|
/// An inclusive range
|
2024-02-26 21:32:49 +00:00
|
|
|
RangeInc(Integer, Integer),
|
2023-10-30 04:47:00 +00:00
|
|
|
/// A callable thing
|
|
|
|
Function(Function),
|
|
|
|
/// A built-in function
|
|
|
|
BuiltIn(&'static dyn BuiltIn),
|
2023-10-26 19:48:44 +00:00
|
|
|
}
|
|
|
|
impl ConValue {
|
|
|
|
/// Gets whether the current value is true or false
|
|
|
|
pub fn truthy(&self) -> IResult<bool> {
|
|
|
|
match self {
|
|
|
|
ConValue::Bool(v) => Ok(*v),
|
2023-10-30 04:47:00 +00:00
|
|
|
_ => Err(Error::TypeError)?,
|
2023-10-26 19:48:44 +00:00
|
|
|
}
|
|
|
|
}
|
2023-10-27 02:51:18 +00:00
|
|
|
pub fn range_exc(self, other: Self) -> IResult<Self> {
|
|
|
|
let (Self::Int(a), Self::Int(b)) = (self, other) else {
|
2023-10-30 04:47:00 +00:00
|
|
|
Err(Error::TypeError)?
|
2023-10-27 02:51:18 +00:00
|
|
|
};
|
|
|
|
Ok(Self::RangeExc(a, b.saturating_sub(1)))
|
|
|
|
}
|
|
|
|
pub fn range_inc(self, other: Self) -> IResult<Self> {
|
|
|
|
let (Self::Int(a), Self::Int(b)) = (self, other) else {
|
2023-10-30 04:47:00 +00:00
|
|
|
Err(Error::TypeError)?
|
2023-10-27 02:51:18 +00:00
|
|
|
};
|
|
|
|
Ok(Self::RangeInc(a, b))
|
|
|
|
}
|
2024-01-21 11:32:18 +00:00
|
|
|
pub fn index(&self, index: &Self) -> IResult<ConValue> {
|
|
|
|
let Self::Int(index) = index else {
|
|
|
|
Err(Error::TypeError)?
|
|
|
|
};
|
|
|
|
let Self::Array(arr) = self else {
|
|
|
|
Err(Error::TypeError)?
|
|
|
|
};
|
|
|
|
arr.get(*index as usize)
|
|
|
|
.cloned()
|
|
|
|
.ok_or(Error::OobIndex(*index as usize, arr.len()))
|
|
|
|
}
|
2023-10-26 19:48:44 +00:00
|
|
|
cmp! {
|
|
|
|
lt: false, <;
|
|
|
|
lt_eq: true, <=;
|
|
|
|
eq: true, ==;
|
|
|
|
neq: false, !=;
|
|
|
|
gt_eq: true, >=;
|
|
|
|
gt: false, >;
|
|
|
|
}
|
2023-10-29 06:13:48 +00:00
|
|
|
assign! {
|
|
|
|
add_assign: +;
|
|
|
|
bitand_assign: &;
|
|
|
|
bitor_assign: |;
|
|
|
|
bitxor_assign: ^;
|
|
|
|
div_assign: /;
|
|
|
|
mul_assign: *;
|
|
|
|
rem_assign: %;
|
|
|
|
shl_assign: <<;
|
|
|
|
shr_assign: >>;
|
|
|
|
sub_assign: -;
|
|
|
|
}
|
2023-10-26 19:48:44 +00:00
|
|
|
}
|
2023-10-30 04:47:00 +00:00
|
|
|
|
|
|
|
impl Callable for ConValue {
|
2024-04-25 00:34:29 +00:00
|
|
|
fn name(&self) -> Sym {
|
2023-10-30 04:47:00 +00:00
|
|
|
match self {
|
|
|
|
ConValue::Function(func) => func.name(),
|
|
|
|
ConValue::BuiltIn(func) => func.name(),
|
2024-04-25 00:34:29 +00:00
|
|
|
_ => "".into(),
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
|
|
|
}
|
2024-01-05 23:48:19 +00:00
|
|
|
fn call(&self, interpreter: &mut Environment, args: &[ConValue]) -> IResult<ConValue> {
|
2023-10-30 04:47:00 +00:00
|
|
|
match self {
|
|
|
|
Self::Function(func) => func.call(interpreter, args),
|
|
|
|
Self::BuiltIn(func) => func.call(interpreter, args),
|
|
|
|
_ => Err(Error::NotCallable(self.clone())),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-10-26 19:48:44 +00:00
|
|
|
/// Templates comparison functions for [ConValue]
|
|
|
|
macro cmp ($($fn:ident: $empty:literal, $op:tt);*$(;)?) {$(
|
|
|
|
/// TODO: Remove when functions are implemented:
|
|
|
|
/// Desugar into function calls
|
|
|
|
pub fn $fn(&self, other: &Self) -> IResult<Self> {
|
|
|
|
match (self, other) {
|
|
|
|
(Self::Empty, Self::Empty) => Ok(Self::Bool($empty)),
|
|
|
|
(Self::Int(a), Self::Int(b)) => Ok(Self::Bool(a $op b)),
|
|
|
|
(Self::Bool(a), Self::Bool(b)) => Ok(Self::Bool(a $op b)),
|
|
|
|
(Self::Char(a), Self::Char(b)) => Ok(Self::Bool(a $op b)),
|
2024-04-25 00:34:29 +00:00
|
|
|
(Self::String(a), Self::String(b)) => Ok(Self::Bool(a.get() $op b.get())),
|
2023-10-30 04:47:00 +00:00
|
|
|
_ => Err(Error::TypeError)
|
2023-10-26 19:48:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
)*}
|
2023-10-29 06:13:48 +00:00
|
|
|
macro assign($( $fn: ident: $op: tt );*$(;)?) {$(
|
|
|
|
pub fn $fn(&mut self, other: Self) -> IResult<()> {
|
|
|
|
*self = (std::mem::take(self) $op other)?;
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
)*}
|
2023-10-26 19:48:44 +00:00
|
|
|
/// Implements [From] for an enum with 1-tuple variants
|
|
|
|
macro from ($($T:ty => $v:expr),*$(,)?) {
|
|
|
|
$(impl From<$T> for ConValue {
|
|
|
|
fn from(value: $T) -> Self { $v(value.into()) }
|
|
|
|
})*
|
|
|
|
}
|
2024-04-25 00:34:29 +00:00
|
|
|
impl From<&Sym> for ConValue {
|
|
|
|
fn from(value: &Sym) -> Self {
|
|
|
|
ConValue::String(*value)
|
|
|
|
}
|
|
|
|
}
|
2023-10-26 19:48:44 +00:00
|
|
|
from! {
|
2024-02-26 21:32:49 +00:00
|
|
|
Integer => ConValue::Int,
|
2023-10-26 19:48:44 +00:00
|
|
|
bool => ConValue::Bool,
|
|
|
|
char => ConValue::Char,
|
2024-04-25 00:34:29 +00:00
|
|
|
Sym => ConValue::String,
|
2023-10-26 19:48:44 +00:00
|
|
|
&str => ConValue::String,
|
|
|
|
String => ConValue::String,
|
2024-04-19 15:49:25 +00:00
|
|
|
Rc<str> => ConValue::String,
|
2023-10-30 04:47:00 +00:00
|
|
|
Function => ConValue::Function,
|
|
|
|
Vec<ConValue> => ConValue::Tuple,
|
2024-02-29 22:48:09 +00:00
|
|
|
&'static dyn BuiltIn => ConValue::BuiltIn,
|
2023-10-26 19:48:44 +00:00
|
|
|
}
|
|
|
|
impl From<()> for ConValue {
|
|
|
|
fn from(_: ()) -> Self {
|
|
|
|
Self::Empty
|
|
|
|
}
|
|
|
|
}
|
2023-10-30 04:47:00 +00:00
|
|
|
impl From<&[ConValue]> for ConValue {
|
|
|
|
fn from(value: &[ConValue]) -> Self {
|
|
|
|
match value.len() {
|
|
|
|
0 => Self::Empty,
|
|
|
|
1 => value[0].clone(),
|
|
|
|
_ => Self::Tuple(value.into()),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-10-26 19:48:44 +00:00
|
|
|
|
|
|
|
/// Implements binary [std::ops] traits for [ConValue]
|
|
|
|
///
|
|
|
|
/// TODO: Desugar operators into function calls
|
|
|
|
macro ops($($trait:ty: $fn:ident = [$($match:tt)*])*) {
|
|
|
|
$(impl $trait for ConValue {
|
|
|
|
type Output = IResult<Self>;
|
|
|
|
/// TODO: Desugar operators into function calls
|
|
|
|
fn $fn(self, rhs: Self) -> Self::Output {Ok(match (self, rhs) {$($match)*})}
|
|
|
|
})*
|
|
|
|
}
|
|
|
|
ops! {
|
|
|
|
Add: add = [
|
|
|
|
(ConValue::Empty, ConValue::Empty) => ConValue::Empty,
|
|
|
|
(ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a + b),
|
2024-04-25 00:34:29 +00:00
|
|
|
(ConValue::String(a), ConValue::String(b)) => (a.to_string() + &b.to_string()).into(),
|
2023-10-30 04:47:00 +00:00
|
|
|
_ => Err(Error::TypeError)?
|
2023-10-26 19:48:44 +00:00
|
|
|
]
|
|
|
|
BitAnd: bitand = [
|
|
|
|
(ConValue::Empty, ConValue::Empty) => ConValue::Empty,
|
|
|
|
(ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a & b),
|
|
|
|
(ConValue::Bool(a), ConValue::Bool(b)) => ConValue::Bool(a & b),
|
2023-10-30 04:47:00 +00:00
|
|
|
_ => Err(Error::TypeError)?
|
2023-10-26 19:48:44 +00:00
|
|
|
]
|
|
|
|
BitOr: bitor = [
|
|
|
|
(ConValue::Empty, ConValue::Empty) => ConValue::Empty,
|
|
|
|
(ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a | b),
|
|
|
|
(ConValue::Bool(a), ConValue::Bool(b)) => ConValue::Bool(a | b),
|
2023-10-30 04:47:00 +00:00
|
|
|
_ => Err(Error::TypeError)?
|
2023-10-26 19:48:44 +00:00
|
|
|
]
|
|
|
|
BitXor: bitxor = [
|
|
|
|
(ConValue::Empty, ConValue::Empty) => ConValue::Empty,
|
|
|
|
(ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a ^ b),
|
|
|
|
(ConValue::Bool(a), ConValue::Bool(b)) => ConValue::Bool(a ^ b),
|
2023-10-30 04:47:00 +00:00
|
|
|
_ => Err(Error::TypeError)?
|
2023-10-26 19:48:44 +00:00
|
|
|
]
|
|
|
|
Div: div = [
|
|
|
|
(ConValue::Empty, ConValue::Empty) => ConValue::Empty,
|
|
|
|
(ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a / b),
|
2023-10-30 04:47:00 +00:00
|
|
|
_ => Err(Error::TypeError)?
|
2023-10-26 19:48:44 +00:00
|
|
|
]
|
|
|
|
Mul: mul = [
|
|
|
|
(ConValue::Empty, ConValue::Empty) => ConValue::Empty,
|
|
|
|
(ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a * b),
|
2023-10-30 04:47:00 +00:00
|
|
|
_ => Err(Error::TypeError)?
|
2023-10-26 19:48:44 +00:00
|
|
|
]
|
|
|
|
Rem: rem = [
|
|
|
|
(ConValue::Empty, ConValue::Empty) => ConValue::Empty,
|
|
|
|
(ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a % b),
|
2023-10-30 04:47:00 +00:00
|
|
|
_ => Err(Error::TypeError)?
|
2023-10-26 19:48:44 +00:00
|
|
|
]
|
|
|
|
Shl: shl = [
|
|
|
|
(ConValue::Empty, ConValue::Empty) => ConValue::Empty,
|
|
|
|
(ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a << b),
|
2023-10-30 04:47:00 +00:00
|
|
|
_ => Err(Error::TypeError)?
|
2023-10-26 19:48:44 +00:00
|
|
|
]
|
|
|
|
Shr: shr = [
|
|
|
|
(ConValue::Empty, ConValue::Empty) => ConValue::Empty,
|
|
|
|
(ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a >> b),
|
2023-10-30 04:47:00 +00:00
|
|
|
_ => Err(Error::TypeError)?
|
2023-10-26 19:48:44 +00:00
|
|
|
]
|
|
|
|
Sub: sub = [
|
|
|
|
(ConValue::Empty, ConValue::Empty) => ConValue::Empty,
|
|
|
|
(ConValue::Int(a), ConValue::Int(b)) => ConValue::Int(a - b),
|
2023-10-30 04:47:00 +00:00
|
|
|
_ => Err(Error::TypeError)?
|
2023-10-26 19:48:44 +00:00
|
|
|
]
|
|
|
|
}
|
|
|
|
impl std::fmt::Display for ConValue {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
match self {
|
|
|
|
ConValue::Empty => "Empty".fmt(f),
|
|
|
|
ConValue::Int(v) => v.fmt(f),
|
|
|
|
ConValue::Bool(v) => v.fmt(f),
|
2023-10-30 04:47:00 +00:00
|
|
|
ConValue::Char(v) => v.fmt(f),
|
|
|
|
ConValue::String(v) => v.fmt(f),
|
2024-04-19 15:49:25 +00:00
|
|
|
ConValue::Ref(v) => write!(f, "&{v}"),
|
2024-01-21 11:32:18 +00:00
|
|
|
ConValue::Array(array) => {
|
|
|
|
'['.fmt(f)?;
|
|
|
|
for (idx, element) in array.iter().enumerate() {
|
|
|
|
if idx > 0 {
|
|
|
|
", ".fmt(f)?
|
|
|
|
}
|
|
|
|
element.fmt(f)?
|
|
|
|
}
|
|
|
|
']'.fmt(f)
|
|
|
|
}
|
2023-10-27 02:51:18 +00:00
|
|
|
ConValue::RangeExc(a, b) => write!(f, "{a}..{}", b + 1),
|
|
|
|
ConValue::RangeInc(a, b) => write!(f, "{a}..={b}"),
|
2023-10-30 04:47:00 +00:00
|
|
|
ConValue::Tuple(tuple) => {
|
|
|
|
'('.fmt(f)?;
|
|
|
|
for (idx, element) in tuple.iter().enumerate() {
|
|
|
|
if idx > 0 {
|
|
|
|
", ".fmt(f)?
|
|
|
|
}
|
|
|
|
element.fmt(f)?
|
|
|
|
}
|
|
|
|
')'.fmt(f)
|
|
|
|
}
|
|
|
|
ConValue::Function(func) => {
|
2024-04-19 01:47:28 +00:00
|
|
|
write!(f, "{}", func.decl())
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
|
|
|
ConValue::BuiltIn(func) => {
|
2024-02-29 22:48:09 +00:00
|
|
|
write!(f, "{}", func.description())
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
2023-10-26 19:48:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-29 23:51:38 +00:00
|
|
|
pub mod interpret;
|
2023-10-30 04:47:00 +00:00
|
|
|
|
|
|
|
pub mod function {
|
|
|
|
//! Represents a block of code which lives inside the Interpreter
|
2024-04-19 15:49:25 +00:00
|
|
|
|
2024-01-21 11:32:18 +00:00
|
|
|
use super::{Callable, ConValue, Environment, Error, IResult, Interpret};
|
2024-04-25 00:34:29 +00:00
|
|
|
use cl_ast::{Function as FnDecl, Identifier, Param, Sym};
|
2024-04-19 15:49:25 +00:00
|
|
|
use std::rc::Rc;
|
2023-10-30 04:47:00 +00:00
|
|
|
/// Represents a block of code which persists inside the Interpreter
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
pub struct Function {
|
|
|
|
/// Stores the contents of the function declaration
|
2024-04-19 15:49:25 +00:00
|
|
|
decl: Rc<FnDecl>,
|
2024-01-10 04:42:15 +00:00
|
|
|
// /// Stores the enclosing scope of the function
|
|
|
|
// env: Box<Environment>,
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Function {
|
2024-01-10 04:42:15 +00:00
|
|
|
pub fn new(decl: &FnDecl) -> Self {
|
|
|
|
Self { decl: decl.clone().into() }
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
2024-03-01 08:47:07 +00:00
|
|
|
pub fn decl(&self) -> &FnDecl {
|
|
|
|
&self.decl
|
|
|
|
}
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Callable for Function {
|
2024-04-25 00:34:29 +00:00
|
|
|
fn name(&self) -> Sym {
|
|
|
|
let FnDecl { name: Identifier(name), .. } = *self.decl;
|
2024-01-21 11:32:18 +00:00
|
|
|
name
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
2024-01-10 04:42:15 +00:00
|
|
|
fn call(&self, env: &mut Environment, args: &[ConValue]) -> IResult<ConValue> {
|
2024-04-19 15:49:25 +00:00
|
|
|
let FnDecl { name: Identifier(name), bind, body, sign: _ } = &*self.decl;
|
2023-10-30 04:47:00 +00:00
|
|
|
// Check arg mapping
|
2024-04-19 15:49:25 +00:00
|
|
|
if args.len() != bind.len() {
|
|
|
|
return Err(Error::ArgNumber { want: bind.len(), got: args.len() });
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
2024-01-21 11:32:18 +00:00
|
|
|
let Some(body) = body else {
|
2024-04-25 00:34:29 +00:00
|
|
|
return Err(Error::NotDefined(*name));
|
2024-01-21 11:32:18 +00:00
|
|
|
};
|
|
|
|
// TODO: completely refactor data storage
|
2024-01-06 04:47:16 +00:00
|
|
|
let mut frame = env.frame("fn args");
|
2024-04-19 15:49:25 +00:00
|
|
|
for (Param { mutability: _, name: Identifier(name) }, value) in bind.iter().zip(args) {
|
2024-04-25 00:34:29 +00:00
|
|
|
frame.insert(*name, Some(value.clone()));
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
2024-01-21 11:32:18 +00:00
|
|
|
match body.interpret(&mut frame) {
|
2024-01-05 23:48:19 +00:00
|
|
|
Err(Error::Return(value)) => Ok(value),
|
|
|
|
Err(Error::Break(value)) => Err(Error::BadBreak(value)),
|
|
|
|
result => result,
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-29 22:48:09 +00:00
|
|
|
pub mod builtin;
|
2023-10-30 04:47:00 +00:00
|
|
|
|
2024-01-05 23:48:19 +00:00
|
|
|
pub mod env {
|
2023-10-29 06:13:48 +00:00
|
|
|
//! Lexical and non-lexical scoping for variables
|
|
|
|
use super::{
|
2024-02-29 22:48:09 +00:00
|
|
|
builtin::{BINARY, MISC, RANGE, UNARY},
|
2023-10-30 04:47:00 +00:00
|
|
|
error::{Error, IResult},
|
|
|
|
function::Function,
|
2023-10-29 06:13:48 +00:00
|
|
|
temp_type_impl::ConValue,
|
2024-02-29 22:48:09 +00:00
|
|
|
BuiltIn, Callable, Interpret,
|
2024-01-05 23:48:19 +00:00
|
|
|
};
|
2024-04-25 00:34:29 +00:00
|
|
|
use cl_ast::{Function as FnDecl, Identifier, Sym};
|
2024-01-05 23:48:19 +00:00
|
|
|
use std::{
|
|
|
|
collections::HashMap,
|
|
|
|
fmt::Display,
|
|
|
|
ops::{Deref, DerefMut},
|
2023-10-29 06:13:48 +00:00
|
|
|
};
|
|
|
|
|
2024-04-25 00:34:29 +00:00
|
|
|
type StackFrame = HashMap<Sym, Option<ConValue>>;
|
2024-04-19 15:49:25 +00:00
|
|
|
|
2023-10-29 06:13:48 +00:00
|
|
|
/// Implements a nested lexical scope
|
2024-01-05 23:48:19 +00:00
|
|
|
#[derive(Clone, Debug)]
|
2023-10-29 06:13:48 +00:00
|
|
|
pub struct Environment {
|
2024-04-19 15:49:25 +00:00
|
|
|
frames: Vec<(StackFrame, &'static str)>,
|
2023-10-29 06:13:48 +00:00
|
|
|
}
|
|
|
|
|
2024-01-04 08:18:09 +00:00
|
|
|
impl Display for Environment {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
2024-01-06 04:47:16 +00:00
|
|
|
for (frame, name) in self.frames.iter().rev() {
|
|
|
|
writeln!(f, "--- {name} ---")?;
|
|
|
|
for (var, val) in frame {
|
2024-02-29 22:48:09 +00:00
|
|
|
write!(f, "{var}: ")?;
|
2024-01-06 04:47:16 +00:00
|
|
|
match val {
|
2024-02-29 22:48:09 +00:00
|
|
|
Some(value) => writeln!(f, "\t{value}"),
|
2024-01-06 04:47:16 +00:00
|
|
|
None => writeln!(f, "<undefined>"),
|
|
|
|
}?
|
|
|
|
}
|
2024-01-04 08:18:09 +00:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|
2024-01-05 23:48:19 +00:00
|
|
|
impl Default for Environment {
|
|
|
|
fn default() -> Self {
|
2024-02-29 22:48:09 +00:00
|
|
|
Self {
|
|
|
|
frames: vec![
|
|
|
|
(to_hashmap(RANGE), "range ops"),
|
|
|
|
(to_hashmap(UNARY), "unary ops"),
|
|
|
|
(to_hashmap(BINARY), "binary ops"),
|
|
|
|
(to_hashmap(MISC), "builtins"),
|
|
|
|
(HashMap::new(), "globals"),
|
|
|
|
],
|
2024-01-05 23:48:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-04-25 00:34:29 +00:00
|
|
|
fn to_hashmap(from: &[&'static dyn BuiltIn]) -> HashMap<Sym, Option<ConValue>> {
|
|
|
|
from.iter().map(|&v| (v.name(), Some(v.into()))).collect()
|
2024-02-29 22:48:09 +00:00
|
|
|
}
|
2024-01-04 08:18:09 +00:00
|
|
|
|
2023-10-29 06:13:48 +00:00
|
|
|
impl Environment {
|
2023-10-30 04:47:00 +00:00
|
|
|
pub fn new() -> Self {
|
2024-01-05 23:48:19 +00:00
|
|
|
Self::default()
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
2024-01-06 04:47:16 +00:00
|
|
|
/// Creates an [Environment] with no [builtins](super::builtin)
|
|
|
|
pub fn no_builtins(name: &'static str) -> Self {
|
|
|
|
Self { frames: vec![(Default::default(), name)] }
|
2024-01-05 23:48:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn eval(&mut self, node: &impl Interpret) -> IResult<ConValue> {
|
|
|
|
node.interpret(self)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Calls a function inside the interpreter's scope,
|
|
|
|
/// and returns the result
|
2024-04-25 00:34:29 +00:00
|
|
|
pub fn call(&mut self, name: Sym, args: &[ConValue]) -> IResult<ConValue> {
|
2024-01-06 04:47:16 +00:00
|
|
|
// FIXME: Clone to satisfy the borrow checker
|
|
|
|
let function = self.get(name)?.clone();
|
2024-01-05 23:48:19 +00:00
|
|
|
function.call(self, args)
|
|
|
|
}
|
|
|
|
/// Enters a nested scope, returning a [`Frame`] stack-guard.
|
|
|
|
///
|
|
|
|
/// [`Frame`] implements Deref/DerefMut for [`Environment`].
|
|
|
|
pub fn frame(&mut self, name: &'static str) -> Frame {
|
|
|
|
Frame::new(self, name)
|
2023-10-29 06:13:48 +00:00
|
|
|
}
|
2024-01-10 04:39:58 +00:00
|
|
|
/// Resolves a variable mutably.
|
2023-10-30 04:47:00 +00:00
|
|
|
///
|
2024-01-10 04:39:58 +00:00
|
|
|
/// Returns a mutable reference to the variable's record, if it exists.
|
2024-04-25 00:34:29 +00:00
|
|
|
pub fn get_mut(&mut self, id: Sym) -> IResult<&mut Option<ConValue>> {
|
2024-01-10 04:39:58 +00:00
|
|
|
for (frame, _) in self.frames.iter_mut().rev() {
|
2024-04-25 00:34:29 +00:00
|
|
|
if let Some(var) = frame.get_mut(&id) {
|
2024-01-10 04:39:58 +00:00
|
|
|
return Ok(var);
|
2024-01-06 04:47:16 +00:00
|
|
|
}
|
2023-10-29 06:13:48 +00:00
|
|
|
}
|
2024-04-25 00:34:29 +00:00
|
|
|
Err(Error::NotDefined(id))
|
2023-10-29 06:13:48 +00:00
|
|
|
}
|
2024-01-10 04:39:58 +00:00
|
|
|
/// Resolves a variable immutably.
|
|
|
|
///
|
|
|
|
/// Returns a reference to the variable's contents, if it is defined and initialized.
|
2024-04-25 00:34:29 +00:00
|
|
|
pub fn get(&self, id: Sym) -> IResult<ConValue> {
|
2024-01-10 04:39:58 +00:00
|
|
|
for (frame, _) in self.frames.iter().rev() {
|
2024-04-25 00:34:29 +00:00
|
|
|
match frame.get(&id) {
|
2024-04-19 15:49:25 +00:00
|
|
|
Some(Some(var)) => return Ok(var.clone()),
|
2024-04-25 00:34:29 +00:00
|
|
|
Some(None) => return Err(Error::NotInitialized(id)),
|
2024-01-06 04:47:16 +00:00
|
|
|
_ => (),
|
|
|
|
}
|
2023-10-29 06:13:48 +00:00
|
|
|
}
|
2024-04-25 00:34:29 +00:00
|
|
|
Err(Error::NotDefined(id))
|
2023-10-29 06:13:48 +00:00
|
|
|
}
|
2024-01-06 04:47:16 +00:00
|
|
|
/// Inserts a new [ConValue] into this [Environment]
|
2024-04-25 00:34:29 +00:00
|
|
|
pub fn insert(&mut self, id: Sym, value: Option<ConValue>) {
|
2024-01-06 04:47:16 +00:00
|
|
|
if let Some((frame, _)) = self.frames.last_mut() {
|
2024-04-25 00:34:29 +00:00
|
|
|
frame.insert(id, value);
|
2024-01-06 04:47:16 +00:00
|
|
|
}
|
2023-10-30 04:47:00 +00:00
|
|
|
}
|
|
|
|
/// A convenience function for registering a [FnDecl] as a [Function]
|
|
|
|
pub fn insert_fn(&mut self, decl: &FnDecl) {
|
2024-01-21 11:32:18 +00:00
|
|
|
let FnDecl { name: Identifier(name), .. } = decl;
|
2024-04-25 00:34:29 +00:00
|
|
|
let (name, function) = (name, Some(Function::new(decl).into()));
|
2024-01-06 04:47:16 +00:00
|
|
|
if let Some((frame, _)) = self.frames.last_mut() {
|
2024-04-25 00:34:29 +00:00
|
|
|
frame.insert(*name, function);
|
2024-01-06 04:47:16 +00:00
|
|
|
}
|
2023-10-29 06:13:48 +00:00
|
|
|
}
|
|
|
|
}
|
2024-01-05 23:48:19 +00:00
|
|
|
|
|
|
|
/// Functions which aid in the implementation of [`Frame`]
|
|
|
|
impl Environment {
|
|
|
|
/// Enters a scope, creating a new namespace for variables
|
|
|
|
fn enter(&mut self, name: &'static str) -> &mut Self {
|
2024-01-06 04:47:16 +00:00
|
|
|
self.frames.push((Default::default(), name));
|
2024-01-05 23:48:19 +00:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Exits the scope, destroying all local variables and
|
|
|
|
/// returning the outer scope, if there is one
|
|
|
|
fn exit(&mut self) -> &mut Self {
|
2024-01-06 04:47:16 +00:00
|
|
|
if self.frames.len() > 2 {
|
|
|
|
self.frames.pop();
|
2024-01-05 23:48:19 +00:00
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Represents a stack frame
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct Frame<'scope> {
|
|
|
|
scope: &'scope mut Environment,
|
|
|
|
}
|
|
|
|
impl<'scope> Frame<'scope> {
|
|
|
|
fn new(scope: &'scope mut Environment, name: &'static str) -> Self {
|
|
|
|
Self { scope: scope.enter(name) }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
impl<'scope> Deref for Frame<'scope> {
|
|
|
|
type Target = Environment;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
self.scope
|
|
|
|
}
|
|
|
|
}
|
|
|
|
impl<'scope> DerefMut for Frame<'scope> {
|
|
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
|
|
self.scope
|
|
|
|
}
|
|
|
|
}
|
|
|
|
impl<'scope> Drop for Frame<'scope> {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
self.scope.exit();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-26 19:48:44 +00:00
|
|
|
pub mod error {
|
2024-01-06 04:47:16 +00:00
|
|
|
//! The [Error] type represents any error thrown by the [Environment](super::Environment)
|
2023-10-29 06:13:48 +00:00
|
|
|
|
2024-04-25 00:34:29 +00:00
|
|
|
use cl_ast::Sym;
|
|
|
|
|
2023-10-26 19:48:44 +00:00
|
|
|
use super::temp_type_impl::ConValue;
|
|
|
|
|
|
|
|
pub type IResult<T> = Result<T, Error>;
|
|
|
|
|
2024-01-06 04:47:16 +00:00
|
|
|
/// Represents any error thrown by the [Environment](super::Environment)
|
2023-10-26 19:48:44 +00:00
|
|
|
#[derive(Clone, Debug)]
|
2023-10-30 04:47:00 +00:00
|
|
|
pub enum Error {
|
2023-10-26 19:48:44 +00:00
|
|
|
/// Propagate a Return value
|
|
|
|
Return(ConValue),
|
|
|
|
/// Propagate a Break value
|
|
|
|
Break(ConValue),
|
2023-10-30 04:47:00 +00:00
|
|
|
/// Break propagated across function bounds
|
|
|
|
BadBreak(ConValue),
|
2023-10-26 19:48:44 +00:00
|
|
|
/// Continue to the next iteration of a loop
|
|
|
|
Continue,
|
|
|
|
/// Underflowed the stack
|
|
|
|
StackUnderflow,
|
2023-10-29 06:13:48 +00:00
|
|
|
/// Exited the last scope
|
|
|
|
ScopeExit,
|
2023-10-26 19:48:44 +00:00
|
|
|
/// Type incompatibility
|
|
|
|
// TODO: store the type information in this error
|
|
|
|
TypeError,
|
2023-10-27 02:51:18 +00:00
|
|
|
/// In clause of For loop didn't yield a Range
|
|
|
|
NotIterable,
|
2024-04-13 07:54:02 +00:00
|
|
|
/// A value could not be indexed
|
|
|
|
NotIndexable,
|
2024-01-21 11:32:18 +00:00
|
|
|
/// An array index went out of bounds
|
|
|
|
OobIndex(usize, usize),
|
2024-04-13 07:54:02 +00:00
|
|
|
/// An expression is not assignable
|
|
|
|
NotAssignable,
|
2023-10-29 06:13:48 +00:00
|
|
|
/// A name was not defined in scope before being used
|
2024-04-25 00:34:29 +00:00
|
|
|
NotDefined(Sym),
|
2023-10-29 06:13:48 +00:00
|
|
|
/// A name was defined but not initialized
|
2024-04-25 00:34:29 +00:00
|
|
|
NotInitialized(Sym),
|
2023-10-30 04:47:00 +00:00
|
|
|
/// A value was called, but is not callable
|
|
|
|
NotCallable(ConValue),
|
|
|
|
/// A function was called with the wrong number of arguments
|
2024-02-29 22:48:09 +00:00
|
|
|
ArgNumber {
|
|
|
|
want: usize,
|
|
|
|
got: usize,
|
|
|
|
},
|
|
|
|
NullPointer,
|
2023-10-26 19:48:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl std::error::Error for Error {}
|
|
|
|
impl std::fmt::Display for Error {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
match self {
|
2023-10-30 04:47:00 +00:00
|
|
|
Error::Return(value) => write!(f, "return {value}"),
|
|
|
|
Error::Break(value) => write!(f, "break {value}"),
|
|
|
|
Error::BadBreak(value) => write!(f, "rogue break: {value}"),
|
|
|
|
Error::Continue => "continue".fmt(f),
|
|
|
|
Error::StackUnderflow => "Stack underflow".fmt(f),
|
|
|
|
Error::ScopeExit => "Exited the last scope. This is a logic bug.".fmt(f),
|
|
|
|
Error::TypeError => "Incompatible types".fmt(f),
|
|
|
|
Error::NotIterable => "`in` clause of `for` loop did not yield an iterable".fmt(f),
|
2024-04-13 07:54:02 +00:00
|
|
|
Error::NotIndexable => {
|
|
|
|
write!(f, "expression cannot be indexed")
|
2024-01-21 11:32:18 +00:00
|
|
|
}
|
|
|
|
Error::OobIndex(idx, len) => {
|
|
|
|
write!(f, "Index out of bounds: index was {idx}. but len is {len}")
|
|
|
|
}
|
2024-04-13 07:54:02 +00:00
|
|
|
Error::NotAssignable => {
|
|
|
|
write!(f, "expression is not assignable")
|
2024-01-21 11:32:18 +00:00
|
|
|
}
|
2023-10-30 04:47:00 +00:00
|
|
|
Error::NotDefined(value) => {
|
|
|
|
write!(f, "{value} not bound. Did you mean `let {value};`?")
|
|
|
|
}
|
|
|
|
Error::NotInitialized(value) => {
|
|
|
|
write!(f, "{value} bound, but not initialized")
|
|
|
|
}
|
|
|
|
Error::NotCallable(value) => {
|
2024-01-21 11:32:18 +00:00
|
|
|
write!(f, "{value} is not callable.")
|
2023-10-29 06:13:48 +00:00
|
|
|
}
|
2023-10-30 04:47:00 +00:00
|
|
|
Error::ArgNumber { want, got } => {
|
2024-03-01 08:47:07 +00:00
|
|
|
write!(
|
|
|
|
f,
|
|
|
|
"Expected {want} argument{}, got {got}",
|
|
|
|
if *want == 1 { "" } else { "s" }
|
|
|
|
)
|
2023-10-29 06:13:48 +00:00
|
|
|
}
|
2024-02-29 22:48:09 +00:00
|
|
|
Error::NullPointer => {
|
|
|
|
write!(f, "Attempted to dereference a null pointer?")
|
|
|
|
}
|
2023-10-26 19:48:44 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2024-01-10 05:52:48 +00:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests;
|