Files
not-python/runtime/src/obj/mod.rs
Alek Ratzloff 8e2cbb10a4 General changes across the runtime crate in support of compile module
* Compile module is able to compile bytecode (or so it seems...)
* Runtime crate has had some new stuff added to it, mostly with objects
  and vtables. Still not 100% on the object method function call story,
  but I guess it'll be tackled when we get there.

Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
2020-09-14 14:09:29 -07:00

131 lines
2.3 KiB
Rust

#[macro_use]
mod macros;
pub mod attrs;
pub mod fun;
pub mod int;
pub mod intern;
pub mod names;
pub mod str;
pub mod sym;
#[cfg(test)]
mod test;
pub mod ty;
pub mod prelude {
pub use crate::obj::{attrs::*, fun::*, int::*, intern::*, str::*, sym::*, ty::*, Obj, ObjRef};
}
use shredder::{Gc, Scan};
use std::{
marker::Unsize,
ops::{CoerceUnsized, Deref, DerefMut},
sync::RwLock,
};
use attrs::*;
use sym::Sym;
//
// trait Obj
//
pub trait Obj: Scan + std::fmt::Debug {
fn vtable(&self) -> &Vtable;
fn attrs(&self) -> &Attrs;
fn attrs_mut(&mut self) -> Option<&mut Attrs>;
fn get_attr(&self, sym: &Sym) -> Option<ObjRef> {
self.attrs()
.get(&sym)
.cloned()
.or_else(|| {
let vtable = self.vtable().get();
vtable.get(&sym).cloned()
})
}
fn set_attr(&mut self, sym: Sym, value: ObjRef) -> Option<ObjRef> {
self.attrs_mut()?.insert(sym, value)
}
}
//
// struct ObjRef
//
#[derive(Debug, Scan)]
pub struct ObjRef<T = (dyn Obj + Send + Sync + 'static)>
where
T: Obj + ?Sized + Send + Sync,
{
gc: Gc<RwLock<T>>,
}
impl<T> Clone for ObjRef<T>
where
T: Obj + ?Sized + Send + Sync,
{
fn clone(&self) -> Self {
ObjRef {
gc: self.gc.clone(),
}
}
}
//
// impl ObjRef
//
impl<T> ObjRef<T>
where
T: Obj + ?Sized + Send + Sync,
{
/// Check object reference equality.
pub fn ref_eq(&self, other: &Self) -> bool {
let lhs: &RwLock<T> = &*self.gc.get();
let rhs: &RwLock<T> = &*other.get();
std::ptr::eq::<RwLock<T>>(lhs, rhs)
}
}
impl<T> ObjRef<T>
where
T: Obj + Send + Sync + 'static,
{
pub fn new(obj: T) -> Self {
ObjRef {
gc: Gc::new(RwLock::new(obj)),
}
}
}
impl<T, U> CoerceUnsized<ObjRef<U>> for ObjRef<T>
where
T: Obj + Send + Sync + ?Sized + Unsize<U>,
U: Obj + Send + Sync + ?Sized,
{
}
//
// impl Deref for ObjRef
//
impl<T: Obj + ?Sized + Send + Sync> Deref for ObjRef<T> {
type Target = Gc<RwLock<T>>;
fn deref(&self) -> &Self::Target {
&self.gc
}
}
//
// impl DerefMut for ObjRef
//
impl<T: Obj + ?Sized + Send + Sync> DerefMut for ObjRef<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.gc
}
}