fix warnings & format

This commit is contained in:
Michael Sippel 2021-11-19 12:19:52 +01:00
parent bf8a949cdd
commit 411b773ab5
Signed by: senvas
GPG key ID: F96CF119C34B64A6
61 changed files with 2759 additions and 2741 deletions

View file

@ -1,8 +1,7 @@
use std::{
fs::File,
io::{Read, Write},
os::unix::io::FromRawFd
os::unix::io::FromRawFd,
};
fn fib(n: u64) -> u64 {
@ -10,7 +9,7 @@ fn fib(n: u64) -> u64 {
let mut y1 = 1;
let mut y2 = 0;
for _ in 0 .. n {
for _ in 0..n {
y = y1 + y2;
y2 = y1;
y1 = y;
@ -26,26 +25,32 @@ fn main() {
nested::magic_header();
eprintln!("
interface (Sequence ) 0 1");
eprintln!(
"
interface (Sequence ) 0 1"
);
let mut f0 = unsafe { File::from_raw_fd(0) };
eprintln!("
eprintln!(
"
>0: n
( )
( MachineInt )
( MachineWord )
( Stream MachineSyllab )
");
"
);
let mut f1 = unsafe { File::from_raw_fd(1) };
eprintln!("
eprintln!(
"
<1: n'th fibonacci number
( )
( MachineInt )
( MachineWord )
( Stream MachineSyllab )
");
"
);
nested::magic_header();
@ -55,4 +60,3 @@ interface (Sequence ) 0 1");
bytes = fib(n).to_le_bytes();
f1.write(&bytes).expect("");
}

View file

@ -1,9 +1,4 @@
use std::{
fs::File,
io::{Read},
os::unix::io::FromRawFd
};
use std::{fs::File, io::Read, os::unix::io::FromRawFd};
fn main() {
nested::magic_header();
@ -11,15 +6,18 @@ fn main() {
nested::magic_header();
let mut f0 = unsafe { File::from_raw_fd(0) };
eprintln!("
eprintln!(
"
>0:
( )
( MachineInt )
( MachineWord )
( Stream MachineSyllab )
");
"
);
eprintln!("
eprintln!(
"
<1:
( )
( PositionalInt 10 BigEndian )
@ -27,7 +25,8 @@ fn main() {
( Sequence UTF-8-Char )
( Stream UTF-8-Char )
( Stream MachineSyllab )
");
"
);
nested::magic_header();
@ -35,4 +34,3 @@ fn main() {
f0.read_exact(&mut bytes).expect("");
println!("{}", u64::from_le_bytes(bytes));
}

View file

@ -1,55 +1,68 @@
use {
nested::{
core::{
ViewPort,
TypeDict
},
vec::{VecBuffer},
integer::{RadixProjection}
}
use nested::{
core::{TypeDict, ViewPort},
integer::RadixProjection,
vec::VecBuffer,
};
#[async_std::main]
async fn main() {
let mut td = TypeDict::new();
for tn in vec![
"MachineWord", "MachineInt", "MachineSyllab",
"Vec", "Stream", "Json",
"Sequence", "UTF-8-Char",
"PositionalInt", "Digit", "LittleEndian", "BigEndian",
"DiffStream", "",
"$src_radix", "$dst_radix"
] { td.add_typename(tn.into()); }
"MachineWord",
"MachineInt",
"MachineSyllab",
"Vec",
"Stream",
"Json",
"Sequence",
"UTF-8-Char",
"PositionalInt",
"Digit",
"LittleEndian",
"BigEndian",
"DiffStream",
"",
"$src_radix",
"$dst_radix",
] {
td.add_typename(tn.into());
}
let radix_types = vec![
td.type_term_from_str("( )").unwrap(),
td.type_term_from_str("( PositionalInt 10 LittleEndian )").unwrap(),
td.type_term_from_str("( PositionalInt 10 LittleEndian )")
.unwrap(),
td.type_term_from_str("( Sequence ( Digit 10 ) )").unwrap(),
td.type_term_from_str("( Sequence UTF-8-Char )").unwrap(),
td.type_term_from_str("( Sequence MachineSyllab )").unwrap()
td.type_term_from_str("( Sequence MachineSyllab )").unwrap(),
];
let src_types = vec![
td.type_term_from_str("( )").unwrap(),
td.type_term_from_str("( PositionalInt $src_radix LittleEndian )").unwrap(),
td.type_term_from_str("( Sequence ( Digit $src_radix ) )").unwrap(),
td.type_term_from_str("( PositionalInt $src_radix LittleEndian )")
.unwrap(),
td.type_term_from_str("( Sequence ( Digit $src_radix ) )")
.unwrap(),
td.type_term_from_str("( Sequence MachineInt )").unwrap(),
td.type_term_from_str("( DiffStream ( Vec MachineInt ) )").unwrap(),
td.type_term_from_str("( DiffStream ( Vec MachineInt ) )")
.unwrap(),
td.type_term_from_str("( Json )").unwrap(),
td.type_term_from_str("( Stream UTF-8-Char )").unwrap(),
td.type_term_from_str("( Stream MachineSyllab )").unwrap()
td.type_term_from_str("( Stream MachineSyllab )").unwrap(),
];
let dst_types = vec![
td.type_term_from_str("( )").unwrap(),
td.type_term_from_str("( PositionalInt $dst_radix LittleEndian )").unwrap(),
td.type_term_from_str("( Sequence ( Digit $dst_radix ) )").unwrap(),
td.type_term_from_str("( PositionalInt $dst_radix LittleEndian )")
.unwrap(),
td.type_term_from_str("( Sequence ( Digit $dst_radix ) )")
.unwrap(),
td.type_term_from_str("( Sequence MachineInt )").unwrap(),
td.type_term_from_str("( DiffStream ( Vec MachineInt ) )").unwrap(),
td.type_term_from_str("( DiffStream ( Vec MachineInt ) )")
.unwrap(),
td.type_term_from_str("( Json )").unwrap(),
td.type_term_from_str("( Stream UTF-8-Char )").unwrap(),
td.type_term_from_str("( Stream MachineSyllab )").unwrap()
td.type_term_from_str("( Stream MachineSyllab )").unwrap(),
];
nested::magic_header();
@ -99,27 +112,26 @@ async fn main() {
src_radix,
dst_radix,
src_digits_port.outer().to_sequence(),
dst_digits_port.inner()
dst_digits_port.inner(),
);
// output dst digits
let writer = {
use std::{
os::unix::io::FromRawFd
};
use std::os::unix::io::FromRawFd;
dst_digits_port.outer().serialize_json(unsafe { std::fs::File::from_raw_fd(1) })
dst_digits_port
.outer()
.serialize_json(unsafe { std::fs::File::from_raw_fd(1) })
};
// start reading src digits
{
use async_std::{
os::unix::io::FromRawFd
};
use async_std::os::unix::io::FromRawFd;
src_digits.from_json(unsafe { async_std::fs::File::from_raw_fd(0) }).await;
src_digits
.from_json(unsafe { async_std::fs::File::from_raw_fd(0) })
.await;
}
drop(writer);
}

View file

@ -1,8 +1,7 @@
use std::{
fs::File,
io::{Read, Write},
os::unix::io::FromRawFd
os::unix::io::FromRawFd,
};
fn main() {
@ -10,16 +9,19 @@ fn main() {
eprintln!(" Parse MachineInt from String");
nested::magic_header();
eprintln!("
eprintln!(
"
$1: radix
( )
( PositionalInt 10 BigEndian )
( Sequence ( Digit 10 ) )
( Sequence UTF-8-Char )
( Sequence MachineSyllab )
");
"
);
eprintln!("
eprintln!(
"
>0: n
( )
( PositionalInt $radix BigEndian )
@ -27,15 +29,18 @@ $1: radix
( Sequence UTF-8-Char )
( Stream UTF-8-Char )
( Stream MachineSyllab )
");
"
);
eprintln!("
eprintln!(
"
<1: n
( )
( MachineInt )
( MachineWord )
( Stream MachineSyllab )
");
"
);
nested::magic_header();
@ -55,6 +60,10 @@ $1: radix
let mut chars = Vec::new();
f0.read_to_end(&mut chars).expect("");
chars.retain(|c| (*c as char).is_alphanumeric());
f1.write(&u64::from_str_radix(&String::from_utf8_lossy(&chars), radix).unwrap().to_le_bytes()).expect("");
f1.write(
&u64::from_str_radix(&String::from_utf8_lossy(&chars), radix)
.unwrap()
.to_le_bytes(),
)
.expect("");
}

View file

@ -1,20 +1,17 @@
use std::{
collections::HashMap,
hash::Hash
};
use std::{collections::HashMap, hash::Hash};
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
pub struct Bimap<V: Eq + Hash, Λ: Eq + Hash> {
pub : HashMap::<V, Λ>,
pub my: HashMap::<Λ, V>
pub : HashMap<V, Λ>,
pub my: HashMap<Λ, V>,
}
impl<V: Eq + Hash + Clone, Λ: Eq + Hash + Clone> Bimap<V, Λ> {
pub fn new() -> Self {
Bimap {
: HashMap::new(),
my: HashMap::new()
my: HashMap::new(),
}
}
@ -25,4 +22,3 @@ impl<V: Eq + Hash + Clone, Λ: Eq + Hash + Clone> Bimap<V, Λ> {
}
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>

View file

@ -1,70 +1,69 @@
use {
crate::core::Observer,
async_std::stream::Stream,
core::{
task::{Poll, Context, Waker},
pin::Pin
pin::Pin,
task::{Context, Poll, Waker},
},
std::{
sync::{Arc, Mutex},
collections::HashSet,
hash::Hash
hash::Hash,
sync::{Arc, Mutex},
},
async_std::{
stream::Stream
},
crate::{
core::{Observer}
}
};
/*\
/*\
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
Traits
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
\*/
pub trait ChannelData : Default + IntoIterator + Send + Sync {
pub trait ChannelData: Default + IntoIterator + Send + Sync {
fn channel_insert(&mut self, x: Self::Item);
}
/*\
/*\
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
Queue Channel
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
\*/
impl<T> ChannelData for Vec<T>
where T: Send + Sync {
where
T: Send + Sync,
{
fn channel_insert(&mut self, x: T) {
self.push(x);
}
}
/*\
/*\
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
Set Channel
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
\*/
impl<T> ChannelData for HashSet<T>
where T: Eq + Hash + Send + Sync {
where
T: Eq + Hash + Send + Sync,
{
fn channel_insert(&mut self, x: T) {
self.insert(x);
}
}
/*\
/*\
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
Singleton Channel
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
\*/
impl<T> ChannelData for Option<T>
where T: Send + Sync {
where
T: Send + Sync,
{
fn channel_insert(&mut self, x: T) {
*self = Some(x);
}
}
/*\
/*\
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
Channel
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
@ -73,7 +72,7 @@ struct ChannelState<Data: ChannelData> {
send_buf: Option<Data>,
recv_iter: Option<Data::IntoIter>,
num_senders: usize,
waker: Option<Waker>
waker: Option<Waker>,
}
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
@ -84,7 +83,9 @@ pub struct ChannelReceiver<Data: ChannelData>(Arc<Mutex<ChannelState<Data>>>);
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
impl<Data: ChannelData> ChannelSender<Data>
where Data::IntoIter: Send + Sync {
where
Data::IntoIter: Send + Sync,
{
pub fn send(&self, msg: Data::Item) {
let mut state = self.0.lock().unwrap();
@ -102,7 +103,10 @@ where Data::IntoIter: Send + Sync {
use crate::core::View;
impl<V: View + ?Sized, Data: ChannelData<Item = V::Msg>> Observer<V> for ChannelSender<Data>
where V::Msg: Clone, Data::IntoIter: Send + Sync {
where
V::Msg: Clone,
Data::IntoIter: Send + Sync,
{
fn notify(&mut self, msg: &V::Msg) {
self.send(msg.clone());
}
@ -138,7 +142,7 @@ impl<Data: ChannelData> ChannelReceiver<Data> {
Some(buf)
} else {
None
}
}
}
}
@ -164,15 +168,12 @@ impl<Data: ChannelData> std::future::Future for ChannelRead<Data> {
impl<Data: ChannelData> Stream for ChannelReceiver<Data> {
type Item = Data::Item;
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>
) -> Poll<Option<Self::Item>> {
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut state = self.0.lock().unwrap();
if let Some(recv_iter) = state.recv_iter.as_mut() {
if let Some(val) = recv_iter.next() {
return Poll::Ready(Some(val))
return Poll::Ready(Some(val));
} else {
state.recv_iter = None
}
@ -191,23 +192,24 @@ impl<Data: ChannelData> Stream for ChannelReceiver<Data> {
}
}
/*\
/*\
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
Factory Functions
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
\*/
pub fn channel<Data: ChannelData>() -> (ChannelSender<Data>, ChannelReceiver<Data>) {
let state = Arc::new(Mutex::new(ChannelState{
let state = Arc::new(Mutex::new(ChannelState {
send_buf: None,
recv_iter: None,
num_senders: 1,
waker: None
waker: None,
}));
(ChannelSender(state.clone()), ChannelReceiver(state))
}
pub fn set_channel<T: Eq + Hash + Send + Sync>() -> (ChannelSender<HashSet<T>>, ChannelReceiver<HashSet<T>>) {
pub fn set_channel<T: Eq + Hash + Send + Sync>(
) -> (ChannelSender<HashSet<T>>, ChannelReceiver<HashSet<T>>) {
channel::<HashSet<T>>()
}
@ -215,7 +217,7 @@ pub fn queue_channel<T: Send + Sync>() -> (ChannelSender<Vec<T>>, ChannelReceive
channel::<Vec<T>>()
}
pub fn singleton_channel<T: Send + Sync>() -> (ChannelSender<Option<T>>, ChannelReceiver<Option<T>>) {
pub fn singleton_channel<T: Send + Sync>() -> (ChannelSender<Option<T>>, ChannelReceiver<Option<T>>)
{
channel::<Option<T>>()
}

View file

@ -1,19 +1,12 @@
use {
crate::core::{
type_term::{TypeDict, TypeTerm},
AnyOuterViewPort, OuterViewPort, View,
},
std::{
collections::HashMap,
sync::{Arc, RwLock}
sync::{Arc, RwLock},
},
crate::{
core::{
type_term::{
TypeTerm,
TypeDict
},
View,
OuterViewPort,
AnyOuterViewPort
}
}
};
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
@ -21,37 +14,31 @@ use {
#[derive(Clone)]
pub struct ReprTree {
port: Option<AnyOuterViewPort>,
branches: HashMap<TypeTerm, Arc<RwLock<ReprTree>>>
branches: HashMap<TypeTerm, Arc<RwLock<ReprTree>>>,
}
impl ReprTree {
pub fn new() -> Self {
ReprTree {
port: None,
branches: HashMap::new()
branches: HashMap::new(),
}
}
pub fn new_leaf(
port: AnyOuterViewPort
) -> Arc<RwLock<Self>> {
pub fn new_leaf(port: AnyOuterViewPort) -> Arc<RwLock<Self>> {
let mut tree = ReprTree::new();
tree.insert_leaf(vec![].into_iter(), port);
Arc::new(RwLock::new(tree))
}
pub fn insert_branch(
&mut self,
type_tag: TypeTerm,
repr: Arc<RwLock<ReprTree>>
) {
pub fn insert_branch(&mut self, type_tag: TypeTerm, repr: Arc<RwLock<ReprTree>>) {
self.branches.insert(type_tag, repr);
}
pub fn insert_leaf(
&mut self,
mut type_ladder: impl Iterator<Item = TypeTerm>,
port: AnyOuterViewPort
port: AnyOuterViewPort,
) {
if let Some(type_term) = type_ladder.next() {
if let Some(next_repr) = self.branches.get(&type_term) {
@ -72,39 +59,45 @@ impl ReprTree {
#[derive(Clone)]
pub struct Object {
pub type_tag: TypeTerm,
pub repr: Arc<RwLock<ReprTree>>
pub repr: Arc<RwLock<ReprTree>>,
}
impl Object {
pub fn get_port<V: View + ?Sized + 'static>(&self) -> Option<OuterViewPort<V>> where V::Msg: Clone {
Some(self.repr.read().unwrap().port.clone()?.downcast::<V>().ok().unwrap())
pub fn get_port<V: View + ?Sized + 'static>(&self) -> Option<OuterViewPort<V>>
where
V::Msg: Clone,
{
Some(
self.repr
.read()
.unwrap()
.port
.clone()?
.downcast::<V>()
.ok()
.unwrap(),
)
}
pub fn downcast(&self, dst_type: TypeTerm) -> Option<Object> {
if let Some(repr) = self.repr.read().unwrap().branches.get(&dst_type) {
Some(Object {
type_tag: dst_type,
repr: repr.clone()
repr: repr.clone(),
})
} else {
None
}
}
fn downcast_ladder(
&self,
repr_ladder: impl Iterator<Item = TypeTerm>
) -> Option<Object> {
repr_ladder.fold(
Some(self.clone()),
|s, t| s?.downcast(t.clone())
)
fn downcast_ladder(&self, repr_ladder: impl Iterator<Item = TypeTerm>) -> Option<Object> {
repr_ladder.fold(Some(self.clone()), |s, t| s?.downcast(t.clone()))
}
pub fn add_iso_repr(
&self,
type_ladder: impl Iterator<Item = TypeTerm>,
morphism_constructors: &HashMap<MorphismType, Box<dyn Fn(Object) -> Object>>
morphism_constructors: &HashMap<MorphismType, Box<dyn Fn(Object) -> Object>>,
) {
let mut cur_repr = self.repr.clone();
@ -117,21 +110,21 @@ impl Object {
let mut obj = None;
for src_type in cur_repr.read().unwrap().branches.keys() {
if let Some(ctor) = morphism_constructors.get(
&MorphismType {
mode: MorphismMode::Iso,
src_type: src_type.clone(),
dst_type: dst_type.clone()
}
) {
let new_obj = ctor(
Object {
type_tag: src_type.clone(),
repr: cur_repr.read().unwrap()
.branches
.get(&src_type).unwrap().clone()
}
);
if let Some(ctor) = morphism_constructors.get(&MorphismType {
mode: MorphismMode::Iso,
src_type: src_type.clone(),
dst_type: dst_type.clone(),
}) {
let new_obj = ctor(Object {
type_tag: src_type.clone(),
repr: cur_repr
.read()
.unwrap()
.branches
.get(&src_type)
.unwrap()
.clone(),
});
assert!(new_obj.type_tag == dst_type);
@ -141,7 +134,10 @@ impl Object {
}
if let Some(obj) = obj {
cur_repr.write().unwrap().insert_branch(obj.type_tag, obj.repr);
cur_repr
.write()
.unwrap()
.insert_branch(obj.type_tag, obj.repr);
} else {
panic!("could not find matching isomorphism!");
}
@ -152,7 +148,7 @@ impl Object {
pub fn add_mono_repr<'a>(
&self,
type_ladder: impl Iterator<Item = TypeTerm>,
morphism_constructors: &HashMap<MorphismType, Box<dyn Fn(Object) -> Object>>
morphism_constructors: &HashMap<MorphismType, Box<dyn Fn(Object) -> Object>>,
) {
let mut cur_type = self.type_tag.clone();
let mut cur_repr = self.repr.clone();
@ -163,24 +159,27 @@ impl Object {
cur_type = dst_type;
cur_repr = next_repr.clone();
} else {
if let Some(constructor) = morphism_constructors.get(
&MorphismType {
mode: MorphismMode::Mono,
src_type: cur_type.clone(),
dst_type: dst_type.clone()
}
) {
let new_obj = constructor(
Object {
type_tag: cur_type.clone(),
repr: cur_repr.read().unwrap()
.branches
.get(&cur_type).unwrap().clone()
}
);
if let Some(constructor) = morphism_constructors.get(&MorphismType {
mode: MorphismMode::Mono,
src_type: cur_type.clone(),
dst_type: dst_type.clone(),
}) {
let new_obj = constructor(Object {
type_tag: cur_type.clone(),
repr: cur_repr
.read()
.unwrap()
.branches
.get(&cur_type)
.unwrap()
.clone(),
});
assert!(new_obj.type_tag == dst_type);
cur_repr.write().unwrap().insert_branch(new_obj.type_tag.clone(), new_obj.repr.clone());
cur_repr
.write()
.unwrap()
.insert_branch(new_obj.type_tag.clone(), new_obj.repr.clone());
cur_type = new_obj.type_tag;
cur_repr = new_obj.repr;
@ -193,9 +192,9 @@ impl Object {
pub fn epi_cast<'a>(
&self,
_type_ladder: impl Iterator<Item = TypeTerm>,
_morphism_constructors: &HashMap<MorphismType, Box<dyn Fn(Object) -> Object>>
_morphism_constructors: &HashMap<MorphismType, Box<dyn Fn(Object) -> Object>>,
) {
// todo
// todo
}
}
@ -220,14 +219,14 @@ pub enum MorphismMode {
Epi,
/// Any other function
Any
Any,
}
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct MorphismType {
pub mode: MorphismMode,
pub src_type: TypeTerm,
pub dst_type: TypeTerm
pub dst_type: TypeTerm,
}
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
@ -237,7 +236,7 @@ pub struct Context {
default_constructors: HashMap<TypeTerm, Box<dyn Fn() -> Object + Send + Sync>>,
morphism_constructors: HashMap<MorphismType, Box<dyn Fn(Object) -> Object + Send + Sync>>,
objects: HashMap<String, Object>,
parent: Option<Arc<RwLock<Context>>>
parent: Option<Arc<RwLock<Context>>>,
}
impl Context {
@ -247,7 +246,7 @@ impl Context {
default_constructors: HashMap::new(),
morphism_constructors: HashMap::new(),
objects: HashMap::new(),
parent
parent,
}
}
@ -266,17 +265,13 @@ impl Context {
pub fn add_morphism(
&mut self,
morph_type: MorphismType,
morph_fn: Box<dyn Fn(Object) -> Object + Send + Sync>
morph_fn: Box<dyn Fn(Object) -> Object + Send + Sync>,
) {
self.morphism_constructors.insert(morph_type, morph_fn);
}
/// adds an object without any representations
pub fn add_obj(
&mut self,
name: String,
typename: &str
) {
pub fn add_obj(&mut self, name: String, typename: &str) {
let type_tag = self.type_dict.type_term_from_str(typename).unwrap();
self.objects.insert(
@ -286,16 +281,13 @@ impl Context {
} else {
Object {
type_tag,
repr: Arc::new(RwLock::new(ReprTree::new()))
repr: Arc::new(RwLock::new(ReprTree::new())),
}
}
},
);
}
pub fn get_obj(
&self,
name: &String
) -> Option<Object> {
pub fn get_obj(&self, name: &String) -> Option<Object> {
if let Some(obj) = self.objects.get(name) {
Some(obj.clone())
} else if let Some(parent) = self.parent.as_ref() {
@ -304,20 +296,17 @@ impl Context {
None
}
}
pub fn get_obj_port<
'a,
V: View + ?Sized + 'static
>(
pub fn get_obj_port<'a, V: View + ?Sized + 'static>(
&self,
name: &str,
type_ladder: impl Iterator<Item = &'a str>
type_ladder: impl Iterator<Item = &'a str>,
) -> Option<OuterViewPort<V>>
where V::Msg: Clone {
where
V::Msg: Clone,
{
self.get_obj(&name.into())?
.downcast_ladder(
type_ladder.map(|tn| self.type_dict.type_term_from_str(tn).unwrap())
)?
.downcast_ladder(type_ladder.map(|tn| self.type_dict.type_term_from_str(tn).unwrap()))?
.get_port()
}
@ -325,43 +314,40 @@ impl Context {
&mut self,
name: &str,
type_ladder: impl Iterator<Item = &'a str>,
port: AnyOuterViewPort
port: AnyOuterViewPort,
) {
self.get_obj(&name.to_string()).unwrap()
.repr.write().unwrap()
self.get_obj(&name.to_string())
.unwrap()
.repr
.write()
.unwrap()
.insert_leaf(
type_ladder.map(|tn| self.type_dict.type_term_from_str(tn).unwrap()),
port
port,
);
}
pub fn epi_cast(
&mut self,
name: &str,
typename: &str
) {
pub fn epi_cast(&mut self, name: &str, typename: &str) {
let dst_type = self.type_dict.type_term_from_str(typename).unwrap();
let old_obj = self.objects.get(&name.to_string()).unwrap().clone();
let new_obj =
if let Some(ctor) = self.morphism_constructors.get(
&MorphismType {
mode: MorphismMode::Epi,
src_type: old_obj.type_tag.clone(),
dst_type: dst_type.clone()
}
) {
ctor(old_obj.clone())
} else {
Object {
type_tag: dst_type,
repr: Arc::new(RwLock::new(ReprTree::new()))
}
};
let new_obj = if let Some(ctor) = self.morphism_constructors.get(&MorphismType {
mode: MorphismMode::Epi,
src_type: old_obj.type_tag.clone(),
dst_type: dst_type.clone(),
}) {
ctor(old_obj.clone())
} else {
Object {
type_tag: dst_type,
repr: Arc::new(RwLock::new(ReprTree::new())),
}
};
new_obj.repr.write().unwrap().insert_branch(
old_obj.type_tag,
old_obj.repr
);
new_obj
.repr
.write()
.unwrap()
.insert_branch(old_obj.type_tag, old_obj.repr);
self.objects.insert(name.to_string(), new_obj);
}
@ -369,9 +355,11 @@ impl Context {
pub fn mono_view<'a, V: View + ?Sized + 'static>(
&mut self,
name: &str,
type_ladder: impl Iterator<Item = &'a str>
type_ladder: impl Iterator<Item = &'a str>,
) -> Option<OuterViewPort<V>>
where V::Msg: Clone {
where
V::Msg: Clone,
{
if let Some(p) = self.get_obj_port(name, type_ladder) {
Some(p)
} else {
@ -381,7 +369,7 @@ impl Context {
&MorphismType {
mode: MorphismMode::Mono,
src_type: old_obj.type_tag.clone(),
dst_type:
dst_type:
}
)
*/
@ -391,4 +379,3 @@ impl Context {
}
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>

View file

@ -1,47 +1,17 @@
pub mod view;
pub mod observer;
pub mod channel;
pub mod context;
pub mod observer;
pub mod port;
pub mod type_term;
pub mod context;
pub mod view;
pub use {
view::{View},
observer::{
Observer,
ObserverExt,
ObserverBroadcast,
NotifyFnObserver,
ResetFnObserver
},
channel::{
ChannelReceiver,
ChannelSender,
set_channel,
queue_channel,
singleton_channel
},
channel::{queue_channel, set_channel, singleton_channel, ChannelReceiver, ChannelSender},
context::{Context, MorphismMode, MorphismType, Object, ReprTree},
observer::{NotifyFnObserver, Observer, ObserverBroadcast, ObserverExt, ResetFnObserver},
port::{
ViewPort,
InnerViewPort,
OuterViewPort,
AnyViewPort,
AnyOuterViewPort,
AnyInnerViewPort,
AnyInnerViewPort, AnyOuterViewPort, AnyViewPort, InnerViewPort, OuterViewPort, ViewPort,
},
type_term::{
TypeID,
TypeTerm,
TypeDict,
},
context::{
ReprTree,
Object,
Context,
MorphismMode,
MorphismType
}
type_term::{TypeDict, TypeID, TypeTerm},
view::View,
};

View file

@ -1,22 +1,18 @@
use {
crate::{
core::{
View,
channel::{channel, ChannelSender, ChannelReceiver}
}
crate::core::{
channel::{channel, ChannelReceiver, ChannelSender},
View,
},
std::{
sync::{Arc, Weak}
},
std::sync::RwLock
std::sync::RwLock,
std::sync::{Arc, Weak},
};
/*\
/*\
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
Observer
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
\*/
pub trait Observer<V: View + ?Sized> : Send + Sync {
pub trait Observer<V: View + ?Sized>: Send + Sync {
fn reset(&mut self, _view: Option<Arc<V>>) {}
fn notify(&mut self, msg: &V::Msg);
}
@ -35,7 +31,7 @@ impl<V: View + ?Sized, O: Observer<V>> Observer<V> for Arc<RwLock<O>> {
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
pub trait ObserverExt<V: View + ?Sized> : Observer<V> {
pub trait ObserverExt<V: View + ?Sized>: Observer<V> {
fn notify_each(&mut self, it: impl IntoIterator<Item = V::Msg>);
}
@ -47,25 +43,30 @@ impl<V: View + ?Sized, T: Observer<V>> ObserverExt<V> for T {
}
}
/*\
/*\
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
Broadcast
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
\*/
pub struct ObserverBroadcast<V: View + ?Sized>
where V::Msg : Send + Sync {
where
V::Msg: Send + Sync,
{
rx: ChannelReceiver<Vec<V::Msg>>,
tx: ChannelSender<Vec<V::Msg>>,
observers: Vec<Weak<RwLock<dyn Observer<V>>>>
observers: Vec<Weak<RwLock<dyn Observer<V>>>>,
}
impl<V: View + ?Sized> ObserverBroadcast<V>
where V::Msg : Clone + Send + Sync {
where
V::Msg: Clone + Send + Sync,
{
pub fn new() -> Self {
let (tx, rx) = channel::<Vec<V::Msg>>();
ObserverBroadcast {
rx, tx,
observers: Vec::new()
rx,
tx,
observers: Vec::new(),
}
}
@ -94,7 +95,9 @@ where V::Msg : Clone + Send + Sync {
}
impl<V: View + ?Sized> Observer<V> for ObserverBroadcast<V>
where V::Msg: Clone {
where
V::Msg: Clone,
{
fn reset(&mut self, view: Option<Arc<V>>) {
for o in self.iter() {
o.write().unwrap().reset(view.clone());
@ -109,26 +112,32 @@ where V::Msg: Clone {
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
pub struct NotifyFnObserver<V, F>
where V: View + ?Sized,
F: Fn(&V::Msg) + Send + Sync {
where
V: View + ?Sized,
F: Fn(&V::Msg) + Send + Sync,
{
f: F,
_phantom: std::marker::PhantomData<V>
_phantom: std::marker::PhantomData<V>,
}
impl<V, F> NotifyFnObserver<V, F>
where V: View + ?Sized,
F: Fn(&V::Msg) + Send + Sync {
where
V: View + ?Sized,
F: Fn(&V::Msg) + Send + Sync,
{
pub fn new(f: F) -> Self {
NotifyFnObserver {
f,
_phantom: std::marker::PhantomData
_phantom: std::marker::PhantomData,
}
}
}
impl<V, F> Observer<V> for NotifyFnObserver<V, F>
where V: View + ?Sized,
F: Fn(&V::Msg) + Send + Sync {
where
V: View + ?Sized,
F: Fn(&V::Msg) + Send + Sync,
{
fn notify(&mut self, msg: &V::Msg) {
(self.f)(msg);
}
@ -137,30 +146,34 @@ where V: View + ?Sized,
//<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
pub struct ResetFnObserver<V, F>
where V: View + ?Sized,
F: Fn(Option<Arc<V>>) + Send + Sync {
where
V: View + ?Sized,
F: Fn(Option<Arc<V>>) + Send + Sync,
{
f: F,
_phantom: std::marker::PhantomData<V>
_phantom: std::marker::PhantomData<V>,
}
impl<V, F> ResetFnObserver<V, F>
where V: View + ?Sized,
F: Fn(Option<Arc<V>>) + Send + Sync {
where
V: View + ?Sized,
F: Fn(Option<Arc<V>>) + Send + Sync,
{
pub fn new(f: F) -> Self {
ResetFnObserver {
f,
_phantom: std::marker::PhantomData
_phantom: std::marker::PhantomData,
}
}
}
impl<V, F> Observer<V> for ResetFnObserver<V, F>
where V: View + ?Sized,
F: Fn(Option<Arc<V>>) + Send + Sync {
where
V: View + ?Sized,
F: Fn(Option<Arc<V>>) + Send + Sync,
{
fn notify(&mut self, _msg: &V::Msg) {}
fn reset(&mut self, view: Option<Arc<V>>) {
(self.f)(view);
}
}

View file

@ -1,22 +1,15 @@
use {
std::sync::Arc,
crate::core::{NotifyFnObserver, Observer, ObserverBroadcast, ResetFnObserver, View},
std::any::Any,
std::sync::Arc,
std::sync::RwLock,
crate::core::{
View,
Observer,
ObserverBroadcast,
NotifyFnObserver,
ResetFnObserver
}
};
pub trait UpdateTask : Send + Sync {
pub trait UpdateTask: Send + Sync {
fn update(&self);
}
/*\
/*\
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
View Port
<<<<>>>><<>><><<>><<<*>>><<>><><<>><<<<>>>>
@ -24,16 +17,18 @@ pub trait UpdateTask : Send + Sync {
pub struct ViewPort<V: View + ?Sized> {
view: Arc<RwLock<Option<Arc<V>>>>,
cast: Arc<RwLock<ObserverBroadcast<V>>>,
pub update_hooks: Arc<RwLock<Vec<Arc<dyn UpdateTask>>>>
pub update_hooks: Arc<RwLock<Vec<Arc<dyn UpdateTask>>>>,
}
impl<V: View + ?Sized> ViewPort<V>
where V::Msg: Clone {
where
V::Msg: Clone,
{
pub fn new() -> Self {
ViewPort {
view: Arc::new(RwLock::new(None)),
cast: Arc::new(RwLock::new(ObserverBroadcast::new())),
update_hooks: Arc::new(RwLock::new(Vec::new()))
update_hooks: Arc::new(RwLock::new(Vec::new())),
}
}
@ -51,8 +46,14 @@ where V::Msg: Clone {
pub fn add_observer(&self, observer: Arc<RwLock<dyn Observer<V>>>) {
self.update();
self.cast.write().unwrap().add_observer(Arc::downgrade(&observer));
observer.write().unwrap().reset(self.view.read().unwrap().clone());
self.cast
.write()
.unwrap()
.add_observer(Arc::downgrade(&observer));
observer
.write()
.unwrap()
.reset(self.view.read().unwrap().clone());
}
pub fn add_update_hook(&self, hook_cast: Arc<dyn UpdateTask>) {