2.3 KStates

A KStates text is a state machine. It has states, which carry actions that read and write the model, and transitions, which lead from state to state when their conditions hold. A file has the extension .kstates and holds one state machine. The grammar of the language is src/main/antlr/io/karpfen/dsl/grammar/kstates/Kstates.g4 in the karpfen-dsl-tools repository.

The exact behaviour of each construct at run time is in 3.1 Execution semantics.

The examples of this section run on the lamp metamodel of 2 Modeling languages, in which the room also holds a list of spare bulbs:

type "Bulb" "A light bulb that burns with watts, up to maxWatts" {
    prop("maxWatts", "number")
    prop("watts", "number")
    prop("lit", "boolean")
}
type "Switch" "A wall switch" {
    prop("position", "string")
    prop("presses", list("string"))
}
type "Lamp" "A lamp with a bulb, wired to a switch" {
    prop("mode", "string")
    has("bulb", "Bulb")
    knows("control", "Switch")
}
type "Room" "The room the lamp stands in, with spare bulbs" {
    has("lamp", "Lamp")
    has("switch", "Switch")
    has("spares", list("Bulb"))
}

2.3.1 The state machine#

A text starts with STATEMACHINE ATTACHED TO "Type", where Type is a type of the domain metamodel. The braces after it hold the block STATES, then the block TRANSITIONS, then the block MACROS, in this order. STATES and TRANSITIONS are required, TRANSITIONS may be empty, and MACROS may be left out.

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" { }
    }
    TRANSITIONS { }
}

The state machine runs on one object of the type it is attached to. Every path of the state machine starts at this object, unless it starts with one of the names that 2.3.3.2 Paths lists. Which object of the model it is, a run decides by the key of the object.

A text may instead start with STATEMACHINE "name" ATTACHABLE TO "Type", .... Such an attachable state machine is a definition with a name and one or more types. A run does not attach it by a key. The runtime builds an instance of it for each object that a behaves after of its type, an ATTACH clause or an EXCHANGE names it for, see 2.3.11 State machine management and lifecycle. The name is required, and each type is listed once.

A third form, STATEMACHINE "name" FRAGMENT, is a fragment: a piece of a state machine that runs inside a container state of another one, see 2.3.12 Pages.

STATEMACHINE "glowing" ATTACHABLE TO "Bulb" {
    STATES {
        INITIAL STATE "dark" { }
    }
    TRANSITIONS { }
}

2.3.2 States#

STATE "name" { ... } defines a state. No two states of a state machine have the same name, whatever their depth. Transitions refer to states by their names.

2.3.2.1 Nesting#

A state may hold inner states, which are written inside its braces after everything else of the state. While an inner state is active, the states around it are active too. A transition that starts at an outer state also applies while the state machine is in one of its inner states.

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" { }
        STATE "on" {
            STATE "full" { }
            STATE "dimmed" { }
        }
    }
    TRANSITIONS {
        TRANSITION "off" -> "full" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "full" -> "dimmed" {
            CONDITION { EVENT("switch", "dim") }
        }
        TRANSITION "on" -> "off" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

A press switches the lamp off from full and from dimmed, since the transition from on applies in both. A transition into a state with inner states enters the state itself and none of its inner states.

2.3.2.2 The initial state#

The keyword INITIAL in front of STATE marks where the state machine starts. Exactly one state of a file carries the mark, at any depth, in a state machine and in a fragment alike. A file without a mark or with two marks has the error kstates.initial-state-count.

At the start the state machine enters a stack of states, the outermost first: the start stack. It is built level by level. On the top level it takes the state that is marked or that holds the mark somewhere inside it, and the first state of the level when there is none. It goes on below the chosen state the same way while that state has inner states, and stops at a state without inner states.

So the mark may stand on an inner state. The state machine then starts in the marked state and in every state around it, wherever these stand among their siblings:

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        STATE "off" { }
        STATE "on" {
            STATE "full" { }
            INITIAL STATE "dimmed" { }
        }
    }
    TRANSITIONS {
        TRANSITION "dimmed" -> "full" {
            CONDITION { EVENT("switch", "dim") }
        }
        TRANSITION "on" -> "off" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "off" -> "full" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

The start stack is on, dimmed. off is the first state of the top level, but on holds the mark, and inside on the marked dimmed wins over full, which stands first.

A marked state with inner states leads on to its first inner state, and on to the first inner state of each level below:

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "on" {
            STATE "full" {
                STATE "steady" { }
                STATE "flickering" { }
            }
            STATE "dimmed" { }
        }
        STATE "off" { }
    }
    TRANSITIONS {
        TRANSITION "steady" -> "flickering" {
            CONDITION { EVENT("service", "flicker") }
        }
        TRANSITION "full" -> "dimmed" {
            CONDITION { EVENT("switch", "dim") }
        }
        TRANSITION "on" -> "off" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "off" -> "on" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

The start stack is on, full, steady.

A container state counts as a state whose inner states are the states of its fragment, see 2.3.12 Pages. When the start stack reaches a container state, because it is marked or because it stands first on the way down, it goes on with the start of the fragment: the state of the fragment that its own mark chooses, by the same rule. The examples use this fragment, which starts in dimmed:

STATEMACHINE "dimmer" FRAGMENT {
    STATES {
        STATE "full" { }
        INITIAL STATE "dimmed" { }
        FINAL STATE "dark" { }
    }
    TRANSITIONS {
        TRANSITION "dimmed" -> "full" {
            CONDITION { EVENT("switch", "dim") }
        }
        TRANSITION "full" -> "dark" {
            CONDITION { EVENT("switch", "dim") }
        }
    }
}

A marked container state starts the state machine inside its fragment:

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        STATE "off" { }
        INITIAL CONTAINER STATE "on" USE "dimmer" { }
    }
    TRANSITIONS {
        TRANSITION "on" -> "off" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "off" -> "on" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

The start stack is on, on/dimmed. The states of a fragment carry the name of their container state in front, see 2.3.12.3 Names. A container state that the start reaches on the way down goes on the same way:

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "on" {
            CONTAINER STATE "dimming" USE "dimmer" { }
            STATE "bright" { }
        }
        STATE "off" { }
    }
    TRANSITIONS {
        TRANSITION "dimming" -> "bright" {
            CONDITION { DONE }
        }
        TRANSITION "on" -> "off" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "off" -> "on" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

The start stack is on, dimming, dimming/dimmed.

The mark of a fragment belongs to the fragment. The state machine that uses it does not see it, so it does not count as the mark of that state machine and does not pull its start into the container state. It says where the fragment starts, each time its container state is entered:

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" { }
        CONTAINER STATE "on" USE "dimmer" { }
    }
    TRANSITIONS {
        TRANSITION "off" -> "on" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "on" -> "off" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

The start stack is off. A press enters on and at once on/dimmed, and so does every later press from off. Had on its inner states written in its braces, the mark on dimmed would be the one mark of the file, and the state machine would start in on, dimmed as in the first example.

The start goes down into a state with inner states written in its braces, and a transition does not: a transition into such a state enters the state itself and none of its inner states, see 2.3.2.1 Nesting. Every entry into a container state, by the start or by a transition, goes on with the start of its fragment. The one exception is a container state with a history that remembers a state of its fragment: it goes on with the remembered state, see 2.3.7 Histories. What runs when the states are entered, and in which tick, is described in 3.1.3 Active states and for every way of entering a state in 3.1.15 Where the engine goes, and, for container states, in 3.1.14 Pages.

2.3.2.3 Parts of a state#

A state holds these parts, each of them optional, in this order:

  1. BREAKPOINT { ... }, see 2.3.9 Breakpoints
  2. TICK LIMIT { ... }, see 2.3.8 Tick limits
  3. ENTRY { ... }, see 2.3.3.1 Entry and do blocks
  4. DO { ... }
  5. the inner states

In front of STATE stand INITIAL and then a history, SHALLOW HISTORY or DEEP HISTORY, see 2.3.7 Histories, each of them optional. Right before STATE may stand CONTAINER or FINAL, which make a container state or a final state with fewer parts, see 2.3.12 Pages.

2.3.3 Actions#

2.3.3.1 Entry and do blocks#

ENTRY { ... } holds the actions a state runs once when the state machine enters it. DO { ... } holds the actions it runs in every tick in which it is the innermost active state. A block holds action rules, IF IN SCOPE blocks and WITH blocks, which run in the order they are written.

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" {
            ENTRY {
                SET("mode", "off")
                SET("bulb->watts", "0")
            }
        }
        STATE "warming up" {
            ENTRY {
                SET("mode", "on")
            }
            DO {
                SET("bulb->watts", EVAL { return min($(bulb->watts) + 10, $(bulb->maxWatts)) })
            }
        }
    }
    TRANSITIONS {
        TRANSITION "off" -> "warming up" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

While the lamp is in warming up, every tick gives the bulb 10 W more, up to its maximum. A state has no block for leaving it.

2.3.3.2 Paths#

A path names a property or a relation. It is a string of keys joined by ->, and it starts at the object the state machine runs on: "mode" is the mode of the lamp, "bulb->watts" the watts of its bulb and "control->position" the position of the switch the lamp knows. A path follows has and knows relations alike. A path that goes on after a list relation goes on from the first object of the list. Spaces around a key are ignored, so a key that is used in paths should not contain ->.

A path starts somewhere else if its first key is one of these names:

First keyWhere the path starts
eventAt the payload of the event in scope, see 2.3.5 Events.
The name of a WITH block around itAt the result of its macro, see 2.3.3.7 WITH blocks.
A parameter of the macro, in the code of a macroAt the value of the parameter, see 2.3.6 Macros.

2.3.3.3 Action rules#

An action rule names an operation and its operands in parentheses. The first operand is always a string.

RuleWhat it does
SET("path", value)Writes the value into a property that is not a list.
APPEND("path", value)Adds the value at the end of a list property.
SETLIST("path", value)Replaces a list property with the list that its EVAL or MACRO returns.
DROPLIST("path")Empties a list property.
SETOBJ("source", "relation", target)Sets the relation of the object at source, which holds one object, to the target.
APPENDOBJ("source", "relation", target)Adds the target to the list relation of the object at source.
DROPOBJ("path")Removes the object at the path from the model, with every reference to it.
EVENT("domain", name)Raises an event of the name in the domain, without payload.
EXCHANGE("path", name)Ends the state machine of the object at the path and attaches an instance of the attachable state machine of the name.

The source of SETOBJ and APPENDOBJ is a path to an object; "self" and "" name the object the state machine runs on. The target of a has relation must be a new object, which a MACRO or an EVAL builds. The target of a knows relation must be an object of the model: a path to it, or a macro that returns reference("Type"). Every operation except EVENT may also be written in lower case, such as set.

A SETOBJ or APPENDOBJ on a has relation may end with ATTACH name, after its parentheses. The clause names the attachable state machine that the object the rule creates gets. EXCHANGE("path", name) replaces the state machine of an object of the model. In both, the name is a value: a string is the name itself, not a path, and an EVAL or a MACRO returns it as a string. ATTACH may also be written attach. 2.3.11 State machine management and lifecycle shows them at work.

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" {
            ENTRY {
                SET("mode", "off")
                DROPLIST("control->presses")
            }
        }
        STATE "on" {
            ENTRY {
                SET("mode", "on")
                APPEND("control->presses", "on")
                EVENT("lamp", "switched on")
            }
        }
        STATE "reset" {
            ENTRY {
                SETLIST("control->presses", EVAL { return ["reset"] })
            }
        }
    }
    TRANSITIONS {
        TRANSITION "off" -> "on" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "on" -> "reset" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "reset" -> "off" { }
    }
}

A state machine attached to the room changes relations. It wires the lamp to the switch, adds a new spare bulb and removes the bulb from the lamp:

STATEMACHINE ATTACHED TO "Room" {
    STATES {
        INITIAL STATE "rewiring" {
            ENTRY {
                SETOBJ("lamp", "control", "switch")
                APPENDOBJ("self", "spares", MACRO("new bulb", "lamp->bulb->watts"))
                DROPOBJ("lamp->bulb")
            }
        }
    }
    TRANSITIONS { }
    MACROS {
        MACRO "new bulb" {
            TAKES("watts", "number")
            RETURNS("Bulb")
            DEFINITION {
                EVAL { return {"watts": $(watts)} }
            }
        }
    }
}

2.3.3.4 Values#

The last operand of a rule, its value, has one of three forms.

FormExampleValue
A string"40"For SET and APPEND, the text read as the type of the property: a number, true or false, or any text. For SETOBJ and APPENDOBJ, a path to an object. For EVENT, the name of the event.
EVAL { code }EVAL { return $(bulb->maxWatts) / 2 }What the code returns, see 2.3.3.5 EVAL code.
MACRO("name", "path", ...)MACRO("half", "bulb->maxWatts")What the macro returns, see 2.3.6 Macros.

A number or a boolean is written as a string too, as in SET("bulb->watts", "0"). Without the quotes it is a syntax error.

2.3.3.5 EVAL code#

EVAL { ... } holds code that the runtime runs as Python. It can be the value of a rule, a clause of a condition or the definition of a macro. The code returns its result with return.

The runtime prepares the code before it runs it. Each $(path) becomes the current value at the path, so $(bulb->watts) + 10 adds 10 to the watts the bulb has at this moment. Each @name(arguments) becomes a call of the macro name, which takes one argument per TAKES of the macro:

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "dimmed" {
            ENTRY {
                SET("bulb->watts", EVAL {
                    full = $(bulb->maxWatts)
                    return @half(full)
                })
            }
        }
    }
    TRANSITIONS { }
    MACROS {
        MACRO "half" {
            TAKES("watts", "number")
            RETURNS("number")
            DEFINITION {
                EVAL { return $(watts) / 2 }
            }
        }
    }
}

The code may run over several lines. The library reads it as KStates text up to the closing brace, so the braces in the code must pair up. Braces and // inside string literals of the code do not count. Outside string literals, // starts a KStates comment that runs to the end of the line: return a // b loses // b, and a closing brace after it on the same line. Write int(a / b) for the integer division and # for a Python comment.

2.3.3.6 IF IN SCOPE blocks#

IF IN SCOPE("path", ...) { ... } runs the actions inside only if every path it names can be read at this moment. A path that starts with event can be read if an event is in scope and its payload has that field. Any other path can be read if it leads to a value from the object the state machine runs on. A state that the state machine enters with and without an event can read the payload this way:

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" { }
        STATE "on" {
            ENTRY {
                SET("bulb->watts", EVAL { return $(bulb->maxWatts) })
                IF IN SCOPE("event->bright") {
                    SET("bulb->lit", EVAL { return $(event->bright) })
                }
            }
        }
    }
    TRANSITIONS {
        TRANSITION "off" -> "on" {
            CONDITION { EVENT("switch", "dim") }
        }
        TRANSITION "on" -> "off" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

Several paths are separated by commas, and the block runs only if all of them can be read. Blocks may be nested.

2.3.3.7 WITH blocks#

WITH MACRO("name", ...) AS "binding" { ... } runs the macro once and gives its result the name binding for the actions inside the block. The code of an EVAL inside reads the result as $(binding), or a value of an object result as $(binding->key), and the arguments of a macro call inside may start with the name too. with and as may also be written in lower case.

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "on" {
            ENTRY {
                WITH MACRO("brightest", "bulb->maxWatts") AS "best" {
                    SET("bulb->watts", EVAL { return $(best) })
                    SET("bulb->lit", EVAL { return $(best) > 0 })
                }
            }
        }
    }
    TRANSITIONS { }
    MACROS {
        MACRO "brightest" {
            TAKES("limit", "number")
            RETURNS("number")
            DEFINITION {
                EVAL { return $(limit) }
            }
        }
    }
}

Both rules see the same result, even when the macro returns another value each time it runs.

2.3.4 Transitions#

TRANSITION "from" -> "to" { ... } leads from one state to another. The braces may hold a BREAKPOINT block and then a CONDITION block. A transition without a CONDITION block fires whenever the runtime tries it. A transition may lead from a state to the state itself.

2.3.4.1 Conditions#

CONDITION { ... } holds one clause or more. The transition fires only if all clauses hold. The runtime checks them from top to bottom and stops at the first one that fails.

ClauseHolds when
EVENT("domain", "name")An event of this name waits in this domain, see 2.3.5 Events.
VALUE("path")The boolean property at the path is true, or the string property at the path is true in any case. VALUE("true") always holds and VALUE("false") never.
EVAL { code }The code returns true.
DONEThe container state the transition leaves has reached a final state of its fragment, see 2.3.12 Pages.

A condition has at most one EVENT clause. Write it first: the clauses after it can read the payload of the event.

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "on" {
            STATE "dimmer" {
                ENTRY {
                    SET("bulb->watts", EVAL { return $(bulb->watts) - 10 })
                }
            }
        }
    }
    TRANSITIONS {
        TRANSITION "on" -> "dimmer" {
            CONDITION {
                EVENT("switch", "dim")
                EVAL { return not $(event->bright) }
                EVAL { return $(bulb->watts) - 10 >= 0 }
            }
        }
    }
}

The lamp gets dimmer on a dim event whose payload has bright set to false, unless the bulb is already at 0 W.

2.3.4.2 Order and NOT LOOPING#

The runtime tries the transitions of the innermost active state first and those of the states around it after. It tries the transitions of one state in the order they are written, and the first one whose condition holds fires. The order of the TRANSITIONS block is therefore a priority.

NOT LOOPING after the target keeps a transition from firing twice in a row. When the runtime skips it for this reason, it tries the next transition. It has an effect only on a TRANSITION, not on a split or a join.

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "on" {
            DO {
                SET("bulb->watts", EVAL { return $(bulb->watts) - 1 })
            }
        }
        STATE "check" { }
    }
    TRANSITIONS {
        TRANSITION "on" -> "on" NOT LOOPING {
            CONDITION { VALUE("bulb->lit") }
        }
        TRANSITION "on" -> "check" { }
        TRANSITION "check" -> "on" { }
    }
}

While the bulb is lit, the state machine enters on again, but not twice in a row: in between it takes the transition to check.

2.3.4.3 Splits and joins#

A split leads from one state into two or more states that are active side by side, each in a branch of its own. A join leads from such states back into one state.

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" { }
        STATE "bulb test" { }
        STATE "switch test" { }
        STATE "tested" { }
    }
    TRANSITIONS {
        SPLIT "off" -> "bulb test", "switch test" {
            CONDITION { EVENT("service", "test") }
        }
        JOIN "bulb test", "switch test" -> "tested" { }
    }
}

SPLIT "from" -> "a", "b", ... names two targets or more, each once. JOIN "a", "b", ... -> "to" names two sources or more, each once. Both take NOT LOOPING, a BREAKPOINT block and a CONDITION block like a TRANSITION. The runtime takes a split only while no branches are active, and a join only when each of its sources is active in a branch of its own; a join comes before the transitions of the branches. See 3.1 Execution semantics for the branches.

2.3.5 Events#

An event has a domain and a name, and it may carry a payload. The domain and the name are any strings: in the lamp, presses arrive in the domain switch and the smash in the domain service. Events come from the EVENT actions of state machines and from outside the runtime, see 3.4 HTTP API, 3.5 WebSocket and 4.7 Bridges.

The clause EVENT("domain", "name") holds when an event of this domain and name waits. The event that fires the transition is then in scope: the clauses after the EVENT clause, the state the transition leads to and the states inside it read its payload with paths that start with event, such as event->bright or $(event->bright). The event stays in scope while that state is active.

The payload of an event has the type of the same name in the event metamodel, see 2.1.7 Event definitions. The event dim of the lamp carries bright:

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "on" { }
        STATE "brighter" {
            ENTRY {
                SET("bulb->watts", EVAL { return $(bulb->watts) + 10 })
            }
        }
    }
    TRANSITIONS {
        TRANSITION "on" -> "brighter" {
            CONDITION {
                EVENT("switch", "dim")
                VALUE("event->bright")
            }
        }
        TRANSITION "brighter" -> "on" { }
    }
}

2.3.6 Macros#

A macro is a named piece of code with typed parameters. The block MACROS at the end of a state machine holds the macros, each written as MACRO "name" { ... } with these parts in this order:

  1. TAKES("parameter", type) for each parameter, none or more
  2. RETURNS(type), exactly once
  3. DEFINITION { EVAL { code } }, exactly once
TypeMeaning
"string", "number", "boolean"A primitive value.
"Type"An object of a type of the domain metamodel or of the event metamodel. As a result, a new object.
list("type")A list of values of the type.
reference("Type")Only in RETURNS: an object that is already part of the model.

The code reads a parameter as $(parameter), and a value of an object parameter as $(parameter->key). A macro that returns a new object returns a Python dictionary of its values, such as {"watts": 40}, see the example of 2.3.3.3 Action rules.

MACRO("name", "path", ...) calls a macro as the value of a rule or in a WITH block. Each argument is a path, and the macro gets the value at the path. A call passes one argument per TAKES. If it passes fewer, the runtime reads each missing one from the path named like its parameter. In the code of an EVAL, @name(arguments) calls a macro with values, see 2.3.3.5 EVAL code.

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "half" {
            ENTRY {
                SET("bulb->watts", MACRO("share", "bulb->maxWatts", "mode"))
            }
        }
    }
    TRANSITIONS { }
    MACROS {
        MACRO "share" {
            TAKES("full", "number")
            TAKES("mode", "string")
            RETURNS("number")
            DEFINITION {
                EVAL { return $(full) / 4 if $(mode) == "eco" else $(full) / 2 }
            }
        }
    }
}

2.3.7 Histories#

A history makes a state with inner states remember which of them was active when the state machine left it. When the state machine enters the state again, it goes on to the remembered state. SHALLOW HISTORY remembers the inner state directly in it, DEEP HISTORY the innermost state at any depth. The history is written after INITIAL and before STATE.

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        SHALLOW HISTORY STATE "on" {
            INITIAL STATE "full" { }
            STATE "dimmed" { }
        }
        STATE "off" { }
    }
    TRANSITIONS {
        TRANSITION "full" -> "dimmed" {
            CONDITION { EVENT("switch", "dim") }
        }
        TRANSITION "dimmed" -> "full" {
            CONDITION { EVENT("switch", "dim") }
        }
        TRANSITION "on" -> "off" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "off" -> "on" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

The lamp starts at full power. A lamp that was switched off while dimmed comes on dimmed again.

2.3.8 Tick limits#

A tick limit bounds how many ticks a state stays active. The block TICK LIMIT { ... } holds a delay, a timeout or both, in either order.

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" { }
        STATE "on" {
            TICK LIMIT {
                DELAY: 2 TICKS
                TIMEOUT: AFTER 20 TICKS TRANSITION TO "off"
            }
        }
    }
    TRANSITIONS {
        TRANSITION "off" -> "on" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "on" -> "off" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

DELAY: n TICKS keeps the state machine in the state until the state was active for more than n ticks. TIMEOUT: AFTER n TICKS TRANSITION TO "state" leads to the named state once the state was active for more than n ticks. Here the lamp stays on for more than two ticks before a press can switch it off, and without a press it goes off once it has been on for more than 20 ticks. A count is a whole number, and TICK and TICKS are read alike, so 1 TICK and 5 TICKS are both fine.

2.3.9 Breakpoints#

A breakpoint marks where the debugger of the IDE halts a run, see 4.6 Debugging. In a state, BREAKPOINT { ENTRY EXIT } halts when the state machine enters the state, when it leaves it, or both. In a transition, split or join, BREAKPOINT { START END } halts at the start of the transition, at its end, or both. A block names one of its two words or both, in either order. In a transition the block comes before the CONDITION block.

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" {
            BREAKPOINT { EXIT }
        }
        STATE "on" { }
    }
    TRANSITIONS {
        TRANSITION "off" -> "on" {
            BREAKPOINT { START END }
            CONDITION { EVENT("switch", "press") }
        }
    }
}

2.3.10 Optional features#

Five parts of KStates are optional features. A tool decides which of them a text may use. The IDE keeps this choice in the settings of a project, see 4.1 Projects. The library allows all of them unless it is told otherwise, see 2.5.6 Optional features.

FeatureIdConstructsThe problem is reported at
HistorieshistorySHALLOW HISTORY, DEEP HISTORYSHALLOW, DEEP
Tick limitstickLimitTICK LIMIT { ... }TICK
BreakpointsbreakpointsBREAKPOINT { ... } in states, transitions, splits and joinsBREAKPOINT
Macrosmacrosthe MACROS block and every MACRO(...) call, also in a WITH blockMACROS once for the block, MACRO of each call
Splits and joinsparallelSPLIT and JOINSPLIT, JOIN

When a feature is switched off, the text is still read as before, but each of its constructs is an error with the code kstates.feature-off. Switching a feature on again turns these errors off. An @name(...) call in EVAL code is not a construct of the feature macros.

At run time, histories, tick limits and breakpoints take effect only where the runtime has the matching feature switched on, see 3.2 Runtime features. Without it, the state machine runs as if they were not written. Dynamic attachment, see 2.3.11 State machine management and lifecycle, and pages, see 2.3.12 Pages, are no optional features: a text may always use fragments, container states, final states and DONE, and the runtime always understands them.

2.3.11 State machine management and lifecycle#

An attached state machine runs on one object that a run names by its key. That fits a lamp that exists from the start. It does not fit objects that come and go while the model runs, such as the spare bulbs of the room, which a state machine creates. For them a project writes attachable state machines and says in the model and in the actions which object gets which one.

Use the attached form, ATTACHED TO "Type", for the state machine of one known object, chosen when the project runs. Use the attachable form, "name" ATTACHABLE TO "Type", ..., for behaviour that many objects share, objects that exist from the start as well as objects that rules create. Each object gets an instance of its own, which starts in the initial state. List several types when the same behaviour fits objects of several types; every path of the state machine must then be valid from each of them.

behaves after "name" in the header of a KMeta type gives every object of the type an instance of the named state machine: each object of the model at the start of a run, and each object a rule creates. Use it for the usual behaviour of a type.

type "Bulb" "A light bulb that burns with watts, up to maxWatts" behaves after "glowing" {
    prop("maxWatts", "number")
    prop("watts", "number")
    prop("lit", "boolean")
}
type "Switch" "A wall switch" {
    prop("position", "string")
    prop("presses", list("string"))
}
type "Lamp" "A lamp with a bulb, wired to a switch" {
    prop("mode", "string")
    has("bulb", "Bulb")
    knows("control", "Switch")
}
type "Room" "The room the lamp stands in, with spare bulbs" {
    has("lamp", "Lamp")
    has("switch", "Switch")
    has("spares", list("Bulb"))
}

Every bulb glows while it has watts:

STATEMACHINE "glowing" ATTACHABLE TO "Bulb" {
    STATES {
        INITIAL STATE "dark" {
            ENTRY { SET("lit", "false") }
        }
        STATE "lit" {
            ENTRY { SET("lit", "true") }
        }
    }
    TRANSITIONS {
        TRANSITION "dark" -> "lit" {
            CONDITION { EVAL { return $(watts) > 0 } }
        }
        TRANSITION "lit" -> "dark" {
            CONDITION { EVAL { return $(watts) == 0 } }
        }
    }
}

A bulb that blinks switches its light on every tick:

STATEMACHINE "blinking" ATTACHABLE TO "Bulb" {
    STATES {
        INITIAL STATE "off" {
            ENTRY { SET("lit", "false") }
        }
        STATE "on" {
            ENTRY { SET("lit", "true") }
        }
    }
    TRANSITIONS {
        TRANSITION "off" -> "on" { }
        TRANSITION "on" -> "off" { }
    }
}

ATTACH name after a SETOBJ or APPENDOBJ on a has relation names the state machine of the object the rule creates, in place of the one its type behaves after. Use it when a created object should start with other behaviour than the usual one. EXCHANGE("path", name) ends the state machine of an object of the model and attaches an instance of the named one, which starts in its initial state. Use it to change the behaviour of an object that exists already. On an object without a state machine, EXCHANGE attaches the named one.

The state machine of the room adds a blinking spare bulb when the switch is pressed, and makes the bulb of the lamp blink on the next press:

STATEMACHINE ATTACHED TO "Room" {
    STATES {
        INITIAL STATE "waiting" { }
        STATE "stocked" {
            ENTRY {
                APPENDOBJ("self", "spares", MACRO("new bulb", "lamp->bulb->maxWatts")) ATTACH "blinking"
            }
        }
        STATE "party" {
            ENTRY {
                EXCHANGE("lamp->bulb", "blinking")
            }
        }
    }
    TRANSITIONS {
        TRANSITION "waiting" -> "stocked" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "stocked" -> "party" {
            CONDITION { EVENT("switch", "press") }
        }
    }
    MACROS {
        MACRO "new bulb" {
            TAKES("watts", "number")
            RETURNS("Bulb")
            DEFINITION {
                EVAL { return {"maxWatts": $(watts), "watts": $(watts)} }
            }
        }
    }
}

The name after ATTACH and the second operand of EXCHANGE are values in the three forms of 2.3.3.4 Values: a string is the name itself, and EVAL { return $(mode) } takes the name from the model, or from a WITH binding by its name. The verifier checks a name written as a string: that an attachable state machine of the project has it, and that the state machine lists the type of the object. A name that an EVAL or a MACRO computes is checked when the action runs. ATTACH on a knows relation is an error, since that relation links an object that exists already; EXCHANGE is the rule for such an object. 2.4 Checks lists the codes.

What happens at run time, when an instance starts, in which order the instances of a tick run, and what becomes of the state machine of an object that is removed, is described in 3.1.13 State machine management and lifecycle.

2.3.12 Pages#

A state machine grows long when it holds every step of a lamp, its self test included. Pages split it: a fragment holds a piece of behaviour, such as the self test, in a file of its own, and a container state of another state machine runs the fragment as its inner states. The state machine and the fragments it uses, directly or through other fragments, form a composition, which the library flattens into one state machine before it runs.

2.3.12.1 Fragments and final states#

A fragment starts with STATEMACHINE "name" FRAGMENT. It has no type: it runs on the object of the state machine that uses it, so its paths start at that object. Its body is that of every state machine: STATES, TRANSITIONS and MACROS. Exactly one of its states is INITIAL, and at least one state at its top level is a final state.

FINAL STATE "name" { } marks the end of the fragment. It stands only at the top level of a fragment, it has no actions, no inner states, no tick limit and no history, and it is never INITIAL. Its braces may hold a BREAKPOINT block and nothing else. No transition, split or join leaves a final state: the state machine stays in it until a transition of the container state leads out.

The fragment bulb test lights the bulb at half its power and passes once the bulb is lit, or fails on a smash:

STATEMACHINE "bulb test" FRAGMENT {
    STATES {
        INITIAL STATE "powered" {
            ENTRY {
                SET("bulb->watts", MACRO("half", "bulb->maxWatts"))
            }
        }
        FINAL STATE "passed" { }
        FINAL STATE "failed" { }
    }
    TRANSITIONS {
        TRANSITION "powered" -> "passed" {
            CONDITION { VALUE("bulb->lit") }
        }
        TRANSITION "powered" -> "failed" {
            CONDITION { EVENT("service", "smash") }
        }
    }
    MACROS {
        MACRO "half" {
            TAKES("watts", "number")
            RETURNS("number")
            DEFINITION {
                EVAL { return $(watts) / 2 }
            }
        }
    }
}

2.3.12.2 Container states and DONE#

CONTAINER STATE "name" USE "fragment" { } runs the named fragment. A container state has no ENTRY and no DO block and no inner states of its own, since its fragment does the work. Its braces may hold a BREAKPOINT block and a TICK LIMIT block, and it may be INITIAL and carry a history like any other state. It may stand at any depth: at the top level, inside another state and inside a fragment. A fragment never uses itself, neither directly nor through other fragments.

Entering a container state starts its fragment the way a state machine starts, see 2.3.2.2 The initial state: the state machine enters the marked state of the fragment and the states around it. A container state with a history enters the state it remembers instead, once it remembers one, see 2.3.7 Histories. While the fragment runs, the container state is active around it, so the transitions of the container state apply in every state of the fragment, as for a state with inner states. A transition that leaves the container state ends the fragment.

The clause DONE holds when the container state the transition leaves has reached a final state of its fragment. It takes no arguments and stands on a TRANSITION or SPLIT whose source is a container state:

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" { }
        CONTAINER STATE "self test" USE "bulb test" {
            TICK LIMIT {
                TIMEOUT: AFTER 50 TICKS TRANSITION TO "off"
            }
        }
        STATE "on" { }
    }
    TRANSITIONS {
        TRANSITION "off" -> "self test" {
            CONDITION { EVENT("service", "test") }
        }
        TRANSITION "self test" -> "on" {
            CONDITION { DONE }
        }
        TRANSITION "self test" -> "off" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

On a test event the lamp runs the bulb test. When the test has reached passed or failed, the lamp goes on. A press or 50 ticks end the test early. DONE does not tell the final states apart; a fragment that ends in several ways writes the outcome into the model in its states, and the transitions of the container state read it.

On a JOIN, DONE speaks of every source that is a container state and holds when each of them has reached a final state; sources that are no container states do not count for it. At least one source of the join is a container state. A split into two container states and a join when both are done run two fragments side by side:

STATEMACHINE "switch test" FRAGMENT {
    STATES {
        INITIAL STATE "waiting" { }
        FINAL STATE "pressed" { }
    }
    TRANSITIONS {
        TRANSITION "waiting" -> "pressed" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}
STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" { }
        CONTAINER STATE "bulb check" USE "bulb test" { }
        CONTAINER STATE "switch check" USE "switch test" { }
        STATE "checked" { }
    }
    TRANSITIONS {
        SPLIT "off" -> "bulb check", "switch check" {
            CONDITION { EVENT("service", "test") }
        }
        JOIN "bulb check", "switch check" -> "checked" {
            CONDITION { DONE }
        }
    }
}

2.3.12.3 Names#

The states and transitions of a file refer only to the states of that file. A file never names a state inside a fragment it uses, and a fragment never names a state of the state machine that uses it.

After flattening, a state of a fragment carries the name of its container state in front, with a slash: the state powered of the bulb test above runs as self test/powered. When a fragment uses a fragment again, the names nest, as in self test/wiring/powered. The trace of a run, the debugger and the runtime show these names. A fragment used by two container states runs as two copies, and nothing is shared between them; in the second lamp above the bulb test runs as bulb check/powered. A flattened name must not equal another state name of the composition, so a state name of a file that contains a slash may clash with one.

Fragments are found by their names alone. The fragments, the attachable state machines and their names form one name space in a project: no two of them have the same name, and the folders and file names of the texts play no part. ATTACH, EXCHANGE and behaves after name attachable state machines only, never a fragment.

2.3.12.4 Macros in a composition#

The macros of all files of a composition form one set, so a file may call a macro that another file of its composition defines. A macro of a fragment that runs twice is in the set once. Two macros of one name with different definitions cannot both be in the set, which is an error. A file is easier to read and to reuse when it defines the macros it calls: a call of a macro that only another file defines is a warning at the call.

The checks of a composition are in 2.4.5 KStates for a single file and in 2.4.6.5 Pages across files. What a container state, a final state and DONE do at run time is described in 3.1 Execution semantics.

2.3.13 Compound states and container states#

A compound state is a state with inner states written in its braces, see 2.3.2.1 Nesting. A container state runs the states of a fragment as its inner states, see 2.3.12 Pages. Both group states under an outer state whose transitions apply in each of them. They differ in where the inner states live and in how far the outer text can reach into them.

Compound stateContainer state with its fragment
Where the inner states are writtenIn the braces of the state, in the same file.In a fragment, a file of its own. Several container states may use one fragment, and each use runs a copy of it.
NamesOne name space for the whole file. Transitions cross the border of the state freely, into and out of any inner state.The file and the fragment each have their own name space. The using text cannot name a state of the fragment, and the fragment cannot name a state outside itself, so no transition crosses the border of the container state. After flattening, a state of the fragment is named with the name of the container state and a slash in front, see 2.3.12.3 Names.
The INITIAL markThe single mark of the file may stand on an inner state, and the state machine then starts inside the compound state.The fragment has a mark of its own, which the using text does not see. It decides where the fragment starts.
What a transition into the state entersThe state itself and none of its inner states.At once the start of the fragment, or the remembered state when the container state has a history that remembers one: a container state is never active without a state of its fragment inside it.
ActionsENTRY and DO blocks.None. The states of the fragment carry them.
FinishingNo final states and no DONE. A transition from an inner state leads out.The fragment ends in a FINAL STATE, and DONE on a transition from the container state holds once it has reached one, see 2.3.12.2 Container states and DONE.
LeavingA transition from the compound state leaves it from any of its inner states.A transition from the container state leaves it from any state of the fragment and ends the fragment.
HistoriesSHALLOW HISTORY and DEEP HISTORY remember the inner state, see 2.3.7 Histories.The same, for the states of the fragment. At run time the two differ in when the remembered state is entered, see 3.1.14.6 Histories, tick limits and breakpoints.
Tick limits and breakpointsAllowed, as on every state.Allowed on the container state. The states of the fragment have their own, and each copy of the fragment has its own states.
MacrosThe macros of the file.The macros of all files of the composition form one set, see 2.3.12.4 Macros in a composition. A file should call only the macros it defines itself.

The lamp below switches between full and dimmed light while it is on, and a dim in dimmed switches it off. Written with a compound state:

STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" { }
        STATE "on" {
            STATE "full" { }
            STATE "dimmed" { }
        }
    }
    TRANSITIONS {
        TRANSITION "off" -> "full" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "full" -> "dimmed" {
            CONDITION { EVENT("switch", "dim") }
        }
        TRANSITION "dimmed" -> "off" {
            CONDITION { EVENT("switch", "dim") }
        }
        TRANSITION "on" -> "off" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

Written with a container state, the light levels move into a fragment:

STATEMACHINE "fading" FRAGMENT {
    STATES {
        INITIAL STATE "full" { }
        STATE "dimmed" { }
        FINAL STATE "faded" { }
    }
    TRANSITIONS {
        TRANSITION "full" -> "dimmed" {
            CONDITION { EVENT("switch", "dim") }
        }
        TRANSITION "dimmed" -> "faded" {
            CONDITION { EVENT("switch", "dim") }
        }
    }
}
STATEMACHINE ATTACHED TO "Lamp" {
    STATES {
        INITIAL STATE "off" { }
        CONTAINER STATE "on" USE "fading" { }
    }
    TRANSITIONS {
        TRANSITION "off" -> "on" {
            CONDITION { EVENT("switch", "press") }
        }
        TRANSITION "on" -> "off" {
            CONDITION { DONE }
        }
        TRANSITION "on" -> "off" {
            CONDITION { EVENT("switch", "press") }
        }
    }
}

The compound state lets off lead straight into full and dimmed lead straight out to off. The container state cannot: the lamp enters on, which starts the fragment in on/full, and the fragment cannot name off, so it ends in its final state faded, and DONE leads out. This takes one more step at run time, see 3.1.14.5 Final states and DONE.

Which one to use: a compound state suits a group of states that belongs to one state machine and needs transitions across its border. A container state suits a piece of behaviour with a clear start and end that is long enough for a file of its own, or that several state machines or several places of one state machine run, such as a self test.

Source: this page on GitHub at commit 3b6029f, refreshed 16 November 2026. The whole reference as a PDF.