Skip to content

v0.11.0

Latest

Choose a tag to compare

@github-actions github-actions released this 25 Nov 20:00
· 9 commits to main since this release
bea887e

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 True and False. true and false are answered with "Pyfun spells this True, as Python does".
  • The string type is str. string in a type is an error that says so. Decode.string is Decode.str. The String module 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 with String.lstrip and rstrip for trimStart and trimEnd, the builder methods return_from and yield_from, and the Exception fields error_kind and error_message. Each old spelling is answered with the new one ("did you mean List.sort_by?").
  • Lookups carry no try prefix. Map.tryFind is Map.find and String.tryIndexOf is String.index_of.
  • An if branch on its own lines opens with :. Write if cond:, elif cond: and else: for indented branches, as in Python. then is 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 TrainTimes reads train_times.pyfun.
  • in is a keyword (see in and not in below), so it can no longer name a value.
  • Json, JNull, JBool, JInt, JFloat, JStr, JList and JObject are 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 4 between is_even and is_odd failed with a NameError when 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 "helper cannot be used yet: it is defined below this line" where it got unbound name. Tools that read the compiler's messages will see the new text.
  • A local accumulator is pure. A let mut assigned in the function that declares it no longer counts as io, so let pure accepts the accumulator style. One corner breaks: a function that was io only through its own accumulator no longer fits a callback arrow declared ->{io}. In an extern, 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, format or getattr, or by the name of a module the compiler imports for itself (json, functools, itertools, asyncio), is emitted as max_, json_, as len and sum already were. A constructor called ValueError, RuntimeError or TimeoutError is the class ValueError_. 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 a Map, {1, 2} a Set, and {} the empty Map, as Python writes them.
  • in and not in. 2 in xs, x not in {1, 2}, "Ada" in ages, "ell" in "hello": an element of a List, Set or Seq, a key of a Map, a substring of a str. 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 built Rect { width = 2.0, height = 3.0 } and matched case 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 } is Rect { 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) = v and let raw (UserId s) = s bind in a parameter, a let, a lambda and a let! when the type has no other constructor.
  • A constructor takes a map or set literal. JObject {"id": JInt 1} and Some {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.Geometry reads shapes/geometry.pyfun, and the code then says Geometry.area. The top of a project is the folder of the file you run. The Python that comes out is shapes/geometry.py in a regular package.
  • The exn effect label. An extern can say that it may raise (->{exn}, ->{io, exn}). The label is inferred through its callers and try discharges it, so a signature can show, and let pure can 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, for and while, 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 a let, and members called by another language's word (Map.get, List.append) each get an error that says what to write.
  • Warnings. A case that can never match, a local let nothing reads (name it _x to say that is intended), an unused import, and a top-level name bound twice. A warning never stops a build, and pyfun check --strict makes one a failure for CI.

JSON

  • Decode.dict and Decode.index. Decode.dict dec reads a JSON object whose keys are data into a Map, in the object's order. Decode.index i dec reads one position of an array, for arrays whose positions each mean something else ([1, [4, "10"]]).
  • JSON as data. Decode.value reads any JSON as the built-in Json type, 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, and Encode.value writes it back with ints, floats and key order as they came. A Json field inside a derived codec travels as it is.

Tools

  • pyfun test. A test_* function in a test_*.pyfun file is a test, run by pytest. Test.equal expected actual, Test.is_true condition and Test.fail message say what it expects and become assert, so pytest shows its own diff. Each performs exn, so a helper shared by tests may assert and its type says so. A failure is reported at its .pyfun line 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, compile and run print 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 ([ a over , b, a comma under the { of Cell {, an argument one step in from its constructor), and an else set under its if stays there. pyfun fmt --check reports for CI.
  • Tracebacks in .pyfun lines. When a program fails as it runs, each frame names the source file, the line and the statement, under pyfun run, in the REPL and in a notebook. PYFUN_TRACEBACK=python shows Python's own traceback over the emitted code.
  • Typed output. pyfun compile --typed writes 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 with in is a Container, and an extern a project binds carries its declared type. A project compiled this way carries py.typed, and mypy . over it is clean but for two idioms inside a function body that DESIGN.md §5.7 names.
  • Doc comments are docstrings. A ## comment above a function or a record is its docstring in the emitted Python, so help(area) shows it.

In the editor

  • Inlay hints. Each binding's inferred type is shown beside it, the way Python annotates: total: int after a value, -> float ahead 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 match offers "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, then helper), and the same holds for a built-in such as max used above a let max, for an extern under a later let of 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 if guards 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 = a broke List.min, let functools = 1 broke every partial application, and a constructor named ValueError replaced the exception a decoder raises.
  • A parse error names the token it met (elif, case, as, **, %) where it said token, 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.pyfun was reported as tool.pyfun).
  • Map.try_find and e.errorKind are answered with Map.find and error_kind wherever they are met.
  • An extern that 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 e was lost after an inline Decode.decode_string that failed (NameError).