Skip to content

v0.8.0

Choose a tag to compare

@github-actions github-actions released this 30 Aug 19:41
· 111 commits to main since this release
25701a0

v0.8.0

A features round driven by the same real program as 0.7.0, this time reaching for
network play and a browser interface. Scoping those two produced nine issues
(#103 to #111), and reviewing the result produced a tenth (#118). All ten shipped.
The decisions behind each, including the roads not taken, are recorded in
ROADMAP.md items 13 to 22.

Async, end to end

An ->{async} extern must return Async. This is the release's one breaking
change. The async effect label was checked and propagated but never lowered, so
extern sleep: float ->{async} unit compiled to a call whose coroutine was
created and dropped, with only a RuntimeWarning to show for it. The checker now
rejects that declaration and names the working spelling:

error: `sleep` is declared `->{async}` but returns `unit`, which cannot be awaited:
an async Python function returns a coroutine, so declare the result as `Async unit`
(`… -> Async unit`) and bind it with `let!` inside an `async { }` block

The Async type is the one thing the lowering awaits; the label remains an
inferred, checkable fact (let pure over async work is still a compile error).

The Async module. The combinators that are awkward to type as externs
yourself, typed once over asyncio:

member type
Async.sleep float -> Async unit
Async.timeout float -> Async a -> Async (Option a)
Async.toThread (unit ->{e} a) ->{e} Async a
Async.parallel List (Async a) -> Async (List a)
Async.race List (Async a) -> Async a
Async.catch Async a -> Async (Result a Exception)

Async.catch is the await-time try: an async extern does not throw when
called, it returns a coroutine that throws when awaited, so try around the call
could only wrap the coroutine. catch turns a TimeoutError or a
ConnectionResetError raised at the await into the same Exception record try
builds, and lets CancelledError through so structured cancellation keeps
working. race cancels the losers, and racing an empty list raises
ValueError("Async.race needs at least one value") rather than waiting forever.

Structured concurrency. Every task is owned by a scope, the scope does not
return until its children finish, one failure cancels the siblings:

let session =
  Task.scope (fun scope ->
    async {
      Task.start scope (worker "a")
      Task.start scope (worker "b")
      return "both joined"
    })

Task.scope : (Scope ->{e} Async a) ->{e} Async a runs the body inside
async with asyncio.TaskGroup(); Task.start needs the Scope only
Task.scope hands out, so a start outside a scope is a missing argument at
compile time, and there is no cancel to forget.

Async self tail calls loop. A recursive async loop
(return! agentLoop inbox (count + 1)) used to await a fresh coroutine per
message on the same stack, so an agent died near message 1,000 with a
RecursionError. The self-tail-call rewrite now covers the async shape: the
tail calls rebind the parameters and go round a while True: inside the one
coroutine, so an agent that handles a message a second for a year is still on
its first stack frame. As with the sync rewrite, a refused case keeps its
recursive form and says why in a compiler note.

Computation expressions

A bare expression is an item. print reply, or a unit-typed match or
if, stands on its own line inside any builder; no more let _ = in front of
it. A block can also end in do! e or a plain call instead of return (),
which is what every fire-and-forget send wants.

for in every builder. The Python spelling, consistent with match e::

let squares = seq {
  for x in [1, 2, 3]:
    let y = x * x
    yield y
  yield 100
}

seq lowers it to Python's own for … in …: yield; in async it awaits once
per element; in result/option a failed step inside the loop short-circuits
the whole block; a user builder gets F#'s For as B.for_. A body on the same
line as the : is exactly one item, as in Python.

Derived codecs

A program that speaks to itself over a wire has the same type on both ends, so
the compiler derives the codec:

let wire = Encode.auto view
match Decode.decodeString Decode.auto wire:
  case Ok v: print (v == view)     # True
  case Error e: print e.errorMessage

Encode.auto : a -> string and Decode.auto : Decoder a cover records, sum
types, tuples, List, Set, Map, Option, Result, newtypes (erased, the
wire carries the underlying value) and recursion through them. The wire shape is
the internally tagged convention serde, Pydantic and System.Text.Json share:
records as objects, cases as {"type": "Move", "fields": ["K11 a QUIZ"]},
Option as null or the value, a Map with string keys as an object and any
other key type as a list of pairs. The derived decoder is a Decoder like any
other, strict like the primitives, so it composes with Decode.field, map2
and andThen. Decode.auto reads its type from where it is used; a site
nothing pins is a compile error naming the ways to pin it.

The browser

pyfun bundle game.pyfun -o site --page board.html

A static page that runs the program: the compiled Python (a single file or a
project's whole tree), any --asset files, and a loader that boots Pyodide from
its CDN and runs the entry with stdout and stderr on the page. No server; the
program is a shareable link. The page is reachable through Pyodide's js module
like any Python library, the interop cookbook's new browser/ entry is a typed
Dom façade with a counter page as its consumer, and a JS promise is awaitable
under Pyodide, so an extern over a JS async API is simply typed -> Async a.

Also in this release

  • The interop cookbook gains structured_concurrency.pyfun, an F#-style mailbox
    agent over asyncio.Queue living inside a Task.scope.
  • Lessons 12, 13, 18 and 20 cover callbacks across the boundary, for in
    blocks, the Async and Task modules, and derived codecs.
  • Html { class_ "board" } and other near-miss first lines in a builder block
    are diagnosed as "not a computation-expression item" instead of as a record
    literal missing its =.

Upgrading

pip install --upgrade pyfun-lang. One source change may be needed: an extern
declared ->{async} T for an async Python function becomes -> Async T, bound
with let! (or do!) inside an async { } block. Everything else is additive.