Repository navigation
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 arguments are written, the editor shows the function's type with the current parameter picked out.
- Quick fixes. A non-exhaustive
matchoffers "Add the missing cases". An unused name offers a rename to_name, and an unused import its removal. - Format on save, through the language server.
- Packages. Go to definition, find references and rename follow a module into its folder.
- Rename keeps a punned field. Renaming a variable written with the field shorthand (
Rect { width, height },case Rect { width }:) writes the field back beside the new name (width = w), where it used to rename the field. - Hover shows constraints:
num a => a<'u> -> a<'u>,a in b => a -> b -> bool.
Fixes
- A function or value written between two mutually recursive functions was reported as unbound when the later one used it.
- A top-level name bound twice ran the wrong binding: a function written between the two was checked against the first and ran the second. Each binding now has its own name in the Python (
_helper, thenhelper), and the same holds for a built-in such asmaxused above alet max, for anexternunder a laterletof its name, and in the REPL and notebooks. - A function bound again with a different number of parameters no longer changes how the calls above it are emitted.
- A record update rebuilt the wrong record when two records shared a field name.
- A non-exhaustive match whose gap is left only by
ifguards now says that a guarded arm does not count. - A binding could take a name the emitted Python calls, and the program failed when it ran:
let min a b = abrokeList.min,let functools = 1broke every partial application, and a constructor namedValueErrorreplaced the exception a decoder raises. - A parse error names the token it met (
elif,case,as,**,%) where it saidtoken, and a line that stops short is reported where it stops. - The header over a module's errors names the file the module was read from (
_tool.pyfunwas reported astool.pyfun). Map.try_findande.errorKindare answered withMap.findanderror_kindwherever they are met.- An
externthat reads an attribute and takes arguments after its receiver (with_name: Path -> str -> Path = .with_name) failed when it was called from another module or under a second name. - A program's own
let ewas lost after an inlineDecode.decode_stringthat failed (NameError).