86 lines
2 KiB
Elixir
86 lines
2 KiB
Elixir
defmodule Scopes.CSys.Program do
|
|
alias Scopes.CSys
|
|
alias Scopes.Shape
|
|
|
|
defmodule State do
|
|
defstruct [:value, :stage, :prog]
|
|
end
|
|
|
|
def prepare(prog, value \\ []) do
|
|
state = %State{value: value, stage: :initial, prog: prog}
|
|
{state, get_proc(state)}
|
|
end
|
|
|
|
def get_proc(state) do
|
|
get_proc(elem(state.prog, 0), state.stage)
|
|
end
|
|
|
|
defp get_proc(stages, stage) do
|
|
stages[stage] || stages[:default]
|
|
end
|
|
|
|
# basic program
|
|
|
|
def basic_prog() do
|
|
default = &basic_active/2
|
|
stages = %{
|
|
default: default,
|
|
initial: &basic_initial/2,
|
|
active: default,
|
|
retired: default
|
|
}
|
|
transitions = %{
|
|
restart: :initial,
|
|
retire: :retired,
|
|
next: [initial: :active, active: :retired]
|
|
}
|
|
{stages, transitions}
|
|
end
|
|
|
|
def prepare_basic(value \\ []) do
|
|
prepare(basic_prog(), value)
|
|
end
|
|
|
|
# basic processors
|
|
|
|
def basic_initial(msg, scope) do
|
|
basic(msg, scope)
|
|
end
|
|
|
|
def basic_active(msg, scope) do
|
|
basic(msg, scope)
|
|
end
|
|
|
|
def basic(msg, scope) do
|
|
case Shape.head(msg) do
|
|
[:csys, :connect | _rest] -> CSys.connect(msg, scope)
|
|
[:csys, :create, :succ | _rest] -> create_succ(msg, scope)
|
|
[:csys, :create, :pred | _rest] -> create_pred(msg, scope)
|
|
#[:csys, :next | _rest] -> next(scope, meta)
|
|
#[:csys, :data | rest] -> process_data(rest, Shape.data(msg), scope)
|
|
#[:csys, action | rest] -> transition(action, scope)
|
|
_ -> CSys.forward(msg, scope) || CSys.notify(msg, scope)
|
|
end
|
|
end
|
|
|
|
# message handlers // proc steps
|
|
|
|
def create_succ(msg, scope) do
|
|
new = CSys.create(msg, restart(scope))
|
|
data = Shape.data(msg)
|
|
CSys.send_message(self(), [:csys, :connect], Map.put(data, :target, new))
|
|
end
|
|
|
|
def create_pred(msg, scope) do
|
|
new = CSys.create(msg, restart(scope))
|
|
data = Shape.data(msg)
|
|
CSys.send_message(new, [:csys, :connect], Map.put(data, :target, self()))
|
|
end
|
|
|
|
# helper functions
|
|
|
|
def restart({state, _proc, syns, env}) do
|
|
state_n = %{state | stage: :initial}
|
|
{state_n, get_proc(state_n), syns, env}
|
|
end
|
|
end
|