Repository navigation
Releases
v0.11.0
Pyfun 0.11.0
This release follows a review of the whole language. Its spelling now matches Python wherever the two say the same thing, so a 0.10 program needs some renaming. Every old spelling is an error that names the new one, and one run of pyfun check reports every one of them in every module, each with its file and line, so the compiler walks you through the change. The upgrading guide lists every change with its 0.10 and 0.11 spelling side by side.
Breaking changes
- Booleans are
TrueandFalse.trueandfalseare answered with "Pyfun spells thisTrue, as Python does". - The string type is
str.stringin a type is an error that says so.Decode.stringisDecode.str. TheStringmodule keeps its name. - Every name is snake_case. 67 standard library names change (
List.sort_by,Map.of_list,Option.with_default,String.starts_with), along withString.lstripandrstripfortrimStartandtrimEnd, the builder methodsreturn_fromandyield_from, and theExceptionfieldserror_kindanderror_message. Each old spelling is answered with the new one ("did you meanList.sort_by?"). - Lookups carry no
tryprefix.Map.tryFindisMap.findandString.tryIndexOfisString.index_of. - An
ifbranch on its own lines opens with:. Writeif cond:,elif cond:andelse:for indented branches, as in Python.thenis for a branch on the same line. The spelling is the same inside parentheses and a builder's braces (async { },result { }), where the branch is one expression. - A multi-word module is a snake_case file.
import TrainTimesreadstrain_times.pyfun. inis a keyword (seeinandnot inbelow), so it can no longer name a value.Json,JNull,JBool,JInt,JFloat,JStr,JListandJObjectare built in (see JSON as data below). A program that declares a type or constructor by one of these names is told the name is taken.- A constructor and a record type cannot share a name. Both became one Python class and the program failed when it ran. It is now an error at the declaration.
- A name is used below the line that writes it. The one forward reference is between mutually recursive functions. A value written between two of them cannot call them (
let early = is_even 4betweenis_evenandis_oddfailed with aNameErrorwhen the program ran), and a function written between them reads the one above it. Both are compile errors that name the line to move. - A forward reference says what it is. A name that is written further down the file gets "
helpercannot be used yet: it is defined below this line" where it gotunbound name. Tools that read the compiler's messages will see the new text. - A local accumulator is pure. A
let mutassigned in the function that declares it no longer counts asio, solet pureaccepts the accumulator style. One corner breaks: a function that wasioonly through its own accumulator no longer fits a callback arrow declared->{io}. In anextern, declare the arrow->{e}. - A name beginning
_pf_is the compiler's. It writes such names into the Python it emits, so one in source is an error. - More names gain a trailing underscore in the Python. A binding called
min,max,all,any,enumerate,formatorgetattr, or by the name of a module the compiler imports for itself (json,functools,itertools,asyncio), is emitted asmax_,json_, aslenandsumalready were. A constructor calledValueError,RuntimeErrororTimeoutErroris the classValueError_. Python code that imports a compiled module sees the new names. - A doc comment touches its declaration. Only the
##lines directly above a declaration document it. A##block set apart by a blank line, such as a section banner, is an ordinary comment. - Every diagnostic names its file. The location line reads
--> shapes.pyfun:3:9, which a terminal or an editor opens. Tools that read the compiler's messages will see the new form. - Types are displayed as they are written. A type variable prints as
a(it printed'a), and constraints are shown in front:comparison a => a -> a -> bool. Tools that read the compiler's messages will see the new text.
The language
- Map and Set literals.
{"a": 1}is aMap,{1, 2}aSet, and{}the emptyMap, as Python writes them. inandnot in.2 in xs,x not in {1, 2},"Ada" in ages,"ell" in "hello": an element of aList,SetorSeq, a key of aMap, a substring of astr. A helper written with it is polymorphic in what it searches (let has x xs = x in xs).- Constructors can name their fields.
type Shape = Circle { radius: float } | Rect { width: float, height: float }. A named constructor is builtRect { width = 2.0, height = 3.0 }and matchedcase Rect { width, height }:. A field every constructor declares at the same type is read and updated on the whole value. From Python the fields have their names (rect.width). - A field name alone builds the field.
Rect { width, height }isRect { width = width, height = height }, the shorthand a pattern already had, for a record and for a named constructor. - A sole constructor unpacks where it is bound.
let unwrap (Wrap v) = vandlet raw (UserId s) = sbind in a parameter, alet, a lambda and alet!when the type has no other constructor. - A constructor takes a map or set literal.
JObject {"id": JInt 1}andSome {1, 2}need no parentheses. from Geometry import area, Circle. The listed names are written bare, as in Python. The module itself is not bound, and there is no*.- Packages.
import Shapes.Geometryreadsshapes/geometry.pyfun, and the code then saysGeometry.area. The top of a project is the folder of the file you run. The Python that comes out isshapes/geometry.pyin a regular package. - The
exneffect label. Anexterncan say that it may raise (->{exn},->{io, exn}). The label is inferred through its callers andtrydischarges it, so a signature can show, andlet purecan require, that a function does not raise. Existing externs are typed as before. - Python habits are answered with the Pyfun form.
x = 5,x += 1,forandwhile,class,import math,lambda x:,xs[0],s.upper(),f(a, b),a if c else b, a{x:.2f}format spec, an annotation on alet, and members called by another language's word (Map.get,List.append) each get an error that says what to write. - Warnings. A
casethat can never match, a localletnothing reads (name it_xto say that is intended), an unusedimport, and a top-level name bound twice. A warning never stops a build, andpyfun check --strictmakes one a failure for CI.
JSON
Decode.dictandDecode.index.Decode.dict decreads a JSON object whose keys are data into aMap, in the object's order.Decode.index i decreads one position of an array, for arrays whose positions each mean something else ([1, [4, "10"]]).- JSON as data.
Decode.valuereads any JSON as the built-inJsontype,JNull | JBool bool | JInt int | JFloat float | JStr str | JList (List Json) | JObject (Map str Json). A program matches on it, builds it and changes it like its own sum types, andEncode.valuewrites it back with ints, floats and key order as they came. AJsonfield inside a derived codec travels as it is.
Tools
pyfun test. Atest_*function in atest_*.pyfunfile is a test, run by pytest.Test.equal expected actual,Test.is_true conditionandTest.fail messagesay what it expects and becomeassert, so pytest shows its own diff. Each performsexn, so a helper shared by tests may assert and its type says so. A failure is reported at its.pyfunline with the Pyfun statement, and its id (test_shapes.pyfun::test_rect) runs that test again.pip install "pyfun-lang[test]"brings pytest.- One run reports every syntax error.
check,compileandrunprint every lex and parse error of a file and of every module of a project. A wrong declaration is one error however often it is used: its uses, in its own module and in the modules that import it, are not reported again. Inside a declaration, a name that is not there (an old library name, a field spelled the 0.10 way) does not stop the checking, so every one of them arrives in the same run. pyfun fmt. Formats a file's spacing and indentation in place and keeps every line break and comment. A leading-comma list keeps its columns ([ aover, b, a comma under the{ofCell {, an argument one step in from its constructor), and anelseset under itsifstays there.pyfun fmt --checkreports for CI.- Tracebacks in
.pyfunlines. When a program fails as it runs, each frame names the source file, the line and the statement, underpyfun run, in the REPL and in a notebook.PYFUN_TRACEBACK=pythonshows Python's own traceback over the emitted code. - Typed output.
pyfun compile --typedwrites the inferred types into the emitted Python as annotations a type checker reads:def pair[A, B](x: A, y: B) -> tuple[A, B],type Shape = Circle | Rect. A parameter searched withinis aContainer, and anexterna project binds carries its declared type. A project compiled this way carriespy.typed, andmypy .over it is clean but for two idioms inside a function body thatDESIGN.md§5.7 names. - Doc comments are docstrings. A
##comment above a function or a record is its docstring in the emitted Python, sohelp(area)shows it.
In the editor
- Inlay hints. Each binding's inferred type is shown beside it, the way Python annotates:
total: intafter a value,-> floatahead of a function's=. - Signature help. While a call's arg...
v0.10.0
Pyfun 0.10.0
async { } now behaves like F#'s async: nothing runs until it is awaited, and every await is a
fresh run. Native builds are checked against plain runs on every change, and the compiler answers
more Python habits with the Pyfun spelling. One change breaks Python code that runs a Pyfun async
value directly, so this is a minor release.
Breaking
-
An
Asyncvalue is cold. Building one runs nothing, and every await is a fresh run, as in
F#'sasync:let roll = async { print "rolling" return 6 } let twice = async { let! a = roll let! b = roll return a + b }twiceprintsrollingtwo times and returns12. Before, the secondlet!raised
RuntimeError: cannot reuse already awaited coroutine, andAsync.parallel [roll, roll]ran
rollonce.Nothing starts before it is awaited, and that changes one pattern. An extern over a Python call
that starts work as soon as it is called (a call returning anasyncioTask, or a browserfetch
promise under Pyodide) used to overlap when written like this:let a = fetch url1 let b = fetch url2 let! x = a let! y = bNow
bstarts only afterafinishes, and awaiting one value twice makes the request twice.
Nothing fails, it is just slower. To overlap requests, hand them toAsync.paralleltogether:
let! pages = Async.parallel [fetch url1, fetch url2].Python code handed a Pyfun
Asyncnow receives an
awaitable rather than a coroutine: it can await it any number of times, or call it for a fresh
coroutine as it would anasync def. To migrate, writeasyncio.run(job())where Python ran a
Pyfun value withasyncio.run(job)(Python 3.14 accepts either; 3.12 and 3.13 need the call).
Async callbacks handed to Python, such as anasyncio.start_serverhandler, are adapted so
Python receives real coroutines. (#177)
Fixed
==in a native build. A sum type the program compares with<gavefalsefor
Some 1 == Some 1once mypyc compiled it, and<=/>=stopped the build. (#172)- A native build of an async self tail call failed to compile on Linux and crashed on Windows
(a mypyc bug, python/mypy#22221). (#174, and #177 removes the shape altogether) - A multi-line string in a file saved on Windows carried a carriage return before every
newline. A line break in a string is now\nwhatever the file's line endings, as in Python.
(#182) - A file named like
01-intro.pyfunbuilds natively. (#172) pip install mypy setuptoolsis the install line for native builds: a fresh Python 3.12+
venv has nosetuptools, which mypyc needs. (#172)
Improved
- Errors that answer the Python habit:
def area w h = …says to writelet area w h = …;
an unboundlen,str,sumand eleven other builtins name their Pyfun spelling;&&and||
sayandandor; and[1, 2] + [3]points atList.concat xs ys. (#164, #168, #175, #176) - A callback that misses an extern's closed arrow points at
->{e}. Handing anasync { }
handler toextern serve: (Reader -> Writer -> Async unit) -> …used to fail with "effect mismatch:
cannot unify …" under the whole call. It now says what the handler performs, what the extern's
arrow allows, and to write the arrow as->{e}, rather than pasting in the handler's own
effects, which would accept only handlers doing exactly that. (#181, found by a real
program, #180) - Native builds are checked on every PR against plain runs of every lesson program and
example. (#172)
Thanks
To @PandaHUN777 for the &&/|| and list-concatenation hints (#164, #168).
Upgrading
pip install --upgrade pyfun-lang. Python code that runs a Pyfun async value with
asyncio.run(job) should call it, asyncio.run(job()).
v0.9.0
Pyfun 0.9.0
Native builds through mypyc, façade packages, and clearer errors for habits carried over from
Python. Two changes break code, so this is a minor release.
Breaking
-
Task.scopeandTask.startlose theScopeargument. Starting a task is now an effect,
spawn, andTask.scopeis the only thing that handles it:let session = Task.scope (async { Task.start (worker "a") Task.start (worker "b") return "both joined" })Task.start : Async unit ->{spawn} unitandTask.scope : Async a -> Async a. A function that
starts tasks carries->{spawn}in its type and can be called inside any scope's body. Starting a
task anywhere else is a compile error ("this starts a task outside anyTask.scope, so nothing
would own it"). To migrate, drop thescopeparameter and argument and pass the async body
straight toTask.scope. A real 11-module program needed four changed lines. (#147) -
A capitalized
letname is an error.let Some x = Some 1used to define a function called
Some. It now says the name reads as a constructor and points you atmatch. (#130)
New
-
Native builds.
pyfun build --native prog.pyfun -o outcompiles a program with
mypyc, and the result runs aspython out. It needs
pip install mypy setuptoolsand a C compiler. In native mode everymatchbecomes anif/isinstance
ladder, and functions and module-level values are annotated from their inferred types. On the
repository's benchmarks the mypyc build runs 1.3x to 13x faster than the plain Python output, and
the integer-arithmetic benchmark runs about 12x faster than hand-written Python. Multi-module
projects work too: a real 11-module program compiles whole, and its move generator runs about
1.5x faster.pyfun compile --nativealone also speeds up match-heavy code on plain CPython.
(#149, #151–#159, #161, #163, #166, #167) -
Façade packages.
pyfun add <package>installs a pip package that ships typedextern
declarations, copies them into your project, and records it in a newpyfun.toml.
pyfun installrestores every listed package on another machine, andpyfun removedrops one.
import Namefinds the vendored module after your own files. There's an example façade in
examples/facades/pyfun-textwrap. (#150, #152) -
Every lesson as a Jupyter notebook, in
docs/src/notebooks/, and the educator pack as a
printable PDF at/educators/educator-pack.pdf. (#143, #144) -
Editors: Helix indentation and textobjects; a Sublime Text package (
editors/sublime);
cross-file find-references and rename for type names in every LSP editor. (#141, #146, #132)
Improved
- Errors that answer the Python habit.
returnoutside a computation expression now says that
a function's value is its last expression, so you can dropreturn(#148), and"-" * 20points
you atString.repeat count string(#169). - Typed holes name what you asked for. A hole's
try:list puts a fit whose name matches the
hole first (?uppersuggestsString.upperfirst) and keeps prelude order instead of
alphabetical (#131). Both thetry:andor:lists end withand N morewhen they are cut, so
you can tell a shortlist from the whole set (#131, #165). - The Jupyter kernel runs async code.
asyncio.runworks in a cell, since the cell runs off the
kernel's own event loop, and a cell starting with:resetbegins a fresh session. (#143)
Fixed
- A top-level fold could overwrite a top-level binding.
let x = 100followed by a
List.fold (fun acc x -> …)at the top level leftxholding the last element, because the
inlined loop's variable was a module global. (#142)
Known issue
- In a native build,
==on anOptionor on a type whose values are also compared with<
can be wrong. mypyc compilesSome 1 == Some 1to an identity check when the class also
defines ordering, so it givesfalse. Plainpyfun runandpyfun compileare unaffected, and
so areSetandMap. The next release fixes it.
Thanks
To @PandaHUN777 and @amandeavor for the first outside contributions (#148, #165, #169).
Upgrading
pip install --upgrade pyfun-lang. Code that uses Task.scope needs the migration above, and a
capitalized let name needs renaming or rewriting as a match. Everything else is additive.
v0.8.1
Pyfun 0.8.1
A bugfix release. Both fixes came from a dogfooding round on a real Pyfun program (a Scrabble game
with an async spectator mode) built against 0.8.0.
Fixed
-
A module
mutassigned insideasync/seq/resultsilently bound a local instead of the
module binding. Every built-in computation expression lowers its body to its own nested Python
function (a coroutine forasync, a generator forseq, and so on), but that nested function was
missing theglobal/nonlocaldeclarations that ordinary function bodies get for capturedmut
assignments. The result: a flag flipped from inside anasync { }block never actually flipped,
with no error — the assignment just bound a fresh local that was thrown away.result {}'s
read-modify-write form hit the louderUnboundLocalErrorversion of the same bug. All four
built-in CE forms now get the same capture analysis as function bodies. (#122) -
A
unitparameter did not erase consistently across an extern's parameter list. A leading
unitbefore real parameters split the call in two instead of dropping
(unit -> int -> int = absapplied tomyAbs () (-5)emittedabs()(-5), calling the result of
abs()), and aunitin the middle of a parameter list was passed through as PythonNone
instead of vanishing (int -> unit -> int -> intemittedmax(3, None, 5)). The rule is now one
rule: aunitparameter contributes no argument, wherever it sits. Partial application of a
unit-slotted extern now closes over a lambda rather thanfunctools.partial(which cannot drop an
argument that has not arrived yet), and the fix reaches receiver methods, kwarg-slot externs, and
bare references the same way. (#123)
Breaking
- An extern's mid-list
unitargument no longer arrives as PythonNoneon the other side of the
boundary — it is dropped from the call entirely, matching how a leading/trailingunitalready
behaved. This only affects an extern binding that both declares a non-leadingunitparameter and
relies on the Python callee actually receivingNonethere; nothing in the standard library or
examples depended on the old behavior.
v0.8.0
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 overasyncio.Queueliving inside aTask.scope. - Lessons 12, 13, 18 and 20 cover callbacks across the boundary,
forin
blocks, theAsyncandTaskmodules, 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.
v0.7.0
v0.7.0
A performance round driven by a real program: a Scrabble move generator that asks
Option questions millions of times per position. Its author hand-edited the
emitted Python to find where the time went, and each edit became a change to the
compiler. Along the way the same program turned up four cases where pyfun check
accepted a program that then failed at runtime, and all four are fixed.
Faster emitted Python
Each of these changes only what the compiler emits. Programs compile unchanged
and produce the same output.
Option and Result matches are if/isinstance ladders (#87). A match
on an Option or Result used to lower to a Python match statement with
class patterns and an unreachable case _: raise arm. It now lowers to what a
person writes:
if isinstance(o, Some):
x = o._0
return x
else:
return 0User-defined types keep match/case.
Nullary constructors are singletons (#89). A case with no fields
(Across in type Dir = Across | Down, and the prelude's None) is built once
at module level and referenced by name (_Across, _None_) instead of being
constructed at every use. Equality between two nullary values is an identity
check. Constructing through the class by hand still works and still compares
equal.
A match that consumes a lookup on the spot skips the Option (#88).
match Map.tryFind k m: with Some v/None arms lowers to
if k in m: v = m[k] …; List.head and List.get do the same. The
Option-returning helper stays for every other use.
Equality searches use the list's own methods (#86).
List.findIndex ((==) x) xs lowers to xs.index(x) under a try,
List.exists ((==) x) xs to x in xs, and List.find ((==) x) to the same
scan, instead of a Python-level loop over a fresh lambda.
A fold that destructures its element is linear (#85). The in-place fold
pass rejected List.fold (fun m (p, l) -> Map.add p l m) Map.empty pairs and
fell back to a copy-per-step reduce, which is quadratic. The element parameter
may now be any irrefutable pattern and emits Python's own
for (p, l) in pairs: header. On the program's 267,751-word automaton build
this is the difference between 1.85 seconds and not finishing.
Every emitted class uses __slots__. ADT cases, records and the prelude's
Some/Ok/Error are declared with @dataclass(frozen=True, slots=True),
so construction and field access are cheaper. This is the one change a Python
caller can notice: vars(instance) and instance.__dict__ no longer exist.
dataclasses.asdict, dataclasses.replace, equality, hashing and ordering are
unchanged.
Measured on the program that drove the round: move generation 1.29x faster
overall (9.84s to 7.63s on its slowest rack), and scoring 8% faster without
being the target, because it uses Option and Map.tryFind too.
Fixed
Four programs that passed pyfun check and failed at runtime. All are the
same kind of gap: the checker knew what the program meant and the lowering
lost it.
A block-local function applied to fewer arguments than it takes is a partial
application (#84). let pair a b = a + b inside a function, then
List.map (pair 10) ys, was emitted as a full call pair(10) and died with a
TypeError. Local functions now carry their arity like top-level ones do, so
this emits functools.partial(pair, 10) and over-application applies the
remainder one argument at a time.
A match-arm capture no longer rebinds a same-named binding for the rest of
the function (#92, #97). Python locals are function-wide; Pyfun's are
lexically scoped. case Some pair: pair in a function that also has a local
def pair used to overwrite it, so a later pair r 1 called an integer. The
compiler now emits such a capture as _pair and every reference follows. The
rename fires only when a reference outside the arm reads a binding that is live
across it, so ordinary code (case Ok x: … case Error x: …, the same capture
name in successive matches) keeps its names and its output is unchanged.
A let in a nested block no longer rebinds the enclosing binding (#96).
let x = 10 inside an if branch or a match arm overwrote the function's
x = 1, so x + y after the branch used 10. Same rule, same _x spelling,
same "only when it matters".
A let that shadows an outer name read earlier in the same function no
longer raises UnboundLocalError (#99). Inside a nested function, let y = x + 1 followed by let x = 2 made Python treat x as local for the whole
function, and the first line failed. This covers let/let! inside option,
result, seq and async blocks too.
Upgrading
pip install --upgrade pyfun-lang. No source changes are needed. If Python
code on your side reads vars() or __dict__ of a Pyfun value, switch to
dataclasses.asdict or attribute access.
v0.6.0
v0.6.0
Four bugs found while writing ordinary Pyfun programs, and the two of them that
needed a semantic change brought a breaking change with it. Types now cross
module boundaries as completely as values already did, and a misplaced line
inside a computation expression says so where it happens.
Breaking changes
Pyfun is below 1.0 and changes the language when a rule turns out to be wrong.
Both changes below reject code that 0.5.0 accepted, and both replace silence or
a misleading message with an accurate one.
A local type may no longer share a name with an imported extern type.
An extern type now crosses module boundaries, so a consumer that declares its
own type of the same name gets an import clash. In 0.5.0 the opaque type did not
cross at all and the two nominal types were quietly treated as one. Rename either
type to fix it.
Inside a computation expression, an argument line may not open left of the
expression it continues. This is rejected:
result {
let! x = Option.toResult "bad"
(String.toInt n)
return x
}
Indent the argument past the start of Option.toResult, or put the whole
expression on its own lines below let! x =. In 0.5.0 the layout parsed, and a
statement written the same way was swallowed as arguments and surfaced as a type
error on the line above naming a type nobody wrote.
Fixed
An extern type can be named across a module boundary (#72). A module's
interface carries its opaque handle types, so Gen.Rng can be written in a
record field, an ADT payload, or an extern signature. Values of the type always
crossed; now the name does too. The workaround of wrapping the type in a record
just to have a name another module may say is no longer needed.
A record reached through another module's exports has its fields (#75).
Interfaces close over what they reference: a record or opaque type mentioned by
an exported scheme, constructor, or record field is carried along, tagged with
the module that declares it, through as many hops as it takes. A third module can
hold a value, read its fields, and name its type without importing the module two
steps away.
A carried type crosses as an identity rather than as a member. Constructing it,
pattern matching it, or writing its qualified name still asks for a direct
import, and the error says which module to import. For field lookup on a value
whose type is not yet known, records this module declares and records it imports
directly decide the lookup, and carried records are consulted only when neither
does. Every lookup that resolved in 0.5.0 resolves the same way.
A statement after a binding in a computation expression is reported where it
is (#64). Items inside the braces are structured by indentation, so a line that
is not indented past the item above it sits in item position and must start with
let!, let, do!, return, or yield. A line that is indented gets a
message naming the item it continues and both ways to fix it:
error: identifier `print` is indented as a continuation of the `let` item on line 4,
where it can only be an argument to that item's expression; to make it a new item,
align it with that item and bind its value (`let _ = ...`), or indent it past the
start of the expression to continue it
pyfun run forwards program arguments (#73). Everything after the source
path reaches the program's sys.argv, with or without a -- separator, so a
program behaves the same under run as it does compiled. Arguments that look
like flags are passed through rather than read by the CLI.
Improved
Rendered lex and parse errors no longer end with a byte span that repeats the
line and column already shown above the caret. Editors get the bare message
alongside the range they already had, and the same text now reaches the REPL and
the Jupyter kernel.
The playground compiles the current compiler and demonstrates the features added
since it was written, and the learning site covers what 0.4.0 and 0.5.0 added.
Upgrading
pip install --upgrade pyfun-lang. If a project stops compiling, it is one of
the two breaking changes above, and each has a one line fix.
v0.5.0
release: 0.5.0 (#59)
Destructuring `let` bindings and the `option {}` computation expression, the
two findings from the second dogfooding session.
Bumps every versioned artifact to the compiler version per RELEASING.md, and
repins the Zed grammar rev, since the tree-sitter grammar changed in both
features (new binding targets, and the `option` builder keyword). Also syncs
the canonical and Zed highlights queries with the nvim one, which was the only
copy updated when the keyword landed.
v0.4.0
Pyfun 0.4.0 Two dogfooding reports from real programs, and the standard-library sweep they triggered. Language: a type declaration can name an imported type; field access resolves from the base's type; parameters destructure tuples, records and _; a direct self tail call lowers to a loop. Standard library: about 115 new members take every module to the F# core set, and every built-in member carries its description and complexity in hover and completion. Fixes: single-file run gives the program its own stdin; a partially applied lambda closes over its argument; multi-argument callbacks can be effectful (List.fold could not print); Seq.empty no longer lowers to a TypeError. Source-incompatible: a dotted extern target whose module prefix cannot be decided from the text is a compile error naming the extern import to add.
v0.3.0
v0.3.0 — input builtin, extern keyword slots, and five fixes