Commit e2d96f04 authored by Tom Niget's avatar Tom Niget

Mutexes work!

parent 0cff3aae
......@@ -62,10 +62,16 @@ template <PySmartPtr T> struct RealType<T> {
namespace typon {
class TyNone {};
//class TyNone {};
using TyNone = std::nullopt_t;
auto None = std::nullopt;
} // namespace typon
static constexpr auto None = typon::None;
// typon_len
template <typename T>
......@@ -121,7 +127,6 @@ std::ostream &operator<<(std::ostream &os, std::optional<T> const &opt) {
return opt ? os << opt.value() : os << "None";
}
static constexpr auto PyNone = std::nullopt;
#define system_error(err, message) \
do { \
......
......@@ -11,6 +11,24 @@ namespace view = std::views;
namespace typon {
using namespace referencemodel;
template<typename _Base0 = object>
struct TyCell__oo : classtype<_Base0, TyCell__oo<>> {
static constexpr std::string_view name = "Cell";
template<typename T>
struct Obj : instance<TyCell__oo<>, Obj<T>> {
T val;
Obj() = default;
Obj(Obj const&) = delete;
};
template<typename T>
auto operator()(T val) const {
return Obj<T>{val};
}
};
template<typename _Base0 = object>
struct TyMutex__oo : classtype<_Base0, TyMutex__oo<>> {
static constexpr std::string_view name = "Mutex";
......@@ -18,30 +36,22 @@ struct TyMutex__oo : classtype<_Base0, TyMutex__oo<>> {
template<typename T>
struct Obj : instance<TyMutex__oo<>, Obj<T>> {
typon::Mutex mutex;
T val;
Obj() {
print("Obj()"_ps);
}
TyCell__oo<>::Obj<T> cell;
};
struct : method {
auto operator()(auto self, auto callback) -> typon::Task<TyNone> const {
print("a"_ps);
auto lock = dot(self, mutex).lock();
print("b"_ps);
co_await lock;
print("c"_ps);
co_await callback(dot(self, val));
print("d"_ps);
co_return {};
co_await callback(ref(dot(self, cell)));
co_return None;
}
} static constexpr when{};
template<typename T>
auto operator()(T val) const {
auto obj = referencemodel::meta::arc<Obj<T>>();
//dot(obj, val) = val;
auto obj = referencemodel::meta::arc<Obj<T>>(std::in_place);
dot(obj, cell).val = val;
return obj;
}
};
......
......@@ -89,7 +89,7 @@ typon::Task<void> print(T const &head, Args const &...args) {
struct {
typon::TyNone operator()() {
std::cout << '\n';
return {};
return typon::None;
}
template <typename T, typename... Args>
......@@ -97,7 +97,7 @@ struct {
std::cout << str(head)->value;
(((std::cout << ' '), (std::cout << str(args)->value)), ...);
std::cout << '\n';
return {};
return typon::None;
}
} print;
// typon::Task<void> print() { std::cout << '\n'; co_return; }
......
......@@ -17,7 +17,31 @@ template <typename _Base0 = object>
struct TySlice__oo : classtype<_Base0, TySlice__oo<>> {
static constexpr std::string_view name = "TySlice";
auto operator()() const {}
template <typename Start, typename Stop, typename Step>
struct Obj : value<TySlice__oo<>, Obj<Start, Stop, Step>> {
Start start;
Stop stop;
Step step;
Obj(Start start, Stop stop, Step step) : start(start), stop(stop), step(step) {}
};
template <typename Stop>
auto operator()(Stop stop) const {
return Obj<TyNone, Stop, TyNone>{None, stop, None};
}
template <typename Start, typename Stop>
auto operator()(Start start, Stop stop) const {
return Obj<Start, Stop, TyNone>{start, stop, None};
}
template <typename Start, typename Stop, typename Step>
auto operator()(Start start, Stop stop, Step step) const {
return Obj<Start, Stop, Step>{start, stop, step};
}
};
static constexpr TySlice__oo<> TySlice{};
......
......@@ -176,6 +176,16 @@ struct TyStr__oo : classtype<_Base0, TyStr__oo<>> {
auto operator()(auto self) const { return (self->value.size()); }
} static constexpr oo__len__oo{};
// getitem
struct : method {
auto operator()(auto self, auto index) const {
if (index < 0) {
index += self->value.size();
}
return Obj(self->value[index]);
}
} static constexpr oo__getitem__oo{};
/*struct : method {
auto operator()(auto self, auto other) const {
auto pos = self->value.find(other->value);
......
......@@ -550,6 +550,8 @@ template <typename T> struct Arc {
Arc(std::nullptr_t) : ptr(nullptr) {}
Arc(std::in_place_t) : ptr(new Pack<T>()) {}
Arc(T &&t) : ptr(new Pack<T>(std::move(t))) {}
Arc(Arc &&arc) : ptr(std::exchange(arc.ptr, nullptr)) {}
......
......@@ -54,7 +54,7 @@ struct socket__oo : referencemodel::moduletype<socket__oo<>> {
if (::setsockopt(self->fd, level, optname, &optval, sizeof(int)) < 0) {
system_error(errno, "setsockopt()");
}
return typon::TyNone{};
return None;
}
} static constexpr setsockopt{};
......@@ -70,7 +70,7 @@ struct socket__oo : referencemodel::moduletype<socket__oo<>> {
if (::bind(self->fd, (const sockaddr *)&addr, sizeof(addr)) < 0) {
system_error(errno, "bind()");
}
return typon::TyNone{};
return None;
}
} static constexpr bind{};
......
//
// Created by Tom on 09/03/2023.
//
#ifndef TYPON_TIME_HPP
#define TYPON_TIME_HPP
#include "builtins.hpp"
#include <iostream>
namespace py_time {
template <typename _Unused = void>
struct time__oo : referencemodel::moduletype<time__oo<>> {
/*FUNCTION(void, exit, (int code), { std::exit(code); })*/
struct : referencemodel::function {
typon::Task<typon::TyNone> operator()(auto duration) const {
co_await typon::io::sleep(std::chrono::seconds(duration));
co_return None;
}
} static constexpr sleep{};
};
time__oo<> all;
} // namespace py_time
#endif // TYPON_TIME_HPP
......@@ -28,7 +28,7 @@ class float:
assert int.__add__
assert (5).__add__
class slice:
class slice[Start, Stop, Step]:
pass
......
def sleep(duration: int) -> None:
...
\ No newline at end of file
......@@ -32,10 +32,9 @@ def thing(x):
if __name__ == "__main__":
print("j")
# act = Actor(123)
m = Mutex(123)
act = Actor(123)
print("k")
#act.mutex.when(thing)
act.mutex.when(thing)
# class Actor[T]:
# def __init__(self):
......
from time import sleep
def inc(cell):
x = cell.val
sleep(1)
cell.val = x + 1
# todo: why doesnt it crash with a wrong field name ???
print("current:", cell.val)
class Thing:
x: int
def __init__(self, x: int):
self.x = x
def inc(self):
x = self.x
sleep(1)
self.x = x + 1
print("current:", self.x)
def truc():
m = Mutex(0)
for _ in range(10):
fork(lambda: m.when(inc))
sync()
def nomutex():
t = Thing(0)
for _ in range(10):
fork(lambda: t.inc())
sync()
if __name__ == "__main__":
print("Mutex:")
truc()
print("No mutex:")
nomutex()
......@@ -62,8 +62,13 @@ def emit_class(name: str, node: ConcreteType) -> Iterable[str]:
yield from emit_function(mname, ty, "method")
yield "template <"
yield from join(",", (f"typename {name}" for name in template_params()))
if node.generic_parent.parameters:
yield from join(",", (f"typename {name}" for name in node.generic_parent.parameters))
yield ", typename... $T"
else:
yield "typename... $T, typename _Void = void"
yield ">"
def obj_params():
yield from join(",", template_params())
......
......@@ -68,7 +68,7 @@ class ExpressionVisitor(NodeVisitor):
elif isinstance(node.value, complex):
yield f"TyComplex({node.value.real}, {node.value.imag})"
elif node.value is None:
yield "PyNone"
yield "None"
else:
raise NotImplementedError(node, type(node))
......
......@@ -323,7 +323,7 @@ class BlockVisitor(NodeVisitor):
if node.value:
yield from self.expr().visit(node.value)
else:
yield "typon::TyNone{}"
yield "None"
yield ";"
......@@ -406,7 +406,6 @@ TY_STR = create_builtin_type("str")
TY_BYTES = create_builtin_type("bytes")
TY_COMPLEX = create_builtin_type("complex")
TY_NONE = create_builtin_type("NoneType")
TY_SLICE = create_builtin_type("slice")
def unimpl(*args, **kwargs):
......@@ -430,6 +429,7 @@ TY_LIST = create_builtin_generic_type("list")
TY_SET = create_builtin_generic_type("set")
TY_DICT = create_builtin_generic_type("dict")
TY_TUPLE = create_builtin_generic_type("tuple")
TY_SLICE = create_builtin_generic_type("slice")
TY_MUTEX = create_builtin_generic_type("Mutex")
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment