Flavors: write Osprey in the syntax you know

What a flavor is

A syntax flavor, or flavor, is a way to write Osprey. There are four today: Default, ML, Python and TypeScript. A Dart flavor, aimed at Flutter developers, is on the way.

Every flavor is the same language. The compiler parses each one into the same syntax tree, then checks and builds it the same way. So:

  • Write in the syntax you already know. A Python developer writes def and match. A TypeScript developer writes function and switch.
  • Use packages from your own ecosystem. Osprey ports popular libraries and keeps their names: NumPy, PyTorch and Transformers for Python, Express for TypeScript. Their tests compare results with the original library.
  • Mix flavors in one project. A Python-flavor module can import a TypeScript-flavor module. The types carry across.
  • Get the same guarantees everywhere. Static types, checked effects, Result instead of exceptions, no null, native binaries.

A flavor is not the original language's runtime. osprey compiles a Python-flavor file to a native binary; CPython never runs it. Node.js never runs a TypeScript-flavor file. Code that depends on that runtime, such as exceptions, null or mutable objects, does not compile. To call real CPython code, use Python interop.

One program, four flavors

Each file below compiles with osprey <file> --run and prints area: 9.0.

Default (.osp):

type Shape = Circle { radius: float } | Square { side: float }

fn area(shape) = match shape {
    Circle { radius } => 3.14159 * radius * radius
    Square { side } => side * side
}

fn main() = print("area: ${area(Square { side: 3.0 })}")

ML (.ospml):

type Shape =
    Circle
        radius : float
    Square
        side : float

area shape =
    match shape
        Circle radius => 3.14159 * radius * radius
        Square side => side * side

main () = print "area: ${area (Square(side = 3.0))}"

Python (.py):

# osprey: flavor=python

@union
class Shape:
    class Circle:
        radius: float

    class Square:
        side: float


def area(shape):
    match shape:
        case Circle(radius=radius):
            return 3.14159 * radius * radius
        case Square(side=side):
            return side * side


def main():
    print(f"area: {area(Square(side=3.0))}")

TypeScript (.ts):

// osprey: flavor=typescript

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number };

function area(shape: Shape) {
  switch (shape.kind) {
    case "circle":
      return 3.14159 * shape.radius * shape.radius;
    case "square":
      return shape.side * shape.side;
  }
}

function main() {
  console.log(`area: ${area({ kind: "square", side: 3.0 })}`);
}
The same Shape program in shapes.osp, shapes.ospml, shapes.py and shapes.ts; the terminal runs each with osprey --run and every one prints area: 9.0.
One program in four flavors, compiled by the same compiler: each prints area: 9.0.

In every flavor, drop a case from the match or switch and the program does not compile. The error is the same in all four:

The Python and TypeScript files with the Square case removed; the terminal shows all four flavors failing with: This match on Shape has no arm for Square. Add the missing arms, or a _ arm. Each exits with status 1.
Remove the Square case and every flavor fails with the same message.

Choose a flavor

Flavor Looks like File Packages from
Default Rust, Swift .osp Osprey
ML OCaml, Haskell, F# .ospml Osprey
Python typed Python .py starting # osprey: flavor=python NumPy, SciPy, PyTorch, Transformers, FastAPI and more
TypeScript TypeScript .ts starting // osprey: flavor=typescript, or listed in osprey.toml Express
Dart Dart, Flutter coming coming

The compiler picks the flavor from the file extension, the first-line marker, or --flavor default|ml|python|typescript. osprey fmt formats every flavor.

Mix flavors in a project

A project lists its Python and TypeScript files in osprey.toml, so build scripts and other .py or .ts files in the folder are left alone:

[project]
name = "shop"
source_roots = ["src"]
python_sources = ["src/pricing.py"]
default_namespace = "shop"
entry = "src/main.osp"
# osprey: flavor=python
# osprey: namespace=shop
# osprey: module=Pricing

__all__ = ["discounted"]


def discounted(price, percent):
    return price - price * percent / 100.0
namespace shop;

import shop::Pricing::{discounted}

fn main() = print("Discounted: ${discounted(price: 80.0, percent: 25.0)}")
Discounted: 60.0

__all__ lists what the module exports; everything else is private. TypeScript files use ES import and export, listed under typescript_sources.

Python flavor

Python flavor looks like typed Python: def, lambda, match, f-strings, comprehensions and PEP 484/695 annotations. Effects and handlers are decorated classes.

Python flavor Python
Run by osprey, which builds a native binary CPython, which interprets it
Types Inferred and checked before the program runs Checked at run time
Values Immutable records; failure is a Result Mutable objects; exceptions
Imports Osprey modules, including ported packages PyPI packages

Static types without type hints

Osprey infers every type, so you rarely write annotations. Every value must have exactly one type. This is valid Python, but Osprey rejects it because the list has no single element type:

# osprey: flavor=python

row = [42, "Ada", 3.5]

print(f"{row[1]} scored {row[2]}")
The Playground compiling row = [42, "Ada", 3.5] in Python flavor: compilation fails because int, string and float do not unify.
Valid Python, rejected before it runs: the list has no single element type.

Give each field its own type with a record. A class with annotated fields is a record:

# osprey: flavor=python

class Row:
    id: int
    name: str
    score: float


row = Row(id=42, name="Ada", score=3.5)

print(f"{row.name} scored {row.score}")

Records, Result and effects

# osprey: flavor=python

@effect
class Log:
    def write(message: str) -> None: ...


@handler(Log)
class console:
    def write(message):
        print(f"log: {message}")


@handler(Arith)
class wrapping:
    def overflow(_op, _left, _right, wrapped):
        return wrapped


class Account:
    owner: str
    balance: int


def withdraw(account, amount):
    perform(Log.write(f"{account.owner} withdraws {amount}"))
    if amount > account.balance:
        return Error(message=f"{account.owner} has only {account.balance}")
    else:
        return Success(value=update(account, balance=account.balance - amount))


def report(result):
    match result:
        case Success(value=value):
            return f"{value.owner} now has {value.balance}"
        case Error(message=message):
            return f"declined: {message}"


def main():
    alice = Account(owner="Alice", balance=100)
    with console:
        with wrapping:
            print(f"{report(withdraw(alice, 30))}\n{report(withdraw(alice, 300))}")
log: Alice withdraws 30
log: Alice withdraws 300
Alice now has 70
declined: Alice has only 100
  • update(record, field=value) returns a changed copy; records never change in place.
  • Failure is a Result you match on. There are no exceptions.
  • @effect declares operations, perform(...) asks for one, and @handler(E) answers it. with console: installs the handler. The compiler rejects a program that performs an operation no handler answers.
  • Integer +, - and * can overflow, so they perform the built-in Arith effect. You choose the policy with a handler; the arithmetic policy lists the options.

What Python flavor rejects

  • while, break, continue, try/except, raise, async/await and yield. Use for, comprehensions, recursion, Result and fibers.
  • Inheritance, __init__, self and methods. A class is a record, a union (@union), an effect or a handler.
  • Arbitrary precision. Integers are 64-bit; floats are 64-bit IEEE.
  • Truthiness. Only booleans can be conditions.

Python packages

Ports keep the original module, function and argument names. Each port's tests compare its results with the real library running under CPython, and its README lists what it covers.

from numpy import Array, Errors, Host
from faiss import Flat, Normalize

For a library that has no port, call CPython through Python interop.

Local LLMs

Osprey's language-model work is written in Python flavor: GPT-2 runs from published Hugging Face weights, and a handler picks CPU or GPU (AI and machine learning). A Qwen3.8-27B model and an Ollama-compatible server on @osprey/transformers are in progress; the local coding model plan tracks them.

TypeScript flavor

TypeScript flavor looks like TypeScript: functions, arrow functions, interfaces, unions tagged by kind, template literals, object spread, xs.map/filter/reduce, for … of and ES modules. Effects use perform<Log>().write(…) and handle<Log>({ … }, () => …).

TypeScript flavor TypeScript
Run by osprey, which builds a native binary Node.js or a browser
Types Inferred and checked by Osprey Checked by tsc, erased at run time
Unannotated parameter Inferred any
Values Immutable records; failure is a Result Mutable objects; exceptions
null, Promise, Node.js API Not available Available
Imports Osprey modules, including ported packages npm packages

Not built yet: classes, exceptions, async/await, and object literals with no declared type that are later used as records (issue 405). tsc can lint the same files, but the compiler never runs it.

Its first port is @osprey/express, Express 5 in TypeScript flavor. The Express README example compiles unchanged. Express on Osprey serves it natively and measures it against Express on Node.js.

Converting between flavors

A converter is planned: it will print a file in another flavor and refuse to write unless the result parses back to the same program. Until then, moving a file between flavors is a manual rewrite.

Specifications