Reference › Handlers

Reference

Handlers: TypeScript, Python, the action language

A handler is a piece of a model's behaviour written as code: a function's body, a port's on-receive, a state's on-enter. You write it in TypeScript, in Python, or in the action language (```arche), which archec translates. TypeScript is what archec new writes.

A first handler#

Save this as main.arche. The project says its handlers are TypeScript. The pinger sends a numbered PING every 20 ms, and the ponger logs the ones after the first.

project "Ping" {
  handlers typescript
}

message PING { n: int32 }

component Pinger "Pinger" {
  out tx:   data sends PING
  var sent: int32 = 0
  states {
    state Idle
    state Busy {
      on-enter ```ts
        self.sent += 1
        send(self.tx, PING({ n: self.sent }))
      ```
    }
    Idle -> Busy on "after 10ms"
    Busy -> Idle on "after 10ms"
  }
}

component Ponger "Ponger" {
  in rx: data receives PING {
    on-receive ```ts
      if (msg.n > 1) log("got", msg.n)
    ```
  }
}

system Desk {
  part pinger: Pinger
  part ponger: Ponger
  pinger.tx -> ponger.rx
}
Diagram: Desk
What archec draws from this code: Desk
Try it

Run it in the browser simulator:

$ archec sim main.arche --for 30ms
Ping — system Desk, 30.000 ms simulated
    0.000 ms  pinger: Idle
   10.000 ms  pinger: Idle → Busy
   10.000 ms  pinger.tx → ponger.rx  PING {"n":1}
   20.000 ms  pinger: Busy → Idle
   30.000 ms  pinger: Idle → Busy
   30.000 ms  pinger.tx → ponger.rx  PING {"n":2}
   30.000 ms  ponger: got 2

2 message(s), 4 state change(s)
at 30.000 ms: pinger Busy

To have the same handlers in Python, convert them:

$ archec convert-handlers main.arche --to python
2 bodies, 3 statements translated, 0 left as TODO(convert)
✓ main.arche

The project now says handlers python, and the ponger's body reads:

if n > 1:
    log("got", n)

The rest of this page is the contract between archec and Arche's simulator. Both sides do what it says. For anything it does not say, do what the Python runtime does (Arche's arche_runtime.py), with the same names.

1. Which language a piece of code is in#

In arche-lang, the language is chosen at four levels:

  • The project says it: project { handlers typescript }, or python, or arche.
  • A component may say its own: component Legacy { handlers python }. Without one, a component takes, in this order:
    1. its definition's language;
    2. the language of the component around it;
    3. the language of its code files (code "ctrl.ts" is TypeScript, code "ctrl.py" is Python);
    4. the project's language.
  • A block says its own: ```ts, ```python, ```arche. A bare ``` block is in the component's language.
  • A project without handlers keeps the language its code is in. Python somewhere (a .py file, a ```python block or a bare block) makes it python. Otherwise it is typescript.

archec new writes handlers typescript. Use archec new --handlers python|arche for the others.

In the Arche project:

  • simulation.yaml says the project's language: behavioral: { language: typescript | python }. When it is absent, the language is python, so every existing project keeps working. archec writes it when the project says handlers, or when the project has code and that code is TypeScript.
  • A model file's code file decides the language of that file's code: code: "rfic.ts" is TypeScript, code: "rfic.py" is Python.
  • Inline code follows the component's code file when it has one, else the project's language. Inline code is activation bodies, handlers, state actions, and guards written as code.

The action language is translated:

  • for Arche, to the project's language. That is TypeScript, or Python in a handlers python project. handlers arche gives TypeScript.
  • for firmware, to C, Rust or Go, as before.

A call to another part is translated too. For example, brake.apply(2.5) goes through a port that requires an interface with that operation. It becomes what a handler writes for it: await component("brk").apply(2.5), for the part at the other end of the link (the specification).

archec copies every body into the Arche project, so Arche runs one language for the whole project. A code "x.ts" function becomes the inline body it would be written as. A block in the other language is reported (handlers-language): archec sim runs it, but Arche would not.

2. What TypeScript code looks like#

The source is TypeScript. Both sides remove the types and run the JavaScript. archec removes them itself (src/tscode.ts), so there is nothing to install. Arche uses a small transpiler in the page. Nothing is type-checked before it runs.

A code file mirrors a .py file one to one, with the same function names:

import { send, reply, goto, wait, ms, warn, u8 } from "arche"   // optional: the names are global anyway
import type { Rfic, SPI_FRAME } from "arche"                     // archec stubs: the model's types

export async function rfic_on_receive_spi(self: Rfic, msg: Rfic.Msg) {
  if (msg.name !== "SPI_FRAME" || (msg.cs !== self.cs_index && msg.cs !== RFIC_BROADCAST)) return
  self.frames += 1
  if (msg.cmd === 0) reply(SPI_FRAME({ cs: msg.cs, cmd: 0, addr: msg.addr, data: await self.readRegister(msg.addr) }))
  else await self.writeRegister(msg.addr, msg.data)
}
  • self. The first parameter is self, as in Python.
    • self.x reads and writes a variable.
    • self.STATUS.state is a port's state.
    • self.mem[...] is memory.
    • await self.f(a) calls a function of the component.
    • Only the owner writes its variables. This is the same rule as in Python.
  • A received message is a value, not bare names.
    • Python puts a message's fields in scope as bare names, and passes its name as message.
    • TypeScript passes one argument, msg. It is an object with the fields by name and the message's name: { name: "SPI_FRAME", cs, cmd, addr, data }.
    • In inline code, msg is in scope. message is in scope too, as the message's name (a string), for code moved from Python.
  • Inline code is the body of an async function. self is in scope, and msg too when a message triggered it: self.count += 1; await goto("Run").
  • Message constructors take one object: SPI_FRAME({ cs: 1, cmd: 0 }). This replaces Python's keyword arguments.
  • Enum literals and constants are global names, as in Python.

In a model, a code "ctrl.ts" file binds to the model as a .py file does. Each element takes the function with its conventional name:

Element Function in the file
fn main main
a state On on_enter_On and on_exit_On
a port rx on_receive_rx
a memory M on_write_M
on-enter name the function named

A function's parameters are self and the fn's arguments. For a message's hook they are self, msg. Other parameters are reported (py-params).

The constants, types and helper functions at the top of the file are copied into each body that uses them. Imports are only for the editor, and are dropped. Only "arche" and "./arche" may be imported: both name the model's arche.d.ts.

3. The API#

The API is a set of global names. They are the same as in arche_runtime.py.

Waits are awaited, as in Python:

wait(d), wait_until(test, timeout?), clock(n?), recv(port, timeout?), select(...ports) / select([ports], timeout), call(port, msg, to?, timeout?), goto(state), put/get/take(port, …), lock(port, timeout?), wait_bits(port, bits, { all, clear, timeout }), stream_write/stream_read, compute(d).

Immediate calls are not awaited:

  • messages and ports: send(port, msg, to?), reply(msg), give, unlock, set_bits, clear_bits, queued, start_timer, stop_timer, pulse(signal, width?), at(address), message(name), component(name);
  • output: log(...a), warn(...a), print(...a) (to the trace), fail(msg?);
  • time and chance: now(), rand(), randint(lo, hi), randn(mu?, sigma?). The engine seeds them. Never use Math.random or Date;
  • durations: ns/us/ms/sec(x), to_ms/to_us/to_s(t), fmt(t);
  • bits and integers: bits(v, hi, lo?), bit(v, n), setbits(v, hi, lo, x), u8/u16/u32/u64/i8/i16/i32/i64(n).

Python's with locked(p): is await lock(p); try { … } finally { unlock(p) }. Math.* is allowed, except Math.random.

The rules are the same as in Python:

  • Determinism. Stepping back runs the code again, and it must give the same result.
  • Runaway loops. Loop turns are counted. Past the same limit, it is an error.

4. Where it runs, and types#

  • Arche runs it in a JsRuntime (Lang = 'python' | 'typescript') in a Web Worker, with no DOM and no network. The engine owns time and state. It uses the same host-call protocol as the Python bridge. Pyodide is loaded only when the project has Python code.

  • archec sim (src/websim.ts, src/websimrt.ts) runs the JavaScript directly, with the same API. It runs in node, in the page archec sim --html writes, in the live page, and in VS Code's ▶ panel.

  • archec stubs writes arche.d.ts in .arche/typings, in the folder of the main file. It writes Python's arche package in the same place. The file holds:

    • the API's signatures;
    • an interface per message, with name;
    • a type per component: its variables, ports and functions, its states as a string union, and a Msg union of what it receives;
    • the constants and the enums.

    Nothing is written beside the code, and there is no tsconfig.json. In VS Code, the extension writes the file on its own, and its TypeScript plugin makes "arche" and the global names resolve to it (see editor.md). For tsc on the command line, add two lines to your tsconfig.json; archec stubs prints them:

    {
      "compilerOptions": { "paths": { "arche": ["./.arche/typings/arche.d.ts"] } },
      "include": ["*.ts", ".arche/typings/arche.d.ts"]
    }

    A paths entry maps "arche", not "./arche": import from "arche" in files that tsc checks. archec stubs --beside writes arche.d.ts and a tsconfig.json beside the .ts files instead, as earlier versions did.

5. Test plans and guards#

Arche runs a test plan's code in the project's language. That code is a step's do and expect, a setup, or a stimulus. In arche-lang you write it in Python, as before. In a TypeScript project, archec writes it to Arche as TypeScript (src/testcode.ts):

Written Arche runs
abs(c.x) < 0.1 and not c.done Math.abs(c.x) < 0.1 && !(c.done)
send(rx.frames, RC_FRAME(throttle=1200, arm=True)) send(rx.frames, RC_FRAME({ throttle: 1200, arm: true }))
x is None, min, max, round, int, len(xs) x === null, Math.min, Math.max, Math.round, Math.trunc, (xs).length
pass, # note nothing, // note
if c: / elif / else: / while c: / for i in range(n): / for x in xs: the same in braces
  • The prefix of an expectation (within 5ms:, never:, always:) stays as it is.
  • What already reads as TypeScript (a && b, GO({ n: 1 })) is left as it is. A ```ts block is written as it is.
  • Some Python has no simple TypeScript: a if c else b, in, //, a def, with, try, an f-string, a lambda. It is reported (test-typescript). Write it another way, or in a ```ts block.

A transition's guard and action are written the same way in a TypeScript project. [abs(angle) > FALLEN] reaches Arche as Math.abs(angle) > FALLEN. The trigger's fields are in scope by name, in either language.

In archec#

What How
Write the language project { handlers typescript }, component c { handlers python }
Move blocks to a file archec fmt --extract-code=behaviour.ts --write main.arche (or --extract-code alone: one file per component, in its language)
The editor's types archec stubs main.arche → .arche/typings/arche.d.ts (and the arche package when there is Python)
Run it archec sim main.arche (--html, --plant, --batch, --test), archec difftest
Check it archec check: each TypeScript syntax error on its line (ts)
Change the language archec convert-handlers main.arche --to typescript|python|arche [--component C] [--dry-run]

Limits#

What archec sim runs of the API:

  • the waits wait, compute, goto, and the part's own functions;
  • send, reply (on the port the message came in by), log, print, warn, fail, now;
  • the seeded rand, randint, randn;
  • the durations, fmt, the bit helpers, the integer casts, message(name).

What it does not run:

  • recv, select, call, put/get/take, lock, the bits, streams and timers, wait_until, clock, pulse, at, component. Each one stops the body with an error that says Arche's simulator runs it.
  • Math.random and Date. They are errors too, because a run must replay.
  • A port handle's state. It does not exist in archec sim.

TypeScript that does not read:

  • an enum or a namespace. They have no JavaScript of their own. Use a union of strings, or the model's enum.
  • a constructor's public x parameter.
  • an async arrow function, in archec sim. Write an async function instead.

A message with no fields, such as message GO: bool, is { name, value }.

Portable TypeScript#

The simulators run any TypeScript. The generators do not. archec gen --target c|embassy|go and archec difftest translate only what the action language can say, as they do for ```arche. A TypeScript body that keeps to this subset is read into the action language's tree. Then the C, Rust or Go is written from that tree.

The subset:

TypeScript The action language
let x = e, const x = e (a value given) var x = e
self.x = e, +=, -=, *=, /=, self.n++, --k x = e, n += 1, k -= 1
if (c) … else if (c) … else …, while (c) { } if, while
for (let i = a; i < b; i++) (or i <= b, i += 1) for i in a..b
send(self.p, MSG({ k: v })), MSG(), { k } send p MSG { k: v }
await goto("Run"), await wait(ms(2)), wait(ms(self.t)) goto Run, wait 2ms, wait t * 1ms
log(…), print(…) log …
await self.f(a) f(a), the part's function
msg.distance, msg.name distance, message (the received message's fields)
self.state === "Idle" state == Idle
=== !== < <= > >= + - * / % && || !, x ** 2 == != … and or not, x * x
Math.abs min max sqrt sin cos atan2, Math.trunc(x), Number(x), Math.PI abs …, int(x), float(x), a literal
now(), to_s(t), to_ms(t), ns/us/ms/sec(x) the same
return, break, continue, numbers, strings, true, false, constants, Color.Red the same

Then the action language's check runs. The body stays out of the subset if it has a name the check does not know, a type that does not fit, or a division of two integers. (TypeScript divides integers as floats.)

These are outside the subset: an array or an index (the action language has them, buf[i]; TypeScript's are not read into it), a ternary, a template string, a method of a value (list.push), a helper function, reply, recv, a bit operator, switch, try. Such a body still runs in the simulators as it is. The generators write a TODO with the TypeScript in its place, as they do for Python they cannot translate. archec check names the construct (ts-portable). It is info in a project that only simulates, and a warning when a deployment generates code for the component.

A port's on-receive in TypeScript may read its message (msg.distance). In C it gets the message as <part>_on_receive_<port>(self, const void *arche_msg), with its fields by name. A transition's guards and actions get theirs the same way. A guard written in TypeScript ([msg.force > 0]) is translated the same way too. So archec difftest compares the TypeScript the simulator runs with the C it becomes. examples/ts-handlers agrees.

Converting#

archec convert-handlers main.arche --to typescript|python|arche rewrites the model's handlers in another language, in place. It rewrites:

  • each ``` block, keeping its fence and indentation;
  • each code file. code "ctrl.py" becomes "ctrl.ts". The old file is kept; remove it when you are done. To arche, each function becomes a ```arche block on its element;
  • the transitions' guards;
  • handlers on the project, or on the component with --component Ctrl.

How each language is read:

  • From ```arche: exact, by the same translators that make Arche's copy.
  • From Python: statement by statement, through what the action language says. This is the same reading the generators use for Python.
  • From TypeScript: statement by statement, through the portable subset above.
  • A received message: Python's bare field names (distance) become TypeScript's msg.distance, and Python's message becomes msg.name. The action language has no message in a body, so a statement that reads one stays a TODO.

What happens to the rest:

  • A statement that does not translate stays as a comment with the original: // TODO(convert): <python>, or # TODO(convert): <ts> in Python. The command lists each one with the reason. archec check reports it (convert-todo) until you write it.
  • Comments between statements are kept. A comment at the end of a line, or inside a nested block, is not.
  • Nothing is written when the result has more errors than the model. --dry-run only says what would change.

Converting keeps the meaning, not the text. clamp(x, a, b) comes back from TypeScript as min(max(x, a), b), and a - b + (c - d) as a - b + c - d.

Diagnostics#

Code
handlers handlers names no handler language
handlers-language code in another language than the one Arche runs the project in
code-language a ``` block of a language that is not a handler language
ts TypeScript that does not read, has no JavaScript, imports a module, or keeps state at the top of a file
ts-portable a TypeScript body outside the portable subset: the construct; the generators write a TODO
convert-todo a statement archec convert-handlers left as a TODO(convert): comment
py-params, py-not-found, py-unused, code-not-found as for .py files
test-typescript test code in a TypeScript project that archec cannot write as TypeScript (§5)