.. include:: alias.rst

Core model
==========

Overview
--------

The |rcm| is an executable coordination model and its syntactic elements are:

* States (state machines)
* Links (to states)
* Barriers
* Ports
* Connections

The first three syntactic elements (states, links and barriers) are
nodes in |rcm|'s state machines. Ports are properties of states and
connections connect different nodes with each other. States execute code, barriers are
used to implement concurrency and links allow to re-use existing state
machines.


States
^^^^^^

A state is the central entity for executing code. Hence, it is the
only node type that contains script code to be executed. More
specifically, a state has:

* An entry script: the script that is executed once when the state has
  been activated.
* Action scripts: one or many script blocks. Each script block must
  contain one condition expression. Action scripts are executed while
  a state is active (until it is deactivated) given their condition
  expression evaluates to ``true``.
* An exit script: the script that is executed once when the state has been
  deactivated. If the entry script of a state has been executed, its
  exit script will be executed as well at some point.

States can be parameterized with parameter values. Incomplete
parameter values (e.g. structs with missing fields - possibly nested)
are allowed in root states at upload time to provide default
parameter functionality. But they will be rejected when trying to execute
them.

In addition, states can have a variable and result value. These values are
available in all state scripts and condition expressions of actions and ports
of the state itself. While parameters are read only the variable and result
value can also be changed within scripts. Furthermore, the result value is
available in the parameters of sibling states and action and port conditions of
the parent state.

States contain a set of ports which control deactivation of the state and
consequential transition to the next state if there is one. States can also be
organized hierarchically. Each state can optionally contain (named) child nodes
which can also be active as long as the outer state stays active. If the outer
state is deactivated, all children are preempted.


Links
^^^^^

There are two different types of links:

* Static links, and
* Dynamic links

Static links reference a different state, that is known prior to execution,
while dynamic links are resolved during runtime.

Links behave exactly like actual states, inheriting the ports, children,
scripts and parameter values from the linked state. A link can specify
connections for its inherited ports and instantiate the linked state with
different parameter values.

The parameter value of the linked state acts as a default value for
the parameter value of the link. That is, if a parameter value is
present in exactly one of link or linked state, that one is used, and
if both are present, the parameter value of the link is used. Absence
of a parameter is signaled by not including it as field in the struct
of parameters, not by means of a null value. A null value behaves like a
regular parameter value and can overwrite a default parameter
value. If the parameter values of the link and linked state are
structs, their fields are merged using the above rule. That is, if
fields with the same name exist in both, the one in the link parameter
value is used, or they are merged recursively if they are themselves
structs. Any fields that occur exclusively in either the link or
linked state, according to their name, are used.

Barriers
^^^^^^^^

Barriers implement split and join semantics and are the only
possibility to create parallel behavior in |rcm| state machines as a
regular state can only activate a single port. They are only activated
when all incoming connections are ready and activate all states
connected through outgoing connections simultaneously. It must be
noted that barriers can only be connected to states and not to other
barriers.

Ports
^^^^^

Ports control if a state should be deactivated. Ports are defined with
a port name and a port condition. The port name is
used to identify a port when it is used in connections. The
port condition is an expression that, if it evaluates to ``true``,
causes the owning state to be deactivated and a (possibly) connected
state to be activated. Ports are evaluated in the order in which they are
defined within a state, i.e. the first port whose condition evaluates to
``true`` will cause the state to be deactivated and no further port
conditions will be evaluated.

Connections
^^^^^^^^^^^

Connections connect states, links and barriers with each other. When
connecting two states or links with each other, the connection is
defined over the name of the source state or link, the name of a port
in the source node and the name of the destination node (can be a
state, link or barrier). Connections between barriers and states and
between barriers and links are defined with only the name of the
source node and the name of the destination node. Connections between
two barriers are not allowed.

.. _core_model:

Semantics
---------

Every |rcm| state is executable. Execution denotes the
evaluation of a state and referenced model elements as specified in the
state's syntax. In order to execute a state, the sequence and how these 
model elements are to be evaluated have to be specified. Even though
the execution process is primarily defined by state transitions
describing the progress of a model, it also includes the coordinated
invocation of specified actions, entry functions and exit functions. In the
following paragraphs, execution semantics are described informally
using prose and informal rules and sequences. This format can be
ambiguous. Thus, a formal semantics is defined in the next section.

General
^^^^^^^

When a state is executed, the state to be executed is activated. In
addition, the child state marked as *first*, its first child etc. are
activated as well. The first child of a dynamic link, however, will only
be activated after entering. Execution follows these general rules:

* Evaluation happens top-down, conditions and thus transitions
  (e.g. on port activation) of 'upper' layers in the state hierarchy
  are considered first and may *preempt* evaluation of 'lower'
  levels. (structural priority)
* If the entry function of a state has been executed, the state's exit
  function will always be executed when the state is deactivated.
* Connections at ports are considered in sequence. The order is
  determined by a port priority value where smaller priorities are
  considered first. Port conditions are checked similar to the
  conditional or ``||``, where the first port evaluating to ``true``
  wins and results possibly in a transition. All subsequent ports are
  then ignored even if they evaluate to ``true``.
* Actions are stored in a sequence and are executed in order given
  their action condition evaluates to ``true``. In contrast to ports,
  all actions with a ``true`` condition are evaluated.
* Links directly proxy the linked state but allow for different
  parameterization. Executing a link is identical to replacing the
  link with the linked state and using the parameter value of the
  linked state as default parameters. Multiple links to the same
  linked state do not share common execution state, in particular,
  they do not share parameters, variables and results.
* Connections of states onto themselves are not supported and cannot transition.
* Actions and connections are only evaluated once before services and/or aborted
  execution are considered, i.e. state machines have at least once the chance to
  react to something (unless their parent preempts them).
* The |core| stores root states identified by their names.
* Only root states stored in the |core| can be linked to.
* No link cycles are allowed, i.e. links that contain states that
  contain links to the original linked state are not allowed. In other
  words, recursion using links is not possible.
* Barriers cannot be connected to barriers.

State execution is separated in so called *macro* and *micro* steps. A
*macro* step takes a snapshot of the current state of external inputs
and progresses a given state and its children using micro steps until
a complete state is reached, i.e. no further transitions are
possible. To prevent endless loops without exiting a macro step,
actions and connections can be executed/followed only once in a single
macro step.

Execution status
^^^^^^^^^^^^^^^^

Every node in the state machine hierarchy is always in one of four possible
execution phases (also called status of the state in the following):

``Inactive``, ``Entering``, ``Active``, ``Exiting``

where the following terms are used to denote changes of the execution phase:

* ``Inactive`` -> **activate** -> ``Entering``
* ``Entering`` -> **enter** -> ``Active``
* ``Active`` -> **deactivate** -> ``Exiting``
* ``Exiting`` -> **exit** -> ``Inactive``

Parameter evaluation
^^^^^^^^^^^^^^^^^^^^

Parameters for a state are evaluated when the state is activated,
i.e. when its status is set from ``Inactive`` to
``Entering``. Parameters are not re-evaluated again while the state is
``Entering``, ``Active`` or ``Exiting``. It must be noted that
parameter expressions are not evaluated in the child context but in
the parent context. Consider the following example:

.. code-block:: lua

   foo: child("bar").result.x

It defines how the parameter ``foo`` should be computed. Since the
above expression is evaluated in the parent scope of the state for
which the parameter is defined, ``child("bar")`` accesses a sibling
named ``bar``. However, if the same expression is used in an action
script or action condition expression, it denotes the child named
``bar``.

Resolving dynamic links
^^^^^^^^^^^^^^^^^^^^^^^

Dynamic links are resolved when the containing state is entered, i.e. when its
status is set from ``Entering`` to ``Active``. If the state has an entry action
dynamic links are resolved after the entry action. After resolving, the first
child of the dynamic link will be activated. Dynamic links are not re-evaluated
again while the state is ``Active`` or ``Exiting``.

Micro step rules
^^^^^^^^^^^^^^^^

Micro step evaluation is defined top-down in the state hierarchy, where
'upper' levels are considered before 'lower' levels. The first applicable
micro step rule is then taken and results in a micro step, which starts again
at the root of this execution's state hierarchy.

#. Evaluate *port conditions*, and if one evaluates to ``true``, deactivate the state.

#. For all *actions*: if the action's condition evaluates to ``true`` and it was not
   yet executed (in the current macro step), execute its function body.

#. For all *connections*: transition all **ready** connections by
   deactivating the port of the connection's source and activating its destination
   (deactivation resets all port activations).

    A *port connection* is **ready** when:

      * Source state is ``Inactive``
      * Source port is active
      * Destination is ``Inactive``
      * No port of destination is active

    A *barrier connection* is **ready** when:

      * Source barrier is ``Active``
      * Destination state is ``Inactive``
      * No port of destination is active

    Furthermore, connections **into** and **out of** barriers need to be
    simultaneously ready in order to transition them. This means that a barrier is
    only activated when all incoming connections are ready, and is only
    deactivated when all outgoing connections are ready.

#. If the state is still active, do micro steps in all child states (recursively) with *propagated*
   contexts.

Examples
^^^^^^^^

To further clarify the syntax and execution semantics, an example |rcm| state
machine is discussed in this section. The example consists of a
graphical representation of the state machine at hand and a macro- and micro-
level description of the execution semantics.

Simple composite state
``````````````````````

This example focuses on a composite state with actions and two
children . The considered issues are whether execution of the first
action does precede the transition from ``A`` to ``B`` or similarly if
the second action is executed before or after ``B``'s entry function.

.. note:: The port conditions of ``pA`` and ``pB`` are directly ``true``.

.. _example_state:

.. only:: html

    .. figure:: _static/example_state.png
        :width: 40%
        :align: center
        :target: _static/example_state.png

        Simple composite |rcm| state with actions and two children

.. only:: latex

    .. figure:: _static/example_state.png
        :width: 40%
        :align: center

        Simple composite |rcm| state with actions and two children

**Macro**

On the macro-level, the ``Parent`` state machine will remain active, along
with its child state ``B``. When transitioning into the state the following
functions will get executed:

  #. | ``Parent`` entry
  #. | ``A`` entry
  #. | action ``1)`` of ``Parent``
  #. | ``A`` exit
  #. | ``B`` entry
  #. | action ``2)`` of ``Parent``
  #. | ``B`` exit
  #. | action ``2)`` of ``Parent`` (until execution gets stopped)

**Micro**

The example at hand can be discussed in more detail by examining the taken
micro steps. Execution gets started by *activating* the root node, effectively
setting ``Parent`` and its first node ``A`` on status ``Entering``. From there
on, the following micro steps are taken:

  #. | Enter ``Parent``, execute its ``entry`` function, it is now ``Active``
  #. | Enter ``A``, execute its ``entry`` function, it is now ``Active``
  #. | No port or action of ``Parent`` evaluates to ``true``,
     | evaluate ports of ``A`` -> ``pA`` triggers, ``A`` is now ``Exiting``
  #. | Action ``1)`` of ``Parent`` gets executed because its condition is ``true``
  #. | No port or action of ``Parent`` evaluates to ``true``,
     | exit ``A``, execute its ``exit`` function, it is now ``Inactive``
  #. | No port or action of ``Parent`` evaluates to ``true``,
     | transition into ``B``, activate it, it is now ``Entering``
  #. | No port or action of ``Parent`` evaluates to ``true``,
     | evaluate ports of ``B`` -> ``pB`` triggers, ``B`` is now ``Exiting``
  #. | Action ``2)`` of ``Parent`` gets executed because its condition is ``true``
  #. | No port of ``Parent`` evaluates to ``true``, and action ``2)`` was already executed,
     | exit ``B``, execute its ``exit`` function, it is now ``Inactive``

No further micro steps can be taken (in this macro step) as the only condition
which would evaluate to ``true`` was already executed. However, in **all**
following macro steps, action ``2)`` of ``Parent`` will always be executed
once because the ``pB`` remains triggered - until execution gets stopped.
