Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lingua Tungga

One source for pure logic and data models that behave identically in TypeScript, Python, and Go.

package money {
  export struct Price {
    amount: Int
    currency: Str
  }

  export fn format(p: Price) -> Str {
    `${p.amount / 100}.${p.amount % 100} ${p.currency}`
  }
}

The same file compiles to three ordinary libraries. There is no runtime to install, no interop layer, and no generated code to edit:

lt build -t ts src/money.lt   # -> out/ts
lt build -t py src/money.lt   # -> out/py
lt build -t go src/money.lt   # -> out/go

What it is for

Lingua Tungga owns the part of a program that must agree everywhere: business rules, validation, money arithmetic, data models, and algorithms. It deliberately has no entry point, no UI, no IO, and no concurrency. The host language keeps those.

  • One behavior. Integer division truncates toward zero in every target. Comparison, display, and JSON follow one specification.
  • Ordinary output. TypeScript gets typed modules, Python gets typed modules with a .pyi-free runtime, Go gets packages. You import them like code you wrote.
  • No drift. The conformance suite runs the same .lt tests against all three targets.

Status

Experimental. There is no compatibility promise before 1.0; the language specification is versioned, and the compiler tracks it.

PhaseM9 — distribution
Language.lt
CompilerRust, binary lt
TargetsTypeScript, Python, Go
Conformance100% in all three targets
LicenseMIT

Where to go next

Install

Release binary

The installer downloads the release for your platform, verifies its SHA-256 checksum, and places lt in $HOME/.local/bin:

curl -fsSL https://raw.githubusercontent.com/gntrees/lingua-tungga/main/scripts/install.sh | bash

Pin a version with LT_VERSION:

LT_VERSION=v0.7.2 \
  curl -fsSL https://raw.githubusercontent.com/gntrees/lingua-tungga/main/scripts/install.sh | bash

Use LT_PREFIX to install somewhere else, and LT_BASE_URL to use a mirror:

LT_PREFIX="$HOME/.cargo" LT_BASE_URL=https://mirror.example/lt \
  ./scripts/install.sh

The binary is named lt. Make sure $HOME/.local/bin is on PATH.

From source

cargo install --path crates/lt-cli

Or build the workspace binary directly:

cargo build --release
export PATH="$PWD/target/release:$PATH"
lt --help

Target toolchains

lt build only writes source files. Running lt test --run needs the native toolchain for that target:

TargetRequires
TypeScriptNode 20+
PythonPython 3.11+
GoGo 1.22+

The repository’s conformance scripts create the test dependencies (vitest, pytest, mypy) for you. A consumer project only needs the host language itself.

Verify the install

lt --help
lt check examples/library/catalog_test.lt

If lt is not found, the installer prints the directory to add to PATH.

Your first project

This page builds one package and imports it from TypeScript, Python, and Go. It takes a few minutes and needs no test runner.

1. Create the project

lt init money
cd money

lt init writes:

lt.toml
src/money.lt
.gitignore

The generated src/money.lt is a starting package. Replace it with:

package money {
  export struct Price {
    amount: Int
    currency: Str
  }

  export fn format_price(p: Price) -> Str {
    `${p.amount / 100}.${p.amount % 100} ${p.currency}`
  }

  export fn add(a: Price, b: Price) -> Price {
    Price(amount: a.amount + b.amount, currency: a.currency)
  }
}

Rules that matter here:

  • A file contains exactly one package block. A file without one, or with more than one, is a compile error.
  • Fields are named at construction: Price(amount: 1250, currency: "IDR").
  • format_price is a receiver function because its first parameter is a struct. p.format_price() is the same call.
  • export makes a declaration part of the package API. Without it, the declaration is private.
  • Local imports use a path without .lt: import money "./money".

lt.toml starts empty and holds external dependencies:

[dependencies]

2. Check and build

lt check src/
lt fmt src/
lt build -t ts src/money.lt --out out
lt build -t py src/money.lt --out out
lt build -t go src/money.lt --out out

lt check resolves imports and type-checks the graph. lt fmt writes the canonical form. lt build never writes lt.lock; only lt update does.

The build writes one host module per package:

out/ts/src/money.ts
out/py/gen/money.py
out/go/gen/money/money.go

Each target also gets its inline runtime and project metadata. See Backends for the exact layout.

3. Call it from the host language

TypeScript

import { Price, formatPrice } from "./out/ts/src/money";

const total = formatPrice(new Price({ amount: 1250n, currency: "IDR" }));
console.log(total); // 12.50 IDR

Int maps to bigint; snake_case becomes camelCase.

Python

from gen.money import Price, format_price

total = format_price(Price(amount=1250, currency="IDR"))
print(total)  # 12.50 IDR

Run it with out/py on PYTHONPATH.

Go

package main

import (
	"fmt"
	money "linguatungga/gen/money"
)

func main() {
	total := money.FormatPrice(money.Price{Amount: 1250, Currency: "IDR"})
	fmt.Println(total) // 12.50 IDR
}

Go gets one package directory per LT package. Put the generated out/go module on your module path, or copy the packages into your project.

4. Add a dependency

External code is declared in lt.toml, then imported by key:

lt add foo --git https://github.com/foo/bar --version "^1.2"
lt update --all
import user { User } "foo/src/user"

See Packages and dependencies.

5. Next

  • Add tests with test "…" { … } and run them with lt test -t <target> … --run.
  • Read the language guide for types, match, Option, Result, and imports.
  • Use the playground to try a snippet without a local toolchain.

Tutorial: from zero to three targets

This tutorial builds a small library (a book catalog), tests it, and runs it as a TypeScript, Python, and Go package. The complete example lives in examples/library.

The normative description of every rule is the language specification. This page is the shortest path from an empty directory to three working libraries.

1. Install the compiler

curl -fsSL https://raw.githubusercontent.com/gntrees/lingua-tungga/main/scripts/install.sh | bash
lt --help

Or build from source:

cargo build --release
export PATH="$PWD/target/release:$PATH"

To run tests you also need the native toolchain:

TargetRequires
TypeScriptNode 20+
PythonPython 3.11+
GoGo 1.22+

See Install for pins and mirrors.

2. Write the model

examples/library/book.lt:

package book {
  export enum Genre {
    Fiction
    NonFiction
    Reference
  }

  export struct Book {
    title: Str
    author: Str
    genre: Genre
    year: Int
  }

  export fn genre_label(b: Book) -> Str {
    match b.genre {
      Genre.Fiction => "fiction"
      Genre.NonFiction => "non-fiction"
      Genre.Reference => "reference"
    }
  }

  export fn describe(b: Book) -> Str {
    `"${b.title}" by ${b.author} (${b.year}, ${b.genre_label()})`
  }
}

Things to note:

  • A file contains exactly one package block.
  • A struct is only data. Behavior lives in package-level functions; b.genre_label() is sugar for genre_label(b).
  • All fields are immutable. There is no null; absence uses Option<T>.
  • match must be exhaustive.
  • A plain template uses Display. Int, Str, and structs all have it.

3. Write the logic

examples/library/catalog.lt:

import book { Book } "./book"

package catalog {
  export struct Catalog {
    books: List<Book>
  }

  export fn empty() -> Catalog {
    Catalog(books: [])
  }

  export fn add(c: Catalog, book: Book) -> Catalog {
    Catalog(books: c.books.push(book))
  }

  export fn size(c: Catalog) -> Int {
    c.books.len()
  }

  export fn find_by_author(c: Catalog, author: Str) -> List<Book> {
    c.books.filter(fn(book) => book.author == author)
  }

  export fn newest(c: Catalog) -> Option<Book> {
    let mut best: Option<Book> = None
    for book in c.books {
      best = match best {
        None => Some(book)
        Some(current) => if book.year > current.year {
          Some(book)
        } else {
          best
        }
      }
    }
    best
  }
}

Language notes:

  • Imports name packages, not symbols: import book { Book } "./book" imports the package book from that file and takes Book. Without { … }, the package is bound as a qualifier (book.Book).
  • Collections are immutable: push and add return a new value.
  • A function whose parameters are not struct-typed is an ordinary function: call empty().
  • Parameter order determines the receiver: add(c, book) can be written c.add(book).
  • mut is only for local variables; struct fields are never mutable.

4. Write tests

examples/library/catalog_test.lt:

import book { Book, Genre, describe } "./book"
import catalog { Catalog, add, empty, find_by_author, newest, size } "./catalog"

package catalog_test {
  fn sample() -> Catalog {
    let first = Book(title: "Dune", author: "Frank", genre: Genre.Fiction, year: 1965)
    let second = Book(title: "Code", author: "Ada", genre: Genre.Reference, year: 2020)
    add(add(empty(), first), second)
  }

  test "describes a book" {
    let book = Book(title: "Dune", author: "Frank", genre: Genre.Fiction, year: 1965)
    expect.eq(describe(book), "\"Dune\" by Frank (1965, fiction)")
  }

  test "adds books" {
    expect.eq(size(sample()), 2)
  }

  test "filters by author" {
    expect.eq(find_by_author(sample(), "Ada").len(), 1)
    expect.eq(find_by_author(sample(), "Nobody").len(), 0)
  }

  test "newest uses year" {
    expect.eq(newest(sample()).map(fn(book) => book.title), Some("Code"))
  }

  test "empty catalog has no newest" {
    expect.eq(newest(empty()), None)
  }
}
  • Tests are package items written test "title" { … }; titles are unique per package.
  • fn sample() is a private helper because it has no export.
  • Assertions use expect.eq, expect.not_equal, expect.true, and expect.false.

5. Check and format

lt check examples/library/catalog_test.lt
lt fmt examples/library

lt fmt preserves comments. Inline comments (x: Int // note) are rejected; move them to their own line.

6. Compile and run

lt test -t ts examples/library/catalog_test.lt --out out/lib --run
lt test -t py examples/library/catalog_test.lt --out out/lib --run
lt test -t go examples/library/catalog_test.lt --out out/lib --run

--run uses the native runner: vitest, pytest, or go test. Without it, only the test files are emitted.

To build only the library:

lt build -t ts examples/library/catalog.lt --out out/lib
lt build -t py examples/library/catalog.lt --out out/lib
lt build -t go examples/library/catalog.lt --out out/lib

One package becomes one host module. The example has two packages in two files, so the output is two modules:

out/ts/src/book.ts, out/ts/src/catalog.ts
out/py/gen/book.py, out/py/gen/catalog.py
out/go/gen/book/book.go, out/go/gen/catalog/catalog.go

The TypeScript result is roughly:

export class Book {
  readonly title: string;
  readonly author: string;
  readonly genre: Genre;
  readonly year: bigint;
}

Names follow the target convention: snake_case becomes camelCase in TypeScript. Declarations without export stay private in LT; the emitters add a _ prefix (TypeScript, Python) or keep a lowercase initial (Go) so the package’s own tests can still call them.

7. Depend on a git repository

External dependencies are declared in lt.toml:

[dependencies]
foo = { git = "https://github.com/foo/bar", version = "^1.2" }

The import uses the dependency key and the package path inside that repository:

import user { User } "foo/src/user"

lt update resolves versions and writes lt.lock (commit and SHA-256). lt build and lt check never write the lock; an incomplete lock is an error. Related commands:

lt add foo --git https://github.com/foo/bar --version "^1.2"
lt update foo      # one dependency and its closure
lt update --all
lt vendor          # copy locked sources into vendor/ for offline CI

See Packages and dependencies and the import v3 design note.

8. What this language does not do

There is no IO, async, exceptions, inheritance, null, typeclass, or main. A Lingua Tungga program is a pure library; side effects (HTTP, files, UI) remain in the host language.

Language guide

This guide is task-oriented: it shows the shape of the language and the rules you need while writing a package. The normative description, including every edge case, is the specification.

The model

Lingua Tungga compiles pure libraries. There is no main, no IO, no exceptions as control flow, and no shared mutable state. The host language owns effects and wiring.

  • Values are immutable. let mut makes a local variable reassignable; fields, parameters, and collection elements never are.
  • Evaluation is eager and left to right. && and || short-circuit.
  • Nominal types. Two structs with identical fields are different types. Identity is the pair (package, name).
  • One package, one host module. The package name, not the file name, determines the output module.
  • Packages and files — package blocks, imports, visibility, naming.
  • Types — primitives, collections, Option, Result, structs, enums, generics.
  • Declarations — structs, enums, functions, receivers, bindings, tests.
  • Expressions and statements — match, loops, templates, tagged templates, JSX.
  • Errors — ?, traps, and what must stay in the host language.
  • Tests — test, expect, and the conformance suite.

A complete package

package receiver {
  export struct Counter {
    value: Int
  }

  export fn bump(c: Counter) -> Counter {
    Counter(value: c.value + 1)
  }

  test "calls as a function" {
    expect.eq(bump(Counter(value: 1)), Counter(value: 2))
  }

  test "calls as a method" {
    expect.eq(Counter(value: 1).bump(), Counter(value: 2))
  }
}

Packages and files

A file contains exactly one package block. The package name is what imports refer to; the file name is free.

package money {
  export struct Price {
    amount: Int
    currency: Str
  }
}

Rules:

  • A file without a package block, or with more than one, is a compile error.
  • The package name is lowercase_snake_case. Functions, fields, parameters, locals, and bindings are snake_case; structs, enums, and variants are PascalCase.
  • Package identity is (dependency, file path), not the name alone. Two dependencies may both declare package user; importing both into one file requires different aliases.
  • Type identity is nominal per loaded module. money.Price and user.Price never unify, even with identical fields.
  • Case-insensitive uniqueness applies inside a package: Format and format cannot coexist.
  • The package name, not the file name, determines the output module.

Visibility

export is per declaration. Without it, a declaration is private to its package.

package money {
  export fn format_price(p: Price) -> Str { … }

  fn round_to_cents(n: Int) -> Int { n }   // private
}

Privacy applies to every call path: a plain name, a qualified path, and receiver sugar. Another package cannot reach round_to_cents through money.round_to_cents, and cannot call it as a receiver.

Local imports

Local imports start with ./ or ../. The specifier has no .lt extension; the loader appends it.

import money "./wallet/money"
import money { Price, format_price } "./wallet/money"
import money as cash { Price as P } "./wallet/money"
  • Only whole packages are imported, never individual files or symbols.
  • The package name is written explicitly and must exist in the target file.
  • Destructuring is optional and may only name exported declarations (or names the target package explicitly re-exports). It does not remove the qualifier: import money { Price } may still use money.format(...).
  • An empty destructuring list {} is an error.
  • There are no directory imports and no index resolution.
  • Import cycles are compile errors and the message shows the cycle.
  • An import that is never used is a compile error.
  • Imports are not re-exported implicitly.

External imports

External dependencies are declared in lt.toml at the project root:

[dependencies]
acme  = { git = "https://github.com/acme/lt-lib", version = "^1.2" }
utils = { path = "../utils" }

An external import is <dependency-key>/<package path>:

import post "acme/blog/post"

The first segment must be a key in [dependencies]. The rest is the package path inside that dependency. See Packages and dependencies and the import v3 design note.

Re-export

A package can expose imported names as part of its own API:

export import money { Price as P } "./wallet/money"
  • The item list is mandatory; wildcards and the bare form are rejected.
  • The re-exported name must be public in the source package.
  • A re-export does not create a new type: facade.P and money.Price are the same nominal type.
  • Re-exports do not propagate implicitly. Only the names listed are exposed; the package qualifier is not.

Commands

lt add foo --git https://github.com/foo/bar --version "^1.2"
lt add utils --path ../utils
lt remove foo
lt update foo
lt update --all
lt vendor

lt add writes lt.toml; lt update resolves and writes lt.lock; lt build and lt check never write the lock. An incomplete lock is an error. lt migrate --write rewrites v2 imports to v3.

Complete example

import wallet "./_wallet"

package qualified {
  export fn checkout(subtotal: Int) -> Str {
    wallet.format(wallet.add_vat(wallet.Money(amount: subtotal)))
  }

  test "qualified access reaches types, bindings and functions" {
    expect.eq(checkout(100), "Rp111")
  }
}

The support file imported by this case:

package wallet {
  export struct Money {
    amount: Int
  }

  export let vat: Int = 11

  export fn add_vat(money: Money) -> Money {
    Money(amount: money.amount + money.amount * vat / 100)
  }

  export fn format(money: Money) -> Str {
    `Rp${money.amount}`
  }
}

Types

Primitives

TypeSemantics
Int64-bit signed, two’s complement, wrapping overflow.
FloatIEEE-754 binary64. NaN exists and NaN != NaN.
Booltrue or false.
StrImmutable Unicode text. Length and indexing count code points, not bytes or grapheme clusters.

There is no implicit Int ↔ Float conversion. 1 + 1.0 is a compile error.

Collections

TypeOrderLiteral
List<T>insertion order[1, 2, 3]
Map<K, V>sorted by K (Ord)none; build with map.empty()
Dict<V>insertion order, Str keys["a": 1, "b": 2], empty [:]
Set<T>sorted by Tnone; build with set.empty()

All collection operations return a new value. Indexing is partial and returns Option<T>:

xs[0]      // Option<T>, None when out of bounds
m[key]     // Option<V>
d["name"]  // Option<V>
s[1]       // Option<Str>, one code point

Map requires K: Eq + Ord. Its iteration order is the sorted key order, which keeps output identical across targets. Dict ignores order for equality but preserves it for display and iteration.

Structs and enums

A struct is a nominal record with named fields. An enum is a nominal sum type whose variants may carry payloads.

export struct User {
  name: Str
  age: Int
}

export enum Role {
  Admin
  Member(Int)
  Guest
}

Two structs with the same fields are still different types. A struct and an enum never unify. Type identity is nominal per loaded module; two packages with the same name in different dependencies are different types.

Widening with embed

A struct may embed exactly one other struct:

export struct TableInfo {
  name: Str
  columns: List<ColumnInfo>
}

export struct UsersTable {
  embed table_info: TableInfo
  id: IntColumn
}

UsersTable can be used where TableInfo is expected, because the embedded field has exactly that type. The relation is one step only and applies to arguments, returns, annotated bindings, and collection elements. It does not become covariance for List, Map, Dict, Option, or Result. The embedded field remains an ordinary field: construct it by name, read it as users.table_info, and compare it structurally.

Option and Result

Option<T>     // Some(T) | None
Result<T, E>  // Ok(T) | Err(E)

T? is sugar for Option<T>. Some, None, Ok, and Err are always in scope.

Functions as values

Function types are written fn(A, B) -> R. A lambda is fn(x: Int) => x + 1; parameter types may be inferred from context.

  • A function value can live in a local, parameter, return value, or package binding, and is called as f(x).
  • Functions cannot be stored in struct fields, enum payloads, or collections.
  • Functions cannot be compared or converted with to_string.
  • A lambda captures values; later mutations of an outer let mut are invisible inside it.
  • A generic function cannot be used as a value. Wrap it in a concrete lambda.

Generics

Generics are available on structs, enums, and functions. Constraints are limited to the built-in traits Eq, Ord, and Display; Map<K, V> requires K: Eq + Ord. There are no higher-kinded types, associated types, or default type parameters.

package generic_fn {
  export fn identity<T>(value: T) -> T {
    value
  }

  export fn first<T>(items: List<T>) -> Option<T> {
    items.get(0)
  }

  test "infers from a scalar" {
    expect.eq(identity(7), 7)
  }

  test "infers from a list" {
    expect.eq(first(["a", "b"]), Some("a"))
  }
}

Complete example

package map_case {
  export struct Point {
    x: Int
    y: Int
  }

  test "inserts and reads" {
    let empty: Map<Str, Int> = map.empty()
    let filled = empty.insert("b", 2).insert("a", 1)
    expect.eq(filled.get("a"), Some(1))
    expect.eq(filled.len(), 2)
    expect.eq(filled.keys(), ["a", "b"])
    expect.eq(empty.len(), 0)
  }

  test "struct keys follow ord" {
    let empty: Map<Point, Str> = map.empty()
    let filled = empty.insert(Point(x: 10, y: 0), "ten").insert(Point(x: 2, y: 0), "two")
    expect.eq(filled.keys(), [Point(x: 2, y: 0), Point(x: 10, y: 0)])
  }

  test "removes" {
    let empty: Map<Str, Int> = map.empty()
    expect.eq(empty.insert("a", 1).remove("a").len(), 0)
  }
}

Declarations

Structs

export struct User {
  name: Str
  age: Int
  address: Address?
}
  • Fields are immutable. There are no private fields; construction across packages must be able to fill every field.
  • Construction uses named arguments and requires every field: User(name: "Ada", age: 36, address: None). Order is free.
  • There is no constructor, inheritance, override, or abstract.
  • An empty struct is valid and useful as a marker: export struct Unit {}.
  • At most one field may be embed; see Types.

Enums

export enum Role {
  Admin
  Member(Int)
  Guest
}
  • A variant may have no payload or one or more payload types.
  • An enum without payloads is a typed constant.
  • Enums have no fields. Behavior lives in package-level functions that take the enum as a parameter; receiver sugar works (role.label() ≡ label(role)).
  • Variants are referenced as Role.Member(3), or with a qualifier from another package (models.Role.Member(3)).

Functions and receivers

A receiver function is an ordinary function whose first parameter has a struct or enum type. There is no self and no marker.

export fn add(c: Catalog, b: Book) -> Catalog {
  Catalog(books: c.books.push(b))
}

// c.add(b) is add(c, b)

Rules:

  • The sugar value.f(args) applies only when a function f exists in the package where the value’s type is declared. There is no dynamic dispatch.
  • A receiver function must live in the same package as its receiver type.
  • Overloading is allowed only when the receiver type differs. Overloading by name or arity is forbidden.
  • Parameters have nominal or primitive types. No varargs and no default values.
  • A function whose parameters are not struct-typed is an ordinary function: call empty(), not catalog.empty().

Package-level bindings

package money {
  export let default_currency: Str = "IDR"
  let lookup: Map<Str, Int> = map.empty()
}

Bindings are immutable, eager, and parameterless. They may refer to other bindings in the same package as long as no cycle forms. export exposes them as money.default_currency or through destructuring.

Tests

test "formats with currency" {
  let p = Price(amount: 1250, currency: "IDR")
  expect.eq(format_price(p), "12.50 IDR")
}

A test is a package item. Titles are unique per package. Tests are not emitted by lt build; only lt test produces native test files. A test body is a normal statement block with no parameters and no return type, and it may use private declarations.

Complete example

package receiver {
  export struct Counter {
    value: Int
  }

  export fn bump(c: Counter) -> Counter {
    Counter(value: c.value + 1)
  }

  test "calls as a function" {
    expect.eq(bump(Counter(value: 1)), Counter(value: 2))
  }

  test "calls as a method" {
    expect.eq(Counter(value: 1).bump(), Counter(value: 2))
  }
}

Expressions and statements

Statements

Statements are separated by newlines. A semicolon is rejected, and two statements on one line are a compile error. An expression may continue onto the next line inside (, [, <, {, or after a binary operator.

Statements: let, destructuring let, assignment to a let mut, return, if, for, while, break, continue, and expressions.

let point = Point(x: 1, y: 2)
let Point { x, y as py } = point
let mut total = 0
total = total + x

Only the body of a function, an if branch, and a match branch evaluates to their last expression. A standalone block is statement-only; let x = { … } is illegal.

match

match must be exhaustive at the top variant level. Patterns are _, None, a variant, or a variant with nested patterns (Some(Some(x)), Ok(Value.Int(n))). Struct patterns are allowed for struct scrutinees: Point { x, y } binds fields by name, and Point { x: px, y } renames.

match role {
  Role.Admin     => "admin"
  Role.Member(n) => `member-${n}`
  Role.Guest     => "guest"
}
  • Alternatives may share an arm with | when they bind the same names and types.
  • Guards use pat if cond => …, are evaluated after binding, and do not close exhaustiveness.
  • A struct pattern with only bindings and wildcards is irrefutable.
  • Nested exhaustiveness is not checked. An arm that does not match falls through; if nothing matches, the runtime reports an unreachable trap.

Loops

for book in books { … }
for key in map { … }       // keys
for key in dict { … }      // keys
for item in set { … }      // sorted order
while ready { … }

break and continue apply to the nearest loop. Loop state changes only through local let mut.

Templates

A plain template interpolates any value with Display:

`Hi ${user.name}, total ${total}`

Multiline templates are verbatim: newlines and indentation are preserved. Use .trim_indent() to remove indentation.

A tagged template calls a package-level function with signature (List<Str>, List<T>) -> R:

let query = sql`SELECT * FROM users WHERE id = ${Arg.I(id)}`

Every ${…} must be exactly T. There is no implicit Display, no automatic Some, and no automatic variant selection. Mixed types use an enum as T. The invariant parts.len() == values.len() + 1 always holds.

JSX

JSX is an ordinary struct constructor:

<Element tag="div" class_name="user">
  <Element tag="span">{user.name}</Element>
</Element>

The tag name is a struct in scope and must be PascalCase. Attributes are named arguments. Children are collected into a children argument only when the struct declares that field. There is no lifecycle, render function, or framework.

Complete example

package nested_match_case {
  export fn unwrap_nested(x: Option<Option<Int>>) -> Int {
    match x {
      Some(Some(n)) => n
      Some(None) => 0
      None => -1
    }
  }

  export fn kind(text: Str) -> Str {
    match json.parse(text) {
      Ok(Value.Int(n)) => `int ${n}`
      Ok(Value.Str(s)) => `str ${s}`
      Ok(other) => "other"
      Err(message) => message
    }
  }

  test "patterns nest to any depth" {
    expect.eq(unwrap_nested(Some(Some(3))), 3)
    expect.eq(unwrap_nested(Some(None)), 0)
    expect.eq(unwrap_nested(None), -1)
    expect.eq(kind("1"), "int 1")
    expect.eq(kind(`"x"`), "str x")
    expect.eq(kind("true"), "other")
  }
}

Errors: Option, Result, and ?

Lingua Tungga has no exceptions. Expected failure is a value: Option<T> for absence and Result<T, E> for a reason.

Option

export fn find(c: Catalog, title: Str) -> Option<Book> {
  c.books.filter(fn(b) => b.title == title).get(0)
}

Option methods: is_some(), is_none(), unwrap(), unwrap_or(default), map(fn), and_then(fn).

unwrap() on None is a trap, not a recoverable error.

Result

export fn parse(text: Str) -> Result<Int, Str> {
  match text.parse_int() {
    Some(value) => Ok(value)
    None => Err("not a number")
  }
}

Result methods: is_ok(), is_err(), unwrap(), unwrap_or(default), map(fn), map_err(fn), and_then(fn).

The ? operator

expr? unwraps Ok/Some and returns the Err/None from the enclosing function.

export fn double(text: Str) -> Result<Int, Str> {
  let value = number(text)?
  Ok(value * 2)
}

Rules:

  • ? on Option<T> requires a function returning Option<U>.
  • ? on Result<T, E> requires a function returning Result<U, E>.
  • Option and Result cannot be mixed in one function.
  • ? is rejected inside a lambda: its return would leave the lambda, not the function.

Traps

Traps stop the program through the host language’s native mechanism. They are never used as normal flow:

  • integer division or remainder by zero;
  • unwrap() on None or Err;
  • unbounded recursion (the host stack limit is not part of the contract).

Out-of-bounds indexing does not trap: xs[i], m[k], d["k"], and s[i] return None.

What stays in the host

IO, async, concurrency, and HTTP are outside the language. A package returns values; the host decides what to do with them.

Complete example

package question {
  export fn number(text: Str) -> Result<Int, Str> {
    match text.parse_int() {
      Some(value) => Ok(value)
      None => Err("not a number")
    }
  }

  export fn double(text: Str) -> Result<Int, Str> {
    let value = number(text)?
    Ok(value * 2)
  }

  test "success" {
    expect.eq(double("21"), Ok(42))
  }

  test "propagates error" {
    expect.eq(double("x"), Err("not a number"))
  }
}

Tests

Tests are package items. They are compiled only by lt test, never by lt build.

package money {
  test "formats with currency" {
    let p = Price(amount: 1250, currency: "IDR")
    expect.eq(format_price(p), "12.50 IDR")
  }
}
  • A title is a string literal, unique within its package.
  • A test body is a normal statement block. It may call private declarations in the same package.
  • Assertions use the pseudo-package expect: expect.eq(a, b), expect.not_equal(a, b), expect.true(x), expect.false(x).
  • There is no mocking, setup, teardown, or parallel execution. Tests must be deterministic and pure.

Run the tests

lt test -t ts src/money.lt --out out/test --run
lt test -t py src/money.lt --out out/test --run
lt test -t go src/money.lt --out out/test --run

--run uses the native runner: vitest, pytest, or go test. Without it, lt test only emits the test files. The generated test project includes the target runtime and a manifest, so a single command is enough.

A target is considered conformant only when its entire test suite passes. The repository’s conformance flow runs the same .lt tests against all three targets.

Complete example

package generic_fn {
  export fn identity<T>(value: T) -> T {
    value
  }

  export fn first<T>(items: List<T>) -> Option<T> {
    items.get(0)
  }

  test "infers from a scalar" {
    expect.eq(identity(7), 7)
  }

  test "infers from a list" {
    expect.eq(first(["a", "b"]), Some("a"))
  }
}

Lingua Tungga — Language Specification v2.1

Status: v2.1 in effect. The import v3 amendments in §1, §6.1, §13, §15, and §16 are already implemented (0.7.0). The source of truth for the import design is in import-v3.md. The rationale for the v2 changes is in v2-decisions.md. Formal grammar: grammar.ebnf. Project plan: ../PLAN.md.

Biggest change from v0.1: class is removed. The single container is package; a package contains structs, enums, functions, and immutable bindings. Methods become functions with an explicit receiver.

Biggest change from v2.0: imports become package-first with a manifest. One file contains exactly one package; external dependencies are declared in lt.toml; the lock is no longer written by the build.


1. Scope

Lingua Tungga is a pure logic language compiled into TypeScript, Python, and Go libraries.

What exists in v2

  • package (nominal namespace; exactly one package per file)
  • struct (nominal record) and enum (sum type)
  • Package-level functions, including receiver functions (replacement for methods)
  • Primitive types Int, Float, Bool, Str; collections List, Map, Set; Option, Result
  • Generics on structs, enums, and functions
  • Package-level bindings (immutable)
  • Template literals, tagged templates, JSX (struct literal)
  • Package imports: local specifiers without extension, external dependencies through lt.toml, with destructuring, aliases, and explicit re-export
  • test declarations inside a package

What does not exist and never will

Unrestricted null, exceptions as normal flow, inheritance, user-defined interfaces/traits, typeclasses, higher-kinded types, shared mutable state, Dynamic/any types, pointers, IO, async, concurrency, macros, per-target conditional code.

What is deferred

External schema codegen, executable/main, LSP, a fourth target.


2. Execution Model

AspectRule
EvaluationEager, call-by-value.
Value mutabilityAll values are immutable. mut is only allowed on local variables (let mut), not on fields, parameters, collection elements, or package bindings.
Local mutabilityA local let mut variable may be reassigned. This is the only form of mutation in the language.
Reference cyclesImpossible. A value cannot refer to itself; recursion only goes through bounded structures (Option, List).
Global stateNo mutable globals. Package-level bindings are immutable, evaluated eagerly at load, and must not form initialization cycles.
Evaluation orderArguments are evaluated left to right.
Short-circuit&& and || short-circuit.

Consequence: mapping to Rust/Zig later does not require a GC, and Option/List may be recursive without fear of cycles.


3. Lexical

  • Encoding: UTF-8. BOM is rejected.
  • Comments: // to end of line, /* ... */ is not nested.
  • Statements are separated by newline; semicolons ; are rejected. An expression may continue onto the next line only if it is inside (, [, <, {, or after a binary operator.
  • Number literals: decimal, _ may be used as a separator (1_000_000). Floats must have a dot (1.0). No hex/octal/binary.
  • Boolean: true, false.
  • None is a literal keyword, not an identifier.
  • String escapes: \n, \t, \r, \\, \", \`, \$, \u{...}. Any other escape = compile error.
  • Indentation has no syntactic meaning.
  • Statements are separated by newlines: two statements on the same line are a compile error.

v2 keywords: package, export, struct, enum, fn, test, let, mut, return, if, else, for, in, while, match, import, from, as, true, false, None, _.

Removed v1 keywords remain reserved: class, pub, static, self. Using them produces an error naming the replacement (class → package + struct, pub → export, self → explicit receiver parameter).

Soft keywords. A keyword may become a name when the position is unambiguously a name:

  • After ., all keywords are allowed: b.from, b.match, b.class.
  • Field names, named-argument labels, parameters, and JSX attributes may be any keyword, because their position is always followed by : (or =): struct Range { from: Int }, Range(from: 1).
  • Function names, let, pattern bindings, for variables, assignment targets, package names, as well as import items and aliases may only use from, as, and in — the only keywords that cannot start a statement, expression, type, or item. So fn from(r: Range) and r.from() are valid, whereas fn match(...) is not.
  • Type/struct/enum/variant names do not change: they must be PascalCase, and the only capitalized keyword is None.

Using a forbidden keyword in a name position produces an error suggesting a trailing _ (e.g. `match` is a keyword; rename it to `match_`). The host emitter mangles that name when the target language requires it: the field from becomes from in TypeScript, from_ in Python, and From in Go.


4. Naming & Formatting

The compiler rejects naming violations (not a warning). These rules are enforced, not merely documented.

EntityStyle
struct, enum, enum variantsPascalCase
functions, fields, parameters, local variables, package bindingssnake_case
package nameslowercase_snake_case ([a-z][a-z0-9_]*)
file namessnake_case.lt
test titlesfree-form string literal; no style rule

Case-insensitive uniqueness: within one package, two names must not be equal regardless of letter case (Format and format cannot coexist). The reason is the mapping to Go: the function format becomes Format, which would collide with struct Format.

The formatter (lt fmt) produces the canonical form:

  • 2-space indentation, no tabs.
  • Maximum width 100 columns; containers exceeding the limit are split one item per line.
  • Trailing commas on multiline arguments/lists.
  • One blank line between package items; enum variants are written tightly.
  • Imports are sorted by path. Multiple adjacent import entries form one sorted block; blank lines separate sub-blocks and each is sorted independently. Entries inside import ( … ) remain in their block, one per line.
  • Multiple package blocks in one file are separated by one blank line, and their order is preserved as in the source (the formatter does not reorder packages).
  • Braces are always on the same line as the header (fn f() {).
  • Empty bodies are written {}.
  • Excess blank lines are collapsed into one.

lt fmt must be idempotent: fmt(fmt(x)) == fmt(x).

Comments: lt fmt preserves comments and is idempotent with comments.

  • // and /* ... */ comments are attached to the next construct in the same body (file, package, block, or match). Comments after the last construct are printed before the closing }.
  • Inline comments (sharing a line with code, e.g. x: Int // note) are rejected with a clear message; move them to their own line.
  • /* ... */ is normalized to the form /*, * ..., */. /// is preserved.
  • Comments inside expressions (e.g. between arguments) also attach to the next construct/end of the body; their order is preserved but their horizontal position may shift.

5. Types

5.1 Primitives

TypeSemantics
Inti64, two’s complement, overflow wrapping.
Floatf64 IEEE-754. NaN exists; NaN != NaN.
Booltrue/false.
StrImmutable, Unicode code point order (not bytes, not grapheme clusters). len() = number of code points.

There is no implicit Int ↔ Float conversion. 1 + 1.0 = compile error.

5.2 Collections

TypeNotes
List<T>Ordered, immutable. Operations return a new list. Literal: [1, 2].
Map<K, V>Keys must have Eq + Ord. Iteration order = sorted key order (Ord), not insertion/hash order — so output is deterministic and identical across all targets. No literal; build from map.empty(). Key lookup uses binary search and duplicates are discarded in one pass after sorting.
Dict<V>Key is always Str, iteration order = insertion order (Dict has no visible Ord; its cmp is canonical so that Eq ⇔ cmp == 0). Literal: ["a": 1, "b": 2], empty [:].
Set<T>Like Map, elements sorted.

Indexing: xs[i], s[i], m[k], and d["k"] are partial lookups and always return Option<T>; an out-of-bounds index or a missing key becomes None (not a panic). For Str, indexing counts code points and costs O(n). Set cannot be indexed. [ only attaches to an expression on the same line — xs followed by [0] on the next line is two statements.

Dict ignores order when compared (["a": 1, "b": 2] = ["b": 2, "a": 1]), but its Display follows the written order. keys()/values() also follow that order. Inserting an existing key preserves its position and overwrites its value.

map.from(entries) builds a Map<K, V> with a single sort from List<Entry<K, V>>; Entry<K, V> { key: K, value: V } comes from the prelude and is visible without import.

5.3 Option & Result

Option<T>    // variants: Some(T) | None
Result<T, E> // variants: Ok(T) | Err(E)

Sugar: T? = Option<T>. Some, None, Ok, Err are available without import.

5.4 Nominal typing

Two structs with identical fields are still different types. Likewise a struct and an enum. Assigning between them = compile error. There is no structural typing.

Nominal identity is the pair (package, name), not just the name: money.Price and user.Price are two different types.

5.4a Widening through embed

The only exception to nominal typing is a field marked embed:

export struct TableInfo {
  name: Str
  columns: List<ColumnInfo>
}

export struct UsersTable {
  embed table_info: TableInfo
  id: IntColumn
  name: StrColumn
}
  • UsersTable can be used in positions expecting TableInfo — as a function argument, a return value, an annotated binding, a struct field value, or a list/dict element — because the table_info field has exactly type TableInfo.
  • This relation is one step and only through the embed field: a C that embeds D cannot automatically be used as a type embedded by D. There is no covariance for List/Map/Dict/Option/Result.
  • Widening does not apply to generic parameters that are still inference variables; give such a parameter the concrete type Base if you want to accept a derived type.
  • An embed field remains an ordinary field: it must be filled by named argument at construction, participates in Eq/Ord/Display, and is read as users.table_info — not a promoted field. So users.name is always a field of UsersTable, not TableInfo.name.
  • At most one embed field per struct, and its type must be a struct (not an enum, primitive, collection, or type parameter). Embed cycles = compile error.
  • The name of the embed field is chosen by the author like an ordinary field and must be unique in that struct. Because the embed marker (not its name) carries the widening relation, the generator may choose any name that does not collide with any column; a column named embed can still be written embed: Str.

5.4b Functions as values

Function types are written fn(A, B) -> R. The lambda fn(x: Int) => x + 1 (or fn(x) => … when the type can be inferred from context) produces a value of function type, and that value can be stored in a let, parameter, function result, or package binding and called as f(x).

Restrictions that keep Eq/Ord total:

  • Functions must not be stored in struct fields, enum payloads, or inside List/Set/Map/Dict/Option/Result.
  • Functions cannot be compared (==, <) or to_string-ed.
  • A lambda captures values at the time the lambda is created, including let mut: later changes are invisible inside the lambda, and mutations inside the lambda do not leak out.
  • Generic functions cannot be used as values; wrap them in a concrete lambda.
  • ? inside a lambda returns from the lambda, and the lambda’s result type determines it.

5.5 Generics

  • Only on structs, enums, and functions.
  • Constraints are only built-in traits: Eq, Ord, Display. Map<K, V> requires K: Eq + Ord.
  • No higher-kinded types, no associated types, no default type parameters.

6. Declarations

6.1 Package

// src/money.lt
package money {
  export struct Price {
    amount: Int
    currency: Str
  }

  export fn format(p: Price) -> Str {
    `${p.amount / 100}.${p.amount % 100} ${p.currency}`
  }

  fn helper() -> Int { 0 }   // private: cannot be imported by another package
}

Rules:

  • package must wrap all declarations. There are no bare declarations at file top level, and no nested package.
  • One file contains exactly one package block. The file name is free; the package name is verified at import and becomes the output module name. A file without a package, or with more than one, is a compile error.
  • Packages are file-scoped. Package names must be unique within one dependency; two different dependencies may use the same name.
  • Package identity is (dependency, file path). Type identity remains nominal per loaded module, not determined by package name.
  • Package contents: structs, enums, functions, let bindings, and tests. No classes, no methods inside types.
  • Visibility is determined by per-declaration export; default private (visible only in that package). This rule applies to every call path: bare names, qualified paths, and receiver sugar p.f() — a private function cannot be called from another package through any path.
  • Package-level bindings are immutable, evaluated eagerly, and must not form cycles.

6.2 Struct

export struct User {
  name: Str
  age: Int
  address: Address?
}
  • Fields are immutable and read-only from outside. There are no private fields: named-argument construction across packages must be able to fill every field.
  • Construction requires named arguments, all fields required, order free: User(name: "Ana", age: 30, address: None).
  • No constructor, no inheritance, no override, no abstract.
  • One field may be marked embed (see §5.4a). That is not inheritance: the field remains an ordinary member and widening is only one step to that field’s type.
  • An empty struct is valid (export struct Unit {}), useful as a marker.
  • Generics attach to the struct: export struct Box<T> { value: T }.

6.3 Functions & receivers

export fn empty() -> Catalog { Catalog(books: []) }

export fn add(c: Catalog, b: Book) -> Catalog {
  Catalog(books: c.books.push(b))
}

export fn size(c: Catalog) -> Int { c.books.len() }

c.add(b) ≡ add(c, b); c.size() ≡ size(c).

Rules:

  • A receiver function is an ordinary function whose first parameter has a struct/enum type. No special marker, no self.
  • The sugar value.f(args) only applies when a function named f exists in the package where the value’s type is declared. There is no dynamic dispatch; the result is always f(value, args).
  • A receiver function must be in the same package as its receiver type (coherence). This is also what makes mapping to Go methods valid.
  • Overloading is only valid when the receiver type differs: fn len(p: Point) and fn len(s: Shape) may coexist. Overloading by name or arity is forbidden.
  • Parameters may only have nominal/primitive types; no varargs, no default values.
  • A function without a struct-typed parameter is an ordinary function (catalog.empty() only if empty takes a receiver; otherwise call empty()).

6.4 Enum

export enum Role {
  Admin
  Member(Int)
  Guest
}
  • Variants may have no payload or a payload (one or more types).
  • An enum without payload equals a typed constant.
  • No fields in an enum; behavior lives in package-level functions that take the enum as a parameter, and receiver sugar may be used (role.label() ≡ label(role)).
  • A variant is referenced as Role.Member(3); from another package with a qualifier (models.Role.Member(3)) or through destructuring.

6.5 Package-level bindings

package money {
  export let default_currency: Str = "IDR"
  let lookup: Map<Str, Int> = map.empty()
}
  • Immutable, eager, without parameters.
  • May refer to other bindings in the same package as long as no cycle is formed.
  • Exposed through export and accessed as money.default_currency or through destructuring.

6.6 Test

package money {
  test "formats with currency" {
    let p = Price(amount: 1250, currency: "IDR")
    expect.eq(format(p), "12.50 IDR")
  }
}
  • test "title" { ... } is a package item; titles are unique per package.
  • Not emitted into the library package (lt build); only lt test produces test files.
  • The test body is a normal statement block; no parameters, no return type.
  • Tests may use any declaration in their package, including private ones.

7. Statements & Expressions

Statements: let, destructuring let (let Point { x, y as py } = p), assignment (only for mut), return, if, for, while, break, continue, expressions. Two statements on the same line = compile error.

Expressions: literal, identifier, struct construction, function call, receiver call, field access, qualified path, [] list literal, [:]/["k": v] dict literal, match, if expression, lambda, template, tagged template, JSX, ?.

Blocks: only the body of fn, if branches, and match branches evaluate to their last expression. Standalone blocks are statement-only; let x = { … } is illegal.

Lambda: fn(x) => expr or fn(x) => { ... }. A lambda cannot mut-capture an outer variable (no mutable closures). A lambda cannot return Result and then use ? inside it.

match must be exhaustive at the top variant level. Patterns: _, None, Variant, Variant(p, ...) where p may be another pattern — so Ok(Value.Int(n)) and Some(Some(x)) are valid. Struct patterns are also allowed when the scrutinee is a struct: Point { x, y } and Tagged { point: Point { x, y } }; a field written without : binds a field of that name. Because there are no literal patterns, a struct pattern whose fields are all bindings/wildcards is irrefutable, and match still needs one irrefutable arm. Alternatives may be combined with | (E.A(n) | E.B(n)) as long as they all bind the same names and types. Guards are written pat if cond => …, evaluated after binding, and a guarded arm does not count as closing exhaustiveness. No struct destructuring, no literal patterns. Nested pattern exhaustiveness is not checked; a non-matching arm falls through to the next arm, and if none match the runtime reports unreachable.

match role {
  Role.Admin     => "admin"
  Role.Member(n) => `member-${n}`
  Role.Guest     => "guest"
}

Loops: for x in list, for x in set, for key in map, and for key in dict — Map/Dict are iterated through their keys (use .values() for the values), Set through its sorted elements. while cond. break and continue are only valid inside the nearest loop. Loop state changes only through local let mut.

Qualified paths: at most 3 segments.

SegmentFormExample
2package.{type|function|binding}money.Price, money.format(p), money.default_currency
3package.Type.Variantmodels.Role.Admin
4+nonemoney.Price.field = compile error

Resolution of the first segment: local binding → destructuring result name → package qualifier from import. If a name matches in more than one category = error, not silent resolution.


8. Operator Semantics

OperatorRule
+ - * (Int)Wrapping i64.
/ (Int)Integer division, truncating toward zero (-7 / 2 == -3). Divisor 0 = trap.
% (Int)Remainder, sign follows the dividend (-7 % 2 == -1). Divisor 0 = trap.
+ - * / (Float)IEEE-754. / 0.0 = ±Inf or NaN, not a trap.
- unary (Int)Wrap: -Int.min == Int.min.
== !=Value. Struct/enum: structural by content. Float follows IEEE (NaN != NaN).
< <= > >=Int, Float, Str (lexicographic per code point). Requires Ord.
&& ||Bool, short-circuit.
!Bool.

Mapping note: Python rounds down for // and its % follows the divisor — the emitter must wrap these operations so the result is identical to the rules above.


9. ? — Propagation

  • expr? on Option<T> is only valid in a function returning Option<U>.
  • ? must not be used inside a lambda: its return would exit the lambda, not the function.
  • expr? on Result<T, E> is only valid in a function returning Result<U, E>.
  • Option and Result must not be mixed in one function.
  • None/Err is returned directly; otherwise the value is extracted.

10. Built-in Traits

Three traits are known to the compiler. All are derived automatically for every struct and enum:

TraitDefault behavior
DisplayStructural format: User(name: "Ana", age: 30), Role.Member(3).
EqStructural comparison of all fields/variants.
OrdLexicographic over fields in declaration order; enum variants sorted in declaration order.
  • Eq and Ord cannot be overridden. Both are used by sort, Map, and Set, and all three targets implement them through different paths (sort.Slice, __lt__, comparator); allowing them to be overridden would break parity.
  • Display can be overridden by declaring a receiver function named to_string in the package where the type is declared: export fn to_string(p: Price) -> Str { … }.
  • Every value that has Display can be converted through to_string(). A user to_string wins over the built-in version, including inside ${…} interpolation.
  • Ordering is used internally by the runtime (sort, Map, Set) but is not yet available on the language surface: Ordering is rejected as a type and Ordering.Less is not a value. This is a conscious decision until there is a real need and constants in all three runtimes.

Ord is used by sort, Map, and Set:

  • struct: lexicographic over fields in declaration order (compared recursively with Ord).
  • enum: declaration order of variants, then payload.
  • Option/Result: fixed internal order (none < some, ok < err) for stability, not part of the public contract.

11. Templates & Tagged Templates

let s = `Hi ${user.name}, total ${n}`

enum SqlArg {
  I(Int)
  S(Str)
}

let q = query`SELECT * FROM users WHERE id = ${SqlArg.I(id)}`
  • In a plain template, ${expr} must have a type that has Display, and the result is always Str. Unit may not be interpolated. The Display used is the derived version or the user’s to_string version if one exists.
  • Multiline is verbatim: newlines and indentation inside the backticks are preserved as-is. There is no auto-dedent; use .trim_indent() from the stdlib.
  • Tagged template: the tag must be a path pointing to a package-level function (e.g. query, sql.query), with signature (List<Str>, List<T>) -> R. T is written concretely and must not use a type parameter.
  • Every ${expr} in a tagged template must be exactly of type T; there is no Display conversion, no implicit Some wrapping, no automatic variant selection. The value is passed as-is, so the tag can inspect it through match.
  • Mixed-type values are expressed with a user enum used as T.
  • The invariant remains parts.len() == values.len() + 1. There is no built-in tag and no automatic escaping.
  • To convert a value to Str in a ${…} position where T = Str, use to_string().

12. JSX

<Element tag="div" class_name="user">
  <Element tag="span">{user.name}</Element>
</Element>
  • The tag name = the name of a struct visible in scope (local, destructuring result, or package qualifier). A lowercase tag = compile error, because type names must be PascalCase and Go only exports capitalized identifiers.
  • Attributes = named arguments. Value: string literal or {expr}.
  • An attribute may be named like a keyword, because its position is always followed by = (<div class="x">). An attribute name that is not a struct field is still a compile error like any ordinary named argument.
  • Children are collected into the children argument only if the struct declares a children field. If there is no such field but there are children = compile error.
  • Plain text between tags = one Str child. Allowed only if the children field is of type List<Str> (or List<T> with T = Str).
  • <X /> = no children.
  • The opening and closing tags must match exactly.
  • JSX is an ordinary value construct: <Element …> ≡ Element(…). No lifecycle, no render, no framework.

13. Import

// local, without extension
import money { Price, format } "./wallet/money"

// qualifier (money.Price, money.format(...))
import money "./wallet/money"

// package and item aliases
import money as cash { Price as P } "./wallet/money"

// external: first segment = key in lt.toml
import post "acme/blog/post"

// group: one entry per line, no commas
import (
  money { Price } "./wallet/money"
  post  "acme/blog/post"
)

// re-export: explicit item list required
export import money { Price as P } "./wallet/money"
  • Only packages can be imported, not files and not loose symbols. The package name is written explicitly and verified to actually exist in the target file.
  • One file contains exactly one package. The file name is free; the import writes the package name explicitly and verifies it against the target file.
  • Specifiers are without extension. Those starting with ./ or ../ are local imports and resolve relative to the importing file as <specifier>.lt. Other specifiers are <key>/<path>; key must exist in [dependencies] in lt.toml.
  • There are no directory imports and no index files. Specifiers are mandatory; there is no implicit resolution.
  • Package identity is (dependency, file path). Package names must be unique within one dependency; two dependencies may both declare package user. If both are imported into the same file, both must use different aliases.
  • Destructuring ({ … }) is optional and may only name declarations that are exported or names re-exported by the target package. If omitted, the package is bound as a qualifier. Destructuring does not disable the qualifier: import money { Price } may still use money.format(...). An empty list {} = error.
  • Aliases (as) are allowed on qualifiers and on destructured names.
  • Groups import ( … ) are equivalent to writing entries one by one; grouping only, with no additional meaning at the semantic level. import . "path" (dot import) and import _ "path" (blank import) are rejected: every name is always referred to through a qualifier.
  • The from keyword is no longer used in imports; writing it produces an error that suggests the new form.
  • An import name that clashes with a local declaration, or with another import name, = compile error (there is no “local wins” rule).
  • Using a type/function from a package that is not imported = compile error.
  • An unused import = compile error. An entry is considered used when at least one of its bindings is referenced; export import is always considered used.
  • Import cycles = compile error, with a message showing the cycle.

Re-export

  • The form is export import money { Price as P } "./wallet/money". A non-empty item list is required; wildcards and forms without a list are rejected.
  • A re-exported name becomes part of this package’s API: consumers can write import facade { P } "./facade" or facade.P.
  • Re-export does not create a new type. facade.P and money.Price are the same nominal type; the emitter still refers to the originating package.
  • A re-exported name must be part of the originating package’s API: an exported declaration or an explicit re-export result from that package. A private name = error.
  • A name conflict with a local declaration or another re-export result = compile error.
  • Re-export does not propagate implicitly: a package only exposes the names it explicitly re-exports. Package qualifiers are not re-exported.

Manifest

External dependencies are declared in lt.toml at the project root:

[dependencies]
acme  = { git = "https://github.com/acme/lt-lib", version = "^1.2", root = "." }
utils = { path = "../utils" }
  • Dependency keys follow [a-z][a-z0-9_]* and become the first segment of an external specifier.
  • version accepts a semver range (^, ~, =, * in v1), an exact tag, or a 40-hex commit. Branches are rejected.
  • root is optional (default "."): the subdirectory inside the checkout that becomes the dependency’s package root and must contain that dependency’s lt.toml.
  • The v1 manifest only contains [dependencies]; [package], workspaces, and publishing metadata are deferred.
  • The project root = the nearest ancestor of the entry that has an lt.toml. Without lt.toml, only local imports are allowed.

Dependency resolution

  • Resolution is transitive: each dependency’s manifest is also read.
  • One version per source per build: the resolver picks the highest version satisfying all ranges. Ranges that cannot be reconciled = compile error, with the list of parents and their ranges.
  • v1 sources: git (https/ssh) and local paths. No registry.
  • Path dependencies are not pinned to a commit; always live. Their transitive dependencies still enter the lock.
  • Transport: git https/ssh, raw files over https, http:// only for localhost. Authentication uses git credentials / GITHUB_TOKEN. No custom signatures in v1.

Lockfile

  • lt.lock is a versioned-format resolution graph: canonical source, commit, root, sha256 per file, and edge requirements. An entry’s identity is (source, commit), not content.
  • lt.lock must be committed.
  • The build and check never write the lock. A missing, incomplete, or unsatisfying lock (against the manifest ranges) = error telling you to run lt update <key> or lt update --all.
  • lt update <key> re-resolves that key and its closure; lt update --all re-resolves the entire graph. lt add writes the manifest and lock; lt remove prunes the lock entries that are no longer reachable.
  • Source order during build: vendor/ → cache → fetch the locked commit. --offline forbids network entirely. The default cache is $XDG_CACHE_HOME/lt or ~/.cache/lt; LT_CACHE_DIR overrides it.
  • lt vendor copies the locked source tree into vendor/; path dependencies are not vendored.
  • lt migrate [--write] migrates old specifiers, import URLs, and multi-package files. Dry-run is the default.

14. Test

  • lt test -t <target> generates native test files and then runs them: vitest, pytest, go test. For TypeScript, lt test -t ts ... --run runs vitest; without --run it only emits.
  • test declarations are not emitted into the library package (lt build); only lt test produces test files.
  • Test titles are unique per package. The emitter maps titles to native function names and must detect mangling collisions.
  • Assertions only through the expect pseudo-package: expect.eq(a, b), expect.not_equal(a, b), expect.true(x), expect.false(x).
  • No mocking, no setup/teardown, no parallel tests. All tests must be deterministic and pure.
  • A target passes only if the entire conformance suite passes on that target.

15. Errors & Traps

Compile error (rejected by the compiler): every violation in this document, including naming, duplicate package names within one dependency, import cycles, unused imports, a lock that does not satisfy the manifest, ? in the wrong context, non-exhaustive match, unknown types, paths longer than 3 segments, lowercase JSX tags.

Trap (the program stops at runtime, cannot be caught from LT):

  • Int division/remainder by zero
  • Collection index out of bounds (List.get returns Option, so it does not trap)
  • unwrap() on None/Err
  • Unbounded recursion (stack overflow); the maximum depth differs per host and is not guaranteed to be uniform

Traps are mapped to the target’s native mechanism (panic/exception) but are never used as normal flow.


16. Output

  • One package → one host module. File wallet/money.lt with package money produces out/ts/src/wallet/money.ts, out/py/gen/wallet/money.py, and out/go/gen/wallet/money/money.go.
  • External dependency packages are emitted under the _deps prefix: out/ts/src/_deps/<key>/<dir>/<package>.ts, out/py/gen/_deps/<key>/<dir>/<package>.py, out/go/gen/_deps/<key>/<dir>/<package>/<package>.go. _deps is reserved at the source root.
  • The output module name = the file’s relative directory + the package name. Example: collections/map.lt with package map_case produces the module collections/map_case.
  • Tests and usage are only emitted for packages owned by the root project, not for dependency packages.
  • Output file names remain snake_case. struct/enum identity remains PascalCase. Function/field names are converted per the target convention by the emitter (snake_case for Python/Go, camelCase for TypeScript), with export mapped to export (TS), capitalization (Go), and a _ prefix for private ones (Python).
  • Every output package has one inline runtime file (_lingua_rt.ts, lt_runtime.py, lt/runtime.go).
  • Type & construction mapping table: see PLAN.md §5.
  • User code must pass tsc --strict, mypy --strict, as well as go vet and an empty gofmt -l. Canonical formatter: lt fmt.
  • Concrete mapping per backend: backends/typescript.md, backends/python.md, backends/go.md.

17. Stdlib v2

v1 pseudo-classes become lowercase pseudo-packages, consistent with the package naming rules. All are available without import.

SurfaceContents
Universal functionsto_string() -> Str for every value with Display; a user to_string wins, including in interpolation
strlen, trim, trim_indent, lower, upper, split, starts_with, ends_with, contains, replace, slice, chars, parse_int, parse_float
listlen, get(Int) -> T?, push, pop, map, filter, fold, any, all, sort, sort_by(Key), enumerate() -> List<Pair<Int, T>>, zip(List<U>) -> List<Pair<T, U>>, reverse, concat, contains, index_of, join(Str) -> Str (only List<Str>)
mapempty(), from(List<Entry>K, V>>), len, get(K) -> V?, insert, remove, keys, values, entries() -> List<Pair<K, V>>, contains_key
dictlen, get(Str) -> V?, insert(Str, V), remove(Str), keys() -> List<Str>, values() -> List<V>, entries() -> List<Pair<Str, V>>, contains_key(Str); built from the literal ["k": v]
setempty(), len, insert, remove, contains, union, intersect, difference
optionis_some, is_none, unwrap, unwrap_or, map, and_then
resultis_ok, is_err, unwrap, unwrap_or, map, map_err, and_then
mathabs, min, max, floor, ceil, round, sqrt, pow, pi — all Float
ordcmp(A, A) -> Ordering
jsonparse(Str) -> Result<Value, Str>, stringify(Value) -> Str, pretty(Value, Int) -> Str
Valuebuilt-in enum from the value prelude: Null, Bool(Bool), Int(Int), Float(Float), Str(Str), Array(List<Value>), Object(Dict<Value>)
expecteq, not_equal, true, false (only valid inside a test)
Built-in enumsOrdering (Less, Equal, Greater) and Value (see the table above) — both from the prelude

json.parse accepts integral numbers as Value.Int and the rest as Value.Float; objects become Value.Object(Dict<Value>) so key order is preserved; duplicate keys: last wins; trailing garbage and depth over 128 are errors. json.stringify writes compact JSON without spaces, follows the Dict key order, prints integral floats with .0 so Int/Float are not lost, and writes non-ASCII as-is. The package name value is reserved for the prelude.

Usage: built-in functions are called only through receiver sugar (xs.map(…), s.len(), m.get(k), o.is_some()). The qualified function form (list.map(xs, …), str.len(s)) is not yet supported; the only paths available are map.empty(), set.empty(), math.*, and expect.*. Pseudo-package names are reserved keywords: declaring your own package str { … } = compile error.

Stdlib changes are not breaking changes as long as old signatures are preserved.

Grammar

The formal grammar is grammar.ebnf. It covers the lexical layer and the surface syntax of v2.

(* =====================================================================
   Lingua Tungga — Grammar v2.1
   Scope: v2 — `class` removed, replaced by `package` + `struct` + receiver
   functions. See docs/v2-decisions.md for the rationale of each decision.
   Import v3 amendment (target 0.7.0): exactly one package per file,
   extension-less specifiers, and `export import`. See docs/import-v3.md.
   Notation: EBNF, `,` = sequence, `[ ]` = optional, `{ }` = zero or more,
           `|` = alternative.
   ===================================================================== *)

(* ---------- Program ---------- *)

Program        = { Import } , PackageDecl , EOF ;

(* Import points to a PACKAGE, not a file. Local specifiers start with `./` or
   `../` without an extension; external specifiers have the form `<key>/<path>`
   with `key` from `[dependencies]` in lt.toml. The package name is stated
   explicitly and verified to exist in the target file.
   Entries may stand alone or be grouped in one `( ... )` block, one entry per
   line without commas. `export import` stands alone only, must have an item
   list, and may not appear inside a group. *)
Import         = "import" , ( ImportEntry | ImportGroup )
               | "export" , "import" , ExportEntry ;

ImportGroup    = "(" , { ImportEntry } , ")" ;

ImportEntry    = Identifier , [ "as" , Identifier ] ,
                 [ "{" , ImportList , "}" ] , StringLit ;

(* Explicit re-export: the qualifier stays locally bound, but only the items
   inside `{ ... }` enter the package API. No wildcards. *)
ExportEntry    = Identifier , [ "as" , Identifier ] ,
                 "{" , ImportList , "}" , StringLit ;

ImportList     = ImportItem , { "," , ImportItem } ;

ImportItem     = Identifier , [ "as" , Identifier ] ;

(* Must wrap every declaration. No bare declarations at top level, no nested
   packages. Exactly one per file. *)
PackageDecl    = "package" , Identifier , "{" , { PackageItem } , "}" ;

PackageItem    = StructDecl | EnumDecl | FnDecl | Binding | TestDecl ;

(* ---------- Declarations ---------- *)

StructDecl     = [ "export" ] , "struct" , Identifier , [ Generics ] ,
                 "{" , { FieldDecl } , "}" ;

(* `embed` is a contextual marker before the field name. A field actually named
   `embed` is written `embed: Type` and is not treated as a marker. *)
FieldDecl      = [ "embed" ] , Identifier , ":" , Type ;

EnumDecl       = [ "export" ] , "enum" , Identifier , [ Generics ] ,
                 "{" , { Variant } , "}" ;

Variant        = Identifier , [ "(" , Type , { "," , Type } , ")" ] ;

(* No methods inside types. Receiver functions are ordinary functions whose
   first parameter is of struct/enum type, and must live in the same package as
   that type. *)
FnDecl         = [ "export" ] , "fn" , Identifier ,
                 "(" , [ ParamList ] , ")" , [ "->" , Type ] , Block ;

ParamList      = Param , { "," , Param } ;

Param          = Identifier , ":" , Type ;

(* Package-level binding: immutable, eager, without initialization cycles. *)
Binding        = [ "export" ] , "let" , Identifier , [ ":" , Type ] , "=" , Expr ;

(* Test titles are string literals, unique per package. *)
TestDecl       = "test" , StringLit , Block ;

(* ---------- Types ---------- *)

Type           = TypePath , [ Generics ] , [ "?" ]
               | "fn" , "(" , [ Type , { "," , Type } ] , ")" , [ "->" , Type ] ;

(* At most 3 segments: package.Type , package.Type.Variant , package.fn.
   This limit is enforced semantically, not syntactically. *)
TypePath       = Identifier , { "." , Identifier } ;

Generics       = "<" , Type , { "," , Type } , ">" ;

(* ---------- Statement ---------- *)

Block          = "{" , { Stmt } , "}" ;

Stmt           = LetStmt | AssignStmt | ReturnStmt
               | IfStmt | ForStmt | WhileStmt | BreakStmt | ContinueStmt | ExprStmt ;

(* Statements are separated by newlines inside a Block. *)
BreakStmt      = "break" ;

ContinueStmt   = "continue" ;

LetStmt        = "let" , [ "mut" ] , Identifier , [ ":" , Type ] , "=" , Expr ;

AssignStmt     = Identifier , "=" , Expr ;

ReturnStmt     = "return" , [ Expr ] ;

IfStmt         = "if" , Expr , Block , [ "else" , ( IfStmt | Block ) ] ;

(* Iterable: List (elements), Map (key), Dict (key). Set is not supported yet. *)
ForStmt        = "for" , Identifier , "in" , Expr , Block ;

WhileStmt      = "while" , Expr , Block ;

ExprStmt       = Expr ;

(* ---------- Expressions ----------
   `if` and `match` are expressions; as statements they may be followed without
   a semicolon because statements are separated by newlines. *)

Expr           = Lambda | OrExpr ;

Lambda         = "fn" , "(" , [ LambdaParams ] , ")" , "=>" , ( Expr | Block ) ;

LambdaParams   = LambdaParam , { "," , LambdaParam } ;

LambdaParam    = Identifier , [ ":" , Type ] ;   (* the type may be inferred from context *)

OrExpr         = AndExpr , { "||" , AndExpr } ;

AndExpr        = EqExpr , { "&&" , EqExpr } ;

EqExpr         = RelExpr , [ ( "==" | "!=" ) , RelExpr ] ;

RelExpr        = AddExpr , [ ( "<" | "<=" | ">" | ">=" ) , AddExpr ] ;

AddExpr        = MulExpr , { ( "+" | "-" ) , MulExpr } ;

MulExpr        = UnaryExpr , { ( "*" | "/" | "%" ) , UnaryExpr } ;

UnaryExpr      = [ ( "!" | "-" ) ] , PostfixExpr ;

PostfixExpr    = Primary , { PostfixOp } ;

(* `p.f()` on a struct-typed value whose package has a receiver function `f`
   is sugar for `f(p)`. There is no dynamic dispatch. *)
PostfixOp      = "." , Identifier
               | "(" , [ ArgList ] , ")"
               | "[" , Expr , "]"          (* partial lookup: Option<T> *)
               | "?" ;

ArgList        = NamedArg , { "," , NamedArg }
               | Expr , { "," , Expr } ;      (* must not be mixed *)

NamedArg       = Identifier , ":" , Expr ;    (* only valid in struct construction / JSX *)

Primary        = IntLit | FloatLit | StringLit | BoolLit
               | "None"
               | Identifier , [ Generics ]      (* variable / type reference *)
               | ListLit
               | DictLit
               | Template
               | TaggedTemplate
               | Jsx
               | IfExpr
               | MatchExpr
               | "(" , Expr , ")" ;

IfExpr         = "if" , Expr , Block , [ "else" , ( IfExpr | Block ) ] ;

MatchExpr      = "match" , Expr , "{" , { MatchArm } , "}" ;

MatchArm       = Pattern , { "|" , Pattern } , [ "if" , Expr ] , "=>" , ( Expr | Block ) ;

Pattern        = "_"
               | "None"
               | TypePath , [ "(" , [ Pattern , { "," , Pattern } ] , ")" ] ;

ListLit        = "[" , [ Expr , { "," , Expr } ] , "]" ;

(* Dict: keys are always string literals; an empty one is written "[:]". *)
DictLit        = "[" , ( ":" | StringLit , ":" , Expr , { "," , StringLit , ":" , Expr } ) , "]" ;

(* ---------- Template ---------- *)

Template       = "`" , { TemplatePart } , "`" ;

TemplatePart   = Text , [ "${" , Expr , "}" ] ;

(* A tag is a path to a package-level function, not a method. *)
TaggedTemplate = TypePath , Template ;

(* ---------- JSX ---------- *)

(* Tag name = a struct name visible in scope. Attribute = field name.
   Lowercase = compile error (type names must be PascalCase). *)
Jsx            = "<" , TypePath , { JsxAttr } , ( "/>" | ">" , { JsxChild } , "</" , TypePath , ">" ) ;

JsxAttr        = Identifier , "=" , ( StringLit | "{" , Expr , "}" ) ;

JsxChild       = Jsx | JsxText | "{" , Expr , "}" ;

JsxText        = { Character - ( "<" | "{" ) } ;

(* ---------- Lexical ---------- *)

Identifier     = letter , { letter | digit | "_" } ;

IntLit         = digit , { digit | "_" } ;

FloatLit       = digit , { digit | "_" } , "." , digit , { digit | "_" } ,
                 [ ( "e" | "E" ) , [ "+" | "-" ] , digit , { digit } ] ;

BoolLit        = "true" | "false" ;

StringLit      = '"' , { StringChar } , '"' ;

StringChar     = ordinary_char | Escape ;

Escape         = "\\" , ( "n" | "t" | "r" | "\\" | '"' | "`" | "$" )
               | "\\u{" , hex , { hex } , "}" ;

Comment        = "//" , { any - newline } , newline
               | "/*" , { any - "*/" } , "*/" ;     (* not nested *)

(* ---------- Keywords (reserved) ---------- *)
(* package export struct enum fn test let mut return if else
   for in while match import from as true false None _  *)

(* v1 keywords that were removed STAY reserved so the errors are clear:
   class pub static self  *)

(* `embed` is not a full keyword: it is only a marker when followed by a name
   and `:` inside a struct body; `embed` can still be a field name. *)

(* Soft keywords (see spec §7). Positions that are definitely names accept
   keywords: after ".", and before ":" (field, label, parameter, JSX attribute).
   Function/binding/package names and import items only accept from, as, in. *)
NameAfterDot   = Identifier | Keyword ;   (* b.from, b.match *)

SoftName       = Identifier | "from" | "as" | "in" ;

FieldName      = NameAfterDot ;           (* always followed by ":" *)
AttrName       = NameAfterDot ;           (* always followed by "=" *)

The grammar describes syntax only. Type checking, naming rules, exhaustiveness, visibility, and import resolution are specified in the language specification.

Standard library

The standard library is built into the compiler. There is no import and no package to install. Every function is called through receiver sugar: xs.map(…), s.len(), m.get(k), o.is_some().

The qualified forms (list.map(xs, …), str.len(s)) are not available. The only qualified paths are map.empty(), set.empty(), math.*, and expect.*.

Universal

CallResult
value.to_string()Str for every value with Display
to_string(value) equivalentuses a user-defined to_string(receiver) when the type declares one, including inside ${…}

Str

MethodResult
len()Int, number of Unicode code points
trim(), trim_indent()Str
lower(), upper()Str
split(sep)List<Str>
starts_with(prefix), ends_with(suffix), contains(needle)Bool
replace(from, to)Str
slice(start, end)Str, code-point indices
chars()List<Str>
parse_int()Option<Int>
parse_float()Option<Float>

List<T>

MethodResult
len()Int
get(index)T?
push(value)List<T>
pop()T?
map(fn)List<U>
filter(fn)List<T>
fold(initial, fn)accumulator type
any(fn), all(fn)Bool
sort(), reverse()List<T>
sort_by(fn)List<T>
enumerate()List<Pair<Int, T>>
zip(other)List<Pair<T, U>>
concat(other)List<T>
contains(value)Bool
index_of(value)Int?
join(sep)Str, only for List<Str>

Map<K, V> and Set<T>

Map is ordered by key. Build one from map.empty(); there is no literal.

Map<K, V>Result
len()Int
get(key)V?
insert(key, value)Map<K, V>
remove(key)Map<K, V>
keys()List<K>
values()List<V>
entries()List<Pair<K, V>>
contains_key(key)Bool

map.from(entries) builds a map from List<Entry<K, V>>. Entry comes from the prelude.

Set<T>Result
len()Int
insert(value)Set<T>
remove(value)Set<T>
contains(value)Bool
union(other), intersect(other), difference(other)Set<T>

Set iterates in sorted order. Build one from set.empty().

Dict<V>

Dict has Str keys and preserves insertion order. It is built from a literal: ["a": 1, "b": 2], or [:] for empty.

MethodResult
len()Int
get(key)V?
insert(key, value)Dict<V>
remove(key)Dict<V>
keys()List<Str>
values()List<V>
entries()List<Pair<Str, V>>
contains_key(key)Bool

Equality ignores order; display and iteration follow insertion order. Inserting an existing key keeps its position and replaces the value.

Option<T> and Result<T, E>

Option<T>Result
is_some(), is_none()Bool
unwrap()T, traps on None
unwrap_or(default)T
map(fn)Option<U>
and_then(fn)Option<U>; the lambda must return an Option
Result<T, E>Result
is_ok(), is_err()Bool
unwrap()T, traps on Err
unwrap_or(default)T
map(fn)Result<U, E>
map_err(fn)Result<T, F>
and_then(fn)Result<U, E>; the lambda must return a Result

math

All functions take and return Float where applicable:

math.abs, math.min, math.max, math.floor, math.ceil, math.round, math.sqrt, math.pow, math.pi.

json

CallResult
json.parse(text)Result<Value, Str>
json.stringify(value)Str
json.pretty(value, indent)Str

json.parse reads integral numbers as Value.Int, other numbers as Value.Float, and objects as Value.Object(Dict<Value>), preserving key order. The last duplicate key wins. Trailing garbage and nesting deeper than 128 are errors.

json.stringify writes compact JSON, follows Dict key order, prints integral floats with .0, and leaves non-ASCII text as-is.

Value is the prelude enum:

enum Value {
  Null
  Bool(Bool)
  Int(Int)
  Float(Float)
  Str(Str)
  Array(List<Value>)
  Object(Dict<Value>)
}

ord

ord.cmp(a, b) returns Ordering. The Ordering type is used internally by sort, Map, and Set, but it is not exposed on the language surface yet: Ordering is rejected as a type and Ordering.Less is not a value.

expect

Only valid inside a test block:

CallMeaning
expect.eq(a, b)values are equal
expect.not_equal(a, b)values differ
expect.true(x)value is true
expect.false(x)value is false

Complete example

package list_query {
  export fn index_of(xs: List<Int>, needle: Int) -> Option<Int> {
    xs.index_of(needle)
  }

  export fn at(xs: List<Int>, index: Int) -> Option<Int> {
    xs.get(index)
  }

  export fn has_big(xs: List<Int>) -> Bool {
    xs.any(fn(x) => x > 1)
  }

  test "contains and index" {
    expect.true([1, 2, 3].contains(2))
    expect.eq(index_of([1, 2, 3], 3), Some(2))
  }

  test "safe get" {
    expect.eq(at([1, 2], 1), Some(2))
    expect.eq(at([1, 2], 9), None)
  }

  test "any and all" {
    expect.true(has_big([1, 2]))
    expect.false([1, 2].all(fn(x) => x > 1))
  }
}

Command line

The binary is lt. Paths may be files or directories; a directory is searched recursively for *.lt.

lt init [dir] [--name <pkg>] [--force]  create a package (cwd by default)
lt check [--offline] <path>...          resolve imports and type check
lt fmt [--check] <path>                 format in place, or check formatting
lt ast <path>                           dump the AST (debugging)
lt build -t ts|py|go [--offline] <entry>    compile a package
lt test  -t ts|py|go [--offline] <entry>... emit and optionally run tests
lt ir <entry>                           dump the typed IR (debugging)
lt add <key> --git <url> --version <req> [--root <dir>]
lt add <key> --path <dir> [--root <dir>]
lt remove <key>                         remove a dependency
lt update <key>|--all                   re-resolve dependencies, rewrite lt.lock
lt vendor [--offline]                   copy locked sources into vendor/
lt migrate [--write]                    migrate v2 imports to v3
lt lsp                                  LSP server over stdio
lt playground                           generate the static example gallery

lt init

lt init                 # current directory
lt init money           # ./money
lt init money --name billing
lt init money --force

Creates lt.toml, src/<package>.lt, and .gitignore with /out. The package name is derived from the directory and normalized to lowercase_snake_case; --name overrides it. Existing files are not overwritten unless --force is given.

lt check

lt check src/
lt check --offline src/

Resolves the import graph and type-checks every entry. Diagnostics are printed with a source snippet. Exit code is 1 when any file fails and 0 otherwise. --offline forbids network access; an incomplete lt.lock is an error.

lt fmt

lt fmt src/
lt fmt --check src/

lt fmt rewrites files in the canonical form. lt fmt --check prints the files that differ and exits 1 without writing. Formatting is idempotent.

lt build

lt build -t ts src/money.lt
lt build -t py src/money.lt --out out
lt build -t go src/money.lt --offline
FlagDefaultMeaning
-t, --targettsts, py, or go
--outoutoutput root; the target name is appended
--offlineoffforbid network access

build writes the library package only. Test declarations stay out of the output. It never writes lt.lock.

lt test

lt test -t ts tests/*.lt --out out/conf --run
FlagDefaultMeaning
-t, --targettsts, py, or go
--outoutoutput root; the target name is appended
--runoffrun vitest, pytest, or go test
--usageoffalso emit a runnable calling example per package
--offlineoffforbid network access

Without --run, the generated files are written and the command prints the native command to run. --usage is used by the documentation gallery.

Dependencies

lt add foo --git https://github.com/foo/bar --version "^1.2"
lt add foo --git https://github.com/foo/bar --version "^1.2" --root packages/foo
lt add utils --path ../utils
lt remove foo
lt update foo
lt update --all
lt vendor
lt vendor --offline
  • add writes the dependency to lt.toml. --root selects a subdirectory inside the checkout.
  • remove deletes it from lt.toml and lt.lock.
  • update resolves versions and rewrites lt.lock; --all walks the whole graph.
  • vendor copies locked sources into vendor/ for offline builds.

See Packages and dependencies and import v3.

lt migrate

lt migrate          # report v2 imports that need rewriting
lt migrate --write  # rewrite them in place

lt ast and lt ir

lt ast src/money.lt
lt ir src/money.lt

Both print a Rust debug representation to stdout. They are debugging aids, not a stable format.

lt lsp

lt lsp

An LSP server over stdio: diagnostics, hover, definition, references, completion, signature help, symbols, highlights, formatting, rename, and import quick fixes.

lt playground

lt playground
lt playground --root playground --out out/playground
lt playground --allow-stale

Generates the static gallery at out/playground/index.html. --allow-stale permits generation when evidence.json does not match the current cases.

Exit codes

CodeMeaning
0success
1compilation, formatting, dependency, or test failure
2invalid command line

Package manager

The full design and behavior are in import-v3.md. Summary:

  • External dependencies are declared in lt.toml ([dependencies]), not on import lines. Imports use <key>/<path>.
  • v1 sources: git (https/ssh) and local paths. No registry.
  • Versions: semver ranges, exact tags, or 40-hex commits. Transitive resolution with one version per source.
  • lt.lock is the resolution graph: source, commit, root, sha256 per file, and requirement edges. Build/check are read-only; only lt add/lt update write the lock.
  • Cache: $XDG_CACHE_HOME/lt or ~/.cache/lt; LT_CACHE_DIR overrides it. lt vendor copies locked sources to vendor/ for offline builds.
  • Commands: lt add, lt remove, lt update <key>|--all, lt vendor.

LT import v3 — Decision Ledger

Status: in effect (0.7.0). This design is implemented. This document is the source of truth for the import design. Related amendments have landed in spec.md (§1, §6.1, §13, §15, §16) and grammar.ebnf. package-manager.md is the operational summary. Implementation of phases 0–5 has landed; see CHANGELOG.md.

The change in one sentence: package identity moves from a global name to (dependency, path), external dependencies move to the manifest, and the lock becomes read-only during builds.


1. The problem addressed

The v2 design is sound for a single small project, but it has a ceiling:

  • Package names are unique per build, so two dependencies that both have package user cannot coexist. Aliases do not help because the loader rejects before the alias is read.
  • File paths are public API. Moving a file breaks every import.
  • There is no manifest. A version is a raw URL on the import line; there is no dependency graph, per-dependency update, or frozen mode for CI.
  • lt build and lt check write lt.lock silently.
  • Multi-package files share one import list, and importing one package still loads and emits every package in that file.
  • Unused imports are never reported.

What is not changed because it is already right: mandatory qualifiers, per-declaration export, rejection of dot/blank imports, rejection of import cycles, and the mapping of one package to one host module.


2. Decisions

#DecisionRationale
2.1Package identity = (dependency root, file path). Package names are unique per dependency, not per build.Removes the scaling wall; two libraries may use the same package name.
2.2Two dependencies may both declare package user. If both are imported into the same file, both must be aliased differently; the error only occurs when bindings collide.Aliases only become useful once global uniqueness is dropped. Same model as Go.
2.3One file contains exactly one package. Multi-package per file is removed.Imports become package-scoped, the loader loads only what is referenced, and package = file = output module.
2.4File names are free; the package name is written in the import and verified against the target file. Output module name = directory + package name.The playground and conformance use path casing different from package names; forcing stem = name would break that convention with no semantic benefit.
2.5Specifiers without an extension. Local: ./wallet/money. External: acme/wallet/money, first segment = manifest key.The unit of import is the package, not the file. Single resolution: <path>.lt.
2.6External dependencies are declared only in lt.toml. Local imports stay relative and need no manifest.A single place for versions, sources, and dependency edges.
2.7Manifest v1 contains only [dependencies]. [package], workspaces, and publishing metadata are deferred.Metadata nobody uses is better not invented.
2.8v1 sources: git (https/ssh) and local paths. No registry.Covers early ecosystem needs without building a server, auth, and publishing.
2.9Versions are written as semver ranges, exact tags, or 40-hex commits. Branches are rejected. The lock always pins a commit.Reproducibility without forcing every consumer to bump a version manually on a diamond dependency.
2.10Resolution is transitive, one version per source per build: the highest version satisfying all ranges. Irreconcilable ranges = error.A model that can be explained; multi-version splits type identity and output size.
2.11lt build and lt check never write the lock. An unlocked dependency = an error telling you to run lt update.A lock only means something if a build cannot change it silently.
2.12lt.lock is a versioned-format resolution graph: canonical source, commit, root, sha256 per file, and requirement edges. Entry identity = (source, commit), not content.Enough for per-dependency updates, conflict explanation, and transport integrity.
2.13Path dependencies are not pinned to commits — always live — but their transitive dependencies still enter the lock.Local sources are part of the project, not downloaded artifacts.
2.14Unused imports = a compile error, with autofix. Definition: at least one binding from that import entry is referenced.Dead imports are dependencies that should not be resolved.
2.15Explicit per-name re-export: export import money { Price as P } "./wallet/money". The item list is mandatory; wildcards and list-less forms are rejected. The qualifier stays locally bound but is not re-exported.A stable façade without resurrecting nested namespaces or from.
2.16Re-export is a name alias, not a new type. facade.P and money.Price are the same nominal type.Two identical types that are not assignable to each other are a design bug, not a feature.
2.17Dependency output uses the _deps prefix: src/_deps/<key>/<path>.ts, gen/_deps/<key>/<path>/<package>.go. _deps is reserved at the source root.A stable namespace with no collision with local packages.
2.18Transport: git https/ssh, raw files over https, http:// only for localhost. Auth via git credentials / GITHUB_TOKEN. No custom signatures in v1.Consistent with the reproducibility claim; signatures are a project of their own.
2.19vendor/ is optional and may be committed. Source order: vendor → cache → fetch the locked commit. --offline forbids the network. Path dependencies are not vendored.Offline-first without adding a new way to change versions.
2.20v1 commands: lt add, lt remove, lt update <key>/--all, lt vendor, lt migrate. No lt install.One explicit place that writes the lock.
2.21lt build stays entry-based; unreachable local packages are not emitted.Determinism and minimal output.
2.22lt migrate handles mechanical changes and rejects ambiguous cases. Dry-run by default; --write applies.Humans should see file changes before they are written.
2.23Go constraints remain hard: one package per output directory, no import cycles, Go-valid package names.Go is a first-class target; an import graph that cannot be emitted to Go must not pass.
2.24Deferred: registry, publishing, multi-version per source, workspaces, signatures.Keeps v1 shippable and testable.

3. Syntax

// src/app.lt
// imports come before the package block

// local, no extension
import money { Price, format } "./wallet/money"
import money as cash { Price as P } "../shared/money"

// external: the first segment is a key in lt.toml
import post "acme/blog/post"

// groups are still allowed; one entry per line, no commas
import (
  money { Price } "./wallet/money"
  post  "acme/blog/post"
)

// façade: only the items inside { … } enter this package's API
export import money { Price as P } "./wallet/money"

Syntax rules:

  • import always comes at the top of the file, before the package block.
  • export import is valid only as a single entry, not inside a group.
  • export import must have a non-empty item list.
  • The qualifier (money) stays bound after destructuring and after export import, but the qualifier is not re-exported.
  • Dot imports, blank imports, and from are still rejected with dedicated messages.
  • Empty item lists {} and empty import groups () remain errors.

4. Semantics

4.1 Project root and resolution

  1. Project root = the nearest ancestor of the entry that has lt.toml. Without lt.toml, the project may only use local imports.
  2. A specifier starting with ./ or ../ resolves relative to the importing file: <specifier>.lt. There are no directory imports and no index files.
  3. Any other specifier is treated as <key>/<path>: key must exist in [dependencies]. Target file = <checkout>/<root>/<path>.lt.
  4. Every loaded file must declare exactly one package. File names are free; the package name determines identity and the output module name.
  5. Package names must be unique within one dependency. Two different dependencies may use the same name.
  6. Import cycles are detected on the file/package graph, with a message showing the cycle chain.

4.2 Imports and aliases

  • import money "./wallet/money" binds the qualifier money.
  • import money { Price, format } "./wallet/money" binds the qualifier money and the names Price/format without a qualifier.
  • import money as cash { Price as P } "./wallet/money" binds cash and P.
  • An import name must not shadow a local declaration or another import name.
  • If two packages with the same name from two dependencies are imported into the same file, both must use different aliases. The error only appears when bindings collide, not when the package declaration is read.
  • Using a type/function from a package that is not imported remains a compile error; there is no implicit resolution.

4.3 Unused import

  • An import entry counts as used if at least one of its bindings is referenced, including in type positions, inside template strings, and in export import.
  • export import always counts as used because it is part of the API.
  • An unused entry = compile error. Autofix removes that entry; if the entry is the only content of a group, the group is removed too.
  • v1 does not check for unused destructured items as long as the import entry itself is used.

4.4 Re-export

  • export import money { Price as P } "./wallet/money" adds P to this package’s export table. A consumer can write import facade { P } "./facade" or import facade "./facade" and then facade.P.
  • A re-exported name must be part of the origin package’s API: a declaration with export or the result of an explicit re-export from that package. Private names = error.
  • Re-exports may be aliased; a conflict with a local declaration or with another re-export result = error.
  • A re-export does not create a new type. Nominal identity stays with the origin package, and the emitter refers to the origin module, not the façade package.
  • Re-exports are not implicitly transitive: package A only exposes the names it explicitly re-exports.
  • Because import cycles are forbidden, the re-export graph cannot loop.

4.5 Versions and conflicts

  • The manifest writes semver ranges, exact tags, or 40-hex commits. The tag v1.2.0 normalizes to 1.2.0; non-semver tags are valid only as exact versions.
  • v1 range operators: ^, ~, =/exact, and *. Other comparison operators are not supported yet and are rejected as an exact version/tag that is not found.
  • The resolver reads each dependency’s manifest, collects all requirements, then picks the highest version that satisfies all of them.
  • If no version satisfies all ranges, the build fails and prints every parent with its range.
  • One source has only one version per build. There is no side-by-side version selection in v1.
  • The lock stores the chosen commit; a build never re-selects a version.

4.6 Read-only lock

  • lt build/lt check verify that the lock satisfies the current manifest. A missing, incomplete, or non-satisfying lock = an error with the repair command (lt update <key> or lt update --all).
  • lt update <key> re-resolves that key and its closure. If the change touches a shared dependency, other entries are updated too and reported.
  • lt update --all re-resolves the whole graph.
  • lt add writes the manifest and the lock; lt remove removes the manifest then prunes lock entries that are no longer reachable.

5. Manifest

# lt.toml
[dependencies]
acme  = { git = "https://github.com/acme/lt-lib", version = "^1.2", root = "." }
utils = { path = "../utils" }
  • Dependency keys follow [a-z][a-z0-9_]* and become the first segment of external specifiers.
  • git + version (required) or path (required); the two must not appear together.
  • root is optional, default ".": the subdirectory inside the checkout that becomes the dependency’s package root. That directory must contain the dependency’s lt.toml.
  • No [package], workspaces, or publishing fields in v1.
  • The manifest is written by hand or via lt add; lt fmt does not touch it in v1.

6. Lock

Format sketch (not a final byte contract; the content is what is locked):

version = 1

[[root]]
key = "acme"
source = "git+https://github.com/acme/lt-lib"

[[package]]
source = "git+https://github.com/acme/lt-lib"
commit = "0123456789abcdef0123456789abcdef01234567"
root = "."

[[package.files]]
path = "wallet/money.lt"
sha256 = "…"

[[package.dependencies]]
key = "utils"
source = "git+https://github.com/acme/lt-utils"
commit = "89abcdef0123456789abcdef0123456789abcdef"
requirement = "^2.0"
  • source is the canonical normalized URL (host, path, no .git, no trailing slash). The ssh and https forms of the same repo normalize to the same identity.
  • commit is always 40-hex for git. Path dependencies still get an entry (without commit, source path+… relative to the project root) so that edges and prunes can still be tracked; their content is always live and not verified from the lock.
  • files records every file actually loaded, with the sha256 of its content.
  • dependencies records requirement edges, so conflicts can be explained and per-key updates know what changed.
  • version is the lock format version. An old lock without version = an error telling you to run lt update --all.

7. Output

OriginTypeScriptPythonGo
Localsrc/<dir>/<package>.tsgen/<dir>/<package>.pygen/<dir>/<package>/<package>.go
Dependencysrc/_deps/<key>/<dir>/<package>.tsgen/_deps/<key>/<dir>/<package>.pygen/_deps/<key>/<dir>/<package>/<package>.go

The paths above are relative to the target output directory (out/ts, out/py, out/go), following the existing emitter convention.

  • _deps is reserved at the source root; a project must not have a directory named _deps containing local sources.
  • Tests and usage are emitted only for packages owned by the root project, not for dependency packages.
  • The runtime stays one file per output package; dependency modules import the runtime with a relative path computed by the emitter.
  • Type identity stays nominal per module; the output path does not change identity.
  • Source file names are free; the output module uses the file’s directory + the package name.

8. Commands

lt add acme --git https://github.com/acme/lt-lib --version "^1.2"
lt add utils --path ../utils
lt remove acme
lt update acme
lt update --all
lt vendor
lt build -t ts src/app.lt
lt check src/
lt migrate [--write]
  • build/check/test/vendor accept --offline; build/check are read-only with respect to the lock and manifest.
  • vendor copies the locked source tree from the cache (or fetches the locked commit) into vendor/; --offline forbids the network.
  • migrate is dry-run by default; --write applies.

9. Migration

lt migrate handles:

  1. Removing .lt from every local specifier.
  2. Moving URL imports into [dependencies] entries. The key is derived from the repo name; the path inside the repo becomes part of the specifier.
  3. Splitting multi-package files into one file per package, copying only the imports each package actually uses.
  4. Not renaming files: file names are free and package names are preserved.

It refuses and stops with a clear message when:

  • There are two different URLs/refs for the same source (violating one version per source).
  • A dependency key already used by another source = error; choose another key manually.
  • A file name produced by the split is already used by another package.
  • An import cannot be mapped to a path inside the repo (e.g. a non-git URL).

Dry-run prints the plan per file; --write then writes. After migration, the user runs lt update --all to write a new lock.

This repo itself has ~8 import sites and zero multi-package files, so its migration is small. File names do not need to change because file names need not match package names.


10. Implementation plan

PhaseContentsCrate
0This document, spec/grammar amendments, breaking-release notesdocs/
1One package per file, extension-less specifiers, export import, unused imports, per-dependency uniquenesslt-syntax, lt-hir, lt-lsp
2lt.toml, git/path resolver + semver + transitive, lock graph, read-only build/checklt-pkg, lt-hir, lt-cli
3_deps output, test/usage filtering, runtime pathslt-ir, lt-emit-*
4lt add/remove/update/vendor/migrate, error messages, manifest-aware LSPlt-cli, lt-lsp
5New conformance, examples, docs, CItests/, examples/, docs/

Phase 1 deliberately does not depend on the resolver: language changes can land and be tested with local imports only, before lt-pkg is torn apart.


11. v1 non-goals

Registry and publishing, multi-version per source, workspaces, multi-package per file, custom signatures, and [package] in the manifest. Accepted consequences: large packages must be split into several packages or use a re-export façade, and the resolver depends on the git binary (not a Git library).


12. Implementation notes

  • The git resolver uses the git CLI in v1 (ls-remote, fetch, checkout); semver uses the semver crate. Both can be replaced without changing the manifest/lock.
  • The ModuleId type stays per package; what changes is the loader key and the uniqueness validation.
  • The checker must extend the export table with re-export results before validating import items, but TypeName.module still points to the origin package.
  • The emitter computes relative paths from the output name; the _deps prefix only needs to be added in one place (module name computation), not in every emitter.
  • lt check with multiple entries is valid only if they are all under the same project root.

Backends

Every target receives the same typed IR and emits an ordinary library. The build output for one package is:

TargetModuleRuntime
TypeScriptout/ts/src/<package>.tsout/ts/_lingua_rt.ts
Pythonout/py/gen/<package>.pyout/py/lt_runtime.py
Goout/go/gen/<package>/<package>.goout/go/lt/runtime.go

The package name, not the file name, determines the module. A file contains exactly one package. Packages from external dependencies are emitted under _deps/<key>/ and do not expose their tests.

Shared mapping

LTTypeScriptPythonGo
Intbigint + i64 helpersint + 64-bit maskint64
Floatnumberfloatfloat64
Strstringstrstring
Boolbooleanboolbool
List<T>LList<T>LListList[T]
Map<K,V>LMap<K,V>LMapMap[K,V]
Dict<V>LDict<V>LDictDict[V]
Set<T>LSet<T>LSetSet[T]
Option<T>tagged unionOptVariant
Result<T,E>tagged unionResVariant
structreadonly classfrozen dataclassstruct + constructor
enumtagged unionfrozen dataclassVariant

Names follow the host convention: camelCase in TypeScript, snake_case in Python and Go, with export controlling visibility. Private declarations remain callable from the same package’s tests.

Test runners

TargetRunnerCommand
TypeScriptvitest + tsc --strictlt test -t ts … --run
Pythonpytest + mypy --strictlt test -t py … --run
Gogo test + go vetlt test -t go … --run

Read the target page for the exact representation, package layout, naming, and limitations:

TypeScript Backend

First target, used to validate the IR and semantics. Status: v2 — verified; tsc --strict is clean and the full conformance suite passes in vitest.

Representation

LTTypeScript
Int (i64)bigint + BigInt.asIntN(64, …) via lt.iadd/isub/imul/idiv/irem/ineg
Floatnumber
Strstring; index/len are counted per code point ([...s])
Boolboolean
List<T>lt.LList<T> (immutable, copy-on-write)
Map<K,V>lt.LMap<K,V> (entries ordered by Ord, lookup via binary search O(log n))
Dict<V>lt.LDict<V> (string keys, insertion order, Map index)
fn(A) -> R(a: A) => R; a lambda becomes an arrow function
Valueprelude enum value, rendered like a regular enum; json.parse/stringify in lt
Set<T>lt.LSet<T>
Option<T>lt.Opt<T> = union {tag:"some"|"none", values, __lt_meta}
Result<T,E>lt.Res<T,E> = union {tag:"ok"|"err", …}
enuma single identifier: export type Enum + export const Enum, variants called as Enum.Variant(...); variant order & display live in the shared Enum_variant
structclass with readonly fields, object constructor { field: … }, __lt_eq, __lt_cmp, __lt_to_string; embed fields remain regular fields and widens to users.tableInfo
package-level functionsexport function name(...)
private functionsexport function _name(...) — still exported so test files can call them, but marked _ as internal
package bindingsexport const name: T = … (private: _name)
packageone module file: src/<package>.ts
receiver functionsremain module functions; p.len() is lowered to len(p)
Displaylt.disp(value); the owning package’s to_string is called by __lt_to_string
Eq / Ordlt.eq(a, b) / lt.cmp(a, b)
? on Result/Optionconst t = …; if (t.tag === "err"/"none") return t;
templateconcatenation + lt.disp(...)
tagged templatecall to a package-level function with LList<string> + LList<T>; values are not disped
matchswitch (value.tag)
JSXnew Struct({ field: …, children: new LList([...]) })
expect.eq etc.lt.expectEqual / expectNotEqual / expectTrue / expectFalse
test "title"it("title", …) in tests/<package>.test.ts

Package structure

out/ts/
  _lingua_rt.ts        inline runtime (embedded from runtimes/ts/runtime.ts)
  package.json
  tsconfig.json        strict, ES2022, noEmit
  src/<package>.ts     one file per LT package
  tests/<package>.test.ts  only from `lt test`

Cross-package imports use the namespace m<id> (import * as m1 from "./user"), so names never collide. The runtime alias is always lt, and a user declaration named lt is mangled to lt_.

Naming

  • fields, functions, parameters, local variables: snake_case → camelCase
  • private functions/bindings: _ prefix (_doubleTwice)
  • structs, enums, variants: keep PascalCase
  • TypeScript keywords get a _ suffix
  • test titles are used verbatim in it("…")

Test

lt test -t ts tests/conformance/*.lt --out out/conformance --run

--run runs vitest. tsconfig.json includes tests/**/*.ts, so tsc --strict also checks the test files.

Limitations

  • Ordering is not exposed on the language surface yet.
  • Builtins are only available as receivers (xs.map(…)), not list.map(xs, …).

Python Backend

Second target. Status: v2 — verified; mypy --strict is clean and the full conformance suite passes in pytest.

Representation

LTPython
Int (i64)int + _lt.iadd/isub/imul/idiv/irem/ineg (64-bit mask)
Floatfloat; division uses _lt.fdiv so x / 0.0 = ±inf/NaN
Strstr (indexed per code point)
Boolbool
List<T>_lt.LList (immutable tuple)
Map<K,V>_lt.LMap (entries ordered by cmp, lookup via binary search)
Dict<V>_lt.LDict (str keys, insertion order)
fn(A) -> RCallable[[A], R]; a lambda becomes a nested def
Valueprelude enum value; _lt.json_parse/json_stringify
Set<T>_lt.LSet
Option<T>_lt.Opt (tag = "some"/"none", values tuple)
Result<T,E>_lt.Res (tag = "ok"/"err")
enum@dataclass(frozen=True) with tag/values/order; variants are Shape.circle(...) (@staticmethod) and Shape.Point (ClassVar); display via to_display
struct@dataclass(frozen=True); fields become named constructor parameters, plus lt_cmp and to_display; embed fields remain regular fields and widens to users.table_info
package-level functionsdef name(...) (export) / def _name(...) (private)
package bindingsname = … / _name = …
packageone module: gen/<package>.py
receiver functionsremain module functions; p.len() becomes len(p) when lowering
Display_lt.disp(value); to_display calls the package’s to_string when present
Eq / Ord_lt.eq, @dataclass __eq__, _lt.cmp
?if t.tag == "err"/"none": return t
templateconcatenation + _lt.disp(...)
tagged templatecall to a package-level function with LList[str] + LList[T]; generic enum type arguments are erased to Any
matchif/elif chain on value.tag
JSXconstructor call with keyword arguments
expect.eq etc._lt.expect_equal / expect_not_equal / expect_true / expect_false
test "title"def test_title() -> None in tests/test_<package>.py

Builtin shadowing: a package that declares a function named int/str/list/… makes primitive annotations in that module written as builtins.int so mypy --strict stays valid.

Package structure

out/py/
  lt_runtime.py
  pyproject.toml          # pytest: pythonpath=["."], testpaths=["tests"]
  gen/__init__.py
  gen/<package>.py        # one module per LT package
  gen/<dir>/__init__.py   # for packages in subdirectories
  tests/test_<package>.py # only from `lt test`

Cross-package imports: import gen.models.user as m1; cross-module references use that alias. Private helpers can still be called by tests through m1._helper.

Test

lt test -t py tests/conformance/*.lt --out out/conformance --run

--run runs python3 -m pytest -q. The scripts/conformance-py.sh script creates a virtualenv if none exists, runs mypy --strict ., then pytest; dependencies are installed only if they are not already available.

Limitations

  • Generic type parameters are erased in Python (duck typing); generic structs/enums become regular classes.
  • Int is unbounded in Python; masking happens only on emitted arithmetic operations.
  • Ordering is not exposed on the language surface yet.
  • Builtins are only available as receivers (xs.map(…)), not list.map(xs, …).

Go Backend

Third target. Status: v2 — verified; go vet is clean and the full conformance suite passes in go test.

Representation

LTGo
Int (i64)int64 — overflow wrapping is built into Go
Floatfloat64; division goes through lt.FDiv so 1.0/0.0 is not rejected by the compiler as a constant
Strstring; code point operations use lt.StrLen/StrSlice/StrChars/...
Boolbool
List<T>lt.List[T]
Map<K,V>lt.Map[K,V] (ordered entries, lookup via binary search)
Dict<V>lt.Dict[V] (Str keys, insertion order, map[string]V index)
fn(A) -> Rfunc(A) R; a lambda becomes a func literal
Valueprelude enum value as lt.Variant; lt.JSONParse/JSONStringify + lt.ValueFactory
Set<T>lt.Set[T]
Option<T> / Result<T,E>lt.Variant (Tag, Order, Type, Values)
enumlt.Variant with Type = enum name + constructor EnumVariant(...); structural display from Type/Tag/Values, with no per-enum display function
structstruct with exported fields + NewUser(...); embed fields remain regular fields, widening becomes a field access (users.TableInfo)
package-level functionsfunc Name(...) for export, func name(...) (camelCase) for private
package bindingsvar Name T = … / var name T = …
packageone package directory: gen/<package>/<package>.go
receiver functionsremain package-level functions; p.len() becomes len(p) when lowering
Display/Eq/Ordlt.Disp, lt.Eq, lt.Cmp via the LtDisplay/LtEq/LtCmp methods on structs; lt.Variant renders its own display from Type/Tag/Values
?if __try.Tag == "err"/"none" { return __try }
to_string()lt.Disp(value)
tagged templatecall to a package-level function with lt.List[string] + lt.List[T]
matchswitch __m.Tag { case "Some": ... }
JSXcall to New<Struct>(...)
expect.eq etc.lt.ExpectEqual / ExpectNotEqual / ExpectTrue / ExpectFalse
test "title"func TestTitle(t *testing.T) in <package>_test.go, in the same package

Tests are emitted as package <name> (not <name>_test) so that private helpers in that package remain callable — Go does not export lowercase identifiers to other packages.

Package structure

out/go/
  go.mod                    module linguatungga, go 1.22
  lt/runtime.go
  gen/<package>/<package>.go        one directory per LT package
  gen/<package>/<package>_test.go   only from `lt test`

Cross-package imports use the module path: import m1 "linguatungga/gen/user".

Test

lt test -t go tests/conformance/*.lt --out out/conformance --run

--run runs go test ./.... The scripts/conformance-go.sh script also runs go vet ./... and uses the local toolchain at /mnt/A29EE2F79EE2C341/tools/go when go is not on PATH.

Limitations

  • Enum/Option/Result payloads are stored as any; the emitter inserts type assertions it knows from the IR, so type errors still cannot come from an LT program that passed typecheck.
  • Struct fields are exported to be idiomatic; immutability is enforced by the LT compiler, not Go.
  • Generic parameters are erased from enum types (because enums use lt.Variant).
  • Ordering is not exposed on the language surface yet.
  • Builtins are only available as receivers (xs.Map(…)), not list.map(xs, …).

Formatting

gofmt is context-sensitive (it removes spaces around + in call arguments but keeps them in return), so the emitter does not mimic it byte for byte. Go output is formatted by running gofmt -w during packaging; shipped packages must still produce empty gofmt -l output.

Playground

The playground compiles Lingua Tungga in your browser. It is the same compiler that produces the release binary, built for WebAssembly; nothing is sent to a server.

Type a package, press Compile, and read the diagnostics and the generated TypeScript, Python, and Go. The editor supports several files, so imports work exactly as they do on disk.

loading compiler…


      

Your code stays in this tab. Share copies a URL that contains the current snippet.

What it shows

  • Diagnostics from the loader, parser, type checker, and lowering pass, with file:line:col.
  • Generated code for all three targets. The tabs switch target, not project.
  • Imports between the files in the editor. External dependencies are rejected because the browser has no package manager; local imports work.

The playground compiles only. It does not execute TypeScript, Python, or Go, and it cannot show runtime output. For recorded runtime output of every language rule, use the examples gallery.

Keyboard

KeyAction
Ctrl/Cmd + EnterCompile
TabIndent
Ctrl/Cmd + SShare the current snippet (updates the URL)

Examples

The examples gallery is generated from the repository’s executable cases. Each case is one language rule, compiled to TypeScript, Python, and Go, with the generated code, a calling program for each target, and the stdout that program produced.

The gallery is built by scripts/playground.sh, which also runs the three conformance suites. A case is listed only after all three targets pass.

Open the examples gallery

What is in a case

Each case has a source file, metadata, and tests. The generated page shows:

  • the .lt source and why the rule exists;
  • the emitted module for each target;
  • a runnable usage program that calls the emitted library;
  • the stdout that program produced on that machine.

The gallery is static: it works from file:// and from the documentation site.

Editor support

Lingua Tungga ships a tree-sitter grammar and integrations for VS Code, Zed, Neovim, Helix, and Emacs. The language server is lt lsp over stdio.

Everything here is built on two things that already exist in the compiler:

  • editors/tree-sitter-lingua-tungga — the grammar and highlight queries.
  • lt lsp — diagnostics, hover, go-to-definition, references, completion, signature help, document/workspace symbols, highlights, formatting, rename and import quick fixes over stdio.
  • lt fmt — formatting.

The grammar lives in this workspace so the same corpus the conformance suite runs can be parsed by it (scripts/grammar-drift.sh).

Status. Verified on the development machine (VS Code 1.123, Zed 1.30, Neovim 0.12.7 headless):

  • Grammar generates with tree-sitter 0.27.2, scripts/grammar-drift.sh parses 114 files (1 documented exception) and every query compiles.
  • The VS Code extension compiles (tsc), packages (vsce), activates on a .lt file, spawns lt lsp --stdio, and the TextMate grammar tokenizes examples/words.lt into 29 scopes when run through vscode-textmate.
  • Neovim 0.12.7 sets filetype=lingua-tungga, starts lt lsp once per project, and answers prepareRename (verified headless; highlighting needs a parser that was not built in that run).
  • Zed 1.30 loads the language and instantiates the grammar in a throwaway data directory: extensions updated. loading 2, no query errors. Highlighting is therefore live; the language server is not (see below).
  • Helix and Emacs were not launched at all; their files are conventional but unrun.

lt must be on PATH for every editor below. Either cargo install --path crates/lt-cli or export the built binary: export PATH="$PWD/target/release:$PATH".

tree-sitter grammar

cd editors/tree-sitter-lingua-tungga
npm install
npx tree-sitter generate      # writes src/parser.c (not committed)

Drift check against the repository corpus (conformance, examples, playground, bench):

scripts/grammar-drift.sh      # parses every *.lt and fails on ERROR nodes

The script uses a global tree-sitter if present, otherwise editors/tree-sitter-lingua-tungga/node_modules/.bin/tree-sitter, and skips with a message when neither exists (so CI without node still passes). Files that the grammar cannot parse yet are listed with their reason in editors/tree-sitter-lingua-tungga/known-failures.txt; that list must stay short and explained.

Notes and known gaps:

  • Lingua Tungga has contextual keywords: from, to, in and as are legal field/function/binding names (tests/conformance/keywords.lt). The grammar therefore does not set word: $ => $.identifier; tree-sitter’s state-dependent lexer resolves the ambiguity. If a corpus file fails to parse, that is the first thing to adjust.
  • JSX children are expression children in braces (<Label value="x">{x}</Label>), not raw expressions.
  • Template strings (\a ${b}`) and tagged templates (``tag…``) have separate rules; interpolations are re-parsed by the same grammar throughinjections.scm`.
  • Newlines end statements. The compiler stops a return value and a statement at a line break; tree-sitter has no newline token, so x = 100 followed by a line starting with [ parses as an index expression. This is why tests/conformance/closures.lt is in known-failures.txt. A proper fix needs an external scanner that makes newlines significant.
  • playground/ contains deliberate syntax-error cases; the drift script parses them too, so a file that is meant to fail may need an allowlist.

VS Code

cd editors/vscode
npm install
npm run compile
code --extensionDevelopmentPath="$PWD"   # or: npx vsce package

Provides: TextMate highlighting, snippets, and the LSP client (lt lsp), so completion, hover, go-to-definition, references, rename, import quick fixes and symbols come from the server. Formatting comes from the server (textDocument/formatting), so format-on-save needs no external command. Settings: linguaTungga.server.path (default lt), linguaTungga.trace.server.

Verified here: npm run compile, npx vsce package, and launching with --extensionDevelopmentPath activates the extension (onLanguage:lingua-tungga) and spawns lt lsp --stdio. Still worth a human check: open a .lt file from examples/, confirm colours, hover a binding, F12 on a struct/function name, and Format Document.

Zed

Zed clones grammars from a repository root, so publish editors/tree-sitter-lingua-tungga as its own repo (gntrees/tree-sitter-lingua-tungga) or split it:

git subtree split --prefix editors/tree-sitter-lingua-tungga -b ts-lingua-tungga

Point [grammars.lingua_tungga] in extension.toml at that repo and a commit SHA, then install it as a dev extension (zed: install dev extension) and choose the editors/zed directory.

Two details that cost real time when wiring it by hand:

  • The grammar key is lingua_tungga, not lingua-tungga. Zed looks up the exported symbol tree_sitter_<key> in the compiled wasm, and dashes cannot appear in a C symbol. config.toml must say grammar = "lingua_tungga" and the wasm must be grammars/lingua_tungga.wasm.

  • tree-sitter build --wasm (CLI 0.27) fails with Failed to run wasi-sdk clang. Build it directly instead:

    cd editors/tree-sitter-lingua-tungga && npx tree-sitter generate
    ~/.cache/tree-sitter/wasi-sdk/bin/clang \
      --target=wasm32-wasip1 -std=c11 -O2 -fPIC -fno-exceptions -I src \
      -shared -nostartfiles -Wl,--no-entry -Wl,--export=tree_sitter_lingua_tungga \
      -o grammars/lingua_tungga.wasm src/parser.c
    

Language server. src/lib.rs is the Rust half: it answers language_server_command with lt lsp (resolved through worktree.which, so PATH must contain lt; an explicit lsp.lingua-tungga.binary.path in settings overrides it). Build it:

rustup target add wasm32-wasip2
cd editors/zed && cargo build --release --target wasm32-wasip2
cp target/wasm32-wasip2/release/lingua_tungga.wasm extension.wasm

scripts/zed-dev-extension.sh does all of it: snapshots the grammar (including the generated src/parser.c) into a local git repo under out/zed-grammar, copies the crate sources and languages/ into out/zed-extension, and points its extension.toml at that repo. Install out/zed-extension with zed: install dev extension — Zed then compiles both the Rust crate and the grammar itself, which is why the crate sources and src/parser.c must be in those directories.

Do not copy the extension into ~/.local/share/zed/extensions/installed/ by hand: that loads the language and grammar but not the Rust lib, so no server starts and nothing is logged.

Status: the crate compiles and exports language-server-command, but the server was not observed starting here. Copying the extension into a throwaway extensions/installed/ directory loads the language and grammar but not the Rust lib (no lt lsp process, and no error either), because only the UI’s install path registers the lib. Use zed: install dev extension once to verify; if it fails, Zed’s log (zed: open log) now names the reason.

Without the server Zed still gives highlighting, brackets and outline. For hover/definition without extra setup, use VS Code.

Verify: zed <file>.lt → the tab shows Lingua Tungga, ctrl-shift-o lists functions/structs, and the log (zed: open log) has no failed to load language.

Neovim

The plugin directory is a normal runtimepath entry:

-- lazy.nvim
{ dir = "path/to/lingua-tungga/editors/neovim" }
-- or, without a plugin manager
vim.opt.runtimepath:append("path/to/lingua-tungga/editors/neovim")

It registers the .lt filetype, maps the tree-sitter language name, starts lt lsp (root markers: lt.lock, vendor, .git), and adds buffer-local K (hover), gd (definition) and <leader>lf (lt fmt).

The ftplugin file is ftplugin/lingua-tungga.lua, matching the filetype. It used to be lingua_tungga.lua, which Neovim never loads for a dashed filetype, so the server silently never started.

Headless check (no parser needed, proves the LSP half):

nvim --headless -u NONE \
  -c 'set rtp+=path/to/lingua-tungga/editors/neovim' \
  -c 'edit main.lt' \
  -c 'lua vim.wait(15000, function() return #vim.lsp.get_clients({bufnr=0}) > 0 end, 100)' \
  -c 'lua print(vim.bo.filetype, #vim.lsp.get_clients({bufnr=0}))' \
  -c 'qa!'

lingua-tungga 1 means the filetype was detected and the client attached.

Highlighting needs a parser built from the grammar. With nvim-treesitter:

require("nvim-treesitter.parsers").lingua_tungga = {
  install_info = {
    url = "https://github.com/gntrees/tree-sitter-lingua-tungga",
    files = { "src/parser.c" },
  },
}

Verify: :set ft? shows lingua-tungga, :Inspect shows treesitter captures, :checkhealth vim.lsp lists lingua_tungga, K on a binding shows its type.

Helix

Append editors/helix/languages.toml to ~/.config/helix/languages.toml, copy editors/helix/runtime/queries/lingua-tungga to ~/.config/helix/runtime/queries/lingua-tungga, and build the grammar:

cd editors/tree-sitter-lingua-tungga && npm install && npx tree-sitter generate
hx --grammar build editors/tree-sitter-lingua-tungga

Verify: hx examples/words.lt, then :lsp-workspace-symbol/hover (space k) and gd.

Emacs

(add-to-list 'load-path "path/to/lingua-tungga/editors/emacs")
(require 'lingua-tungga-mode)
(add-hook 'lingua-tungga-mode-hook #'eglot-ensure)

Install the grammar once from Emacs 29+:

(add-to-list 'treesit-language-source-alist
             '(lingua-tungga "https://github.com/gntrees/tree-sitter-lingua-tungga"))
M-x treesit-install-language-grammar RET lingua-tungga RET

eglot-server-programs is extended with ("lt" "lsp") when Eglot loads.

Verify: open a .lt file, M-x treesit-explore-mode, hover with eldoc, M-x xref-find-definitions.

What is missing

  • Helix and Emacs have never been launched. Their files and instructions exist here, but treat their “Verify” lines as a checklist, not as a claim. Neovim and VS Code have been run; see the status box above.
  • lt lsp analyses the graph reachable from the file the editor opened. A file that nothing imports, and that imports nothing, is checked on its own, so a name living in a module outside that graph has no quick fix to offer.
  • Rename covers functions, structs, enums, bindings and locals. Struct fields, enum variants and import aliases are deliberately rejected instead of being renamed partially.
  • No semanticTokens, inlayHint, documentLink (URL imports are not clickable) or workspace-wide diagnostics yet.
  • Sync is full-text on every change, debounced by 150 ms on a worker thread; no incremental contentChanges ranges.
  • Grammar and queries are shared by copy, not by symlink, because not every editor can follow links outside its runtime directory. Update editors/tree-sitter-lingua-tungga/queries first, then copy.

Benchmark

scripts/bench.sh emits bench/bench.lt for all three targets and measures its usage program (best of 3). Workload: build a Map of 1,000 entries via map.from, 2,000 lookups, 1,000 Dict inserts, sort 500 Ints, and one round of json.stringify/parse.

Example results on the development machine (not reference numbers):

ts    891 ms
py    184 ms
go     41 ms

Read with care: the TypeScript number is dominated by vite-node startup time, not by the workload. For a fair comparison, increase the size in bench/bench.lt or reduce startup cost (compile ahead of time). Go is measured from the binary produced by go build, so it is closest to pure work time.

Design note: embedded fields and one-step widening

Status: implemented on feature/struct-embed-subtyping (LT 0.5.x line).

Problem

Generated table declarations need both views of the same value:

struct TableInfo {
  name: Str
  schema: Option<Str>
  alt: Option<Str>
  columns: List<ColumnInfo>
}

struct UsersTable {
  embed table_info: TableInfo
  id: IntColumn
  name: StrColumn
}

fn from(s: Select, t: TableInfo) -> Select

from(select(), users)  // users : UsersTable must be accepted as TableInfo
users.name             // must be the column field, not TableInfo.name

Nominal LT structs cannot be passed to a different nominal parameter, and there is no inheritance, structural record, interface, or type alias. Adding implicit structural typing would weaken the one property the three emitters rely on: every value has exactly one host record type.

Options considered

OptionWhy not / why chosen
Structural assignability for any struct with all base fieldsRejected. It silently makes Wrapper { name: Str } a TableInfo, weakens nominal typing everywhere, and is impossible to map to Go structs without an interface or conversion.
Full struct inheritance struct D : BRejected for this change. Go has no inheritance; emitting D as a distinct struct would need either an interface (dynamic dispatch) or a generated converter. It also creates field-promotion/shadowing questions for arbitrary column names.
User-declared interface / trait implemented explicitlyRejected. Go methods would be dynamic dispatch, and field access through a protocol still needs either methods or generated monomorphisation. Both are larger changes than the downstream need.
Emitter-only projection based on field shapeRejected. Without a source marker, the checker cannot distinguish an intentional wrapper from an accidental one, so the same source would be accepted by one emitter heuristic and rejected by another.
Explicit embed field + one-step widening lowered to field accessChosen. The source states the relation; the checker enforces it nominally; all emitters render exactly users.table_info. No inheritance, interface, dynamic dispatch, or runtime check.

Semantics

A field may be marked once:

struct UsersTable {
  embed table_info: TableInfo
  id: IntColumn
  name: StrColumn
}

Rules:

  • At most one embed field per struct. Its type must be a struct (not an enum, primitive, collection, type parameter, or function).
  • D is assignable to B iff D’s embed field has exactly type B. This is deliberately one step: if C embeds D and D embeds B, C is not assignable to B.
  • No covariance or inference through containers: List<D> is never assignable to List<B>, and a field of type Option<D> is not Option<B>.
  • Widening into an unresolved inference variable is rejected, so the lowering pass never has to replay generic inference to decide where the projection goes. Annotate the parameter as B instead of using a bare T.
  • The relation is used by the ordinary assignability check (arguments, annotated bindings, returns, struct fields, list/dict literals). It is not used by equality assertions and never changes runtime equality.
  • The embed field is a normal field: it is constructed with a named argument, it appears in Eq/Ord/Display, and it is read as users.table_info. There is no field promotion.

Collision rule for arbitrary column names

The embedded field has an author-chosen snake_case name, exactly like every other field. Duplicate names in one struct are already a compile error, so:

  • a derived column may be named name, columns, schema, table_name, etc. without colliding with metadata, because metadata lives at users.table_info.columns and the own field at users.columns;
  • if a database column is literally table_info, the generator must pick a different embed field name. Pick a word that differs after the host naming rules, not a variation of the same word: table_info_ and _table_info both export as tableInfo/TableInfo, so either would collide with a literal column on the host side. metadata or table_meta are safe. It has the complete column set, and there are infinitely many valid snake_case names, so a fresh name always exists;
  • a field literally named embed is still legal: embed: Str is a field, while embed x: T is the marker. The parser distinguishes them by lookahead.

This is why arbitrary database column names are supported: the embed marker, not the field name, carries the widening relation. The only requirement is that the embed field name is unique among that struct’s fields, which the codegen controls.

Emission

The IR contains Upcast { value, field, ty }; lowering inserts it only where the checker accepted D for B. Emitters render it as field access:

TargetSourceEmitted
TypeScriptfrom(select(), users)from(select(), users.tableInfo)
Pythonfrom(select(), users)from_(select_(), users.table_info)
Gofrom(select(), users)From(Select_(), users.TableInfo)

The embed field itself is emitted as an ordinary record member in all three targets; Go does not use anonymous embedding. Therefore there is no interface, no dynamic dispatch, no type assertion, and go vet can see the concrete field access. Eq/Ord/Display are derived from the ordinary field list, with the embedded member first if it is declared first.

Rejected detail: Go embedding

Using Go’s anonymous embedding (type UsersTable struct { TableInfo; ... }) would give the projection for free, but it also promotes TableInfo fields into the outer field set and creates shadowing rules that differ from TypeScript/Python. The chosen named-field form keeps one rule across targets: users.name is an own field or an error, never a promoted base field.

Changelog

0.7.2 — 2026-12-05

Added

  • lt init: creates a new LT project in the current directory or in a named directory — lt.toml, src/<package>.lt, and .gitignore. The package name is derived from the directory name and normalised to lowercase_snake_case; --name overrides it, --force overwrites existing files.

Fixed

  • Lambda captures in guards do not leak into later arms: the guard is lowered before the arm body and its captured snapshot is hoisted in front of match. Previously the guard used a name newly declared in a later arm, so TypeScript threw a ReferenceError.

0.7.1 — 2026-12-04

Fixed

  • Byte-exact dependency checkout on every platform: pinned commits are checked out with core.autocrlf=false and core.eol=lf. Previously Git on Windows wrote CRLF, so the per-file sha256 in lt.lock did not match a lock created on another platform.

0.7.0 — 2026-12-04

Changed

  • Import v3 — package-first with a manifest. Import specifiers no longer carry an extension (import money { Price } "./wallet/money"); external dependencies move to lt.toml and are imported as <key>/<path>; package names are unique per dependency, not per build; a file contains exactly one package; export import adds an explicit re-export; an unused import becomes a compile error.
  • The lock is read-only during builds. lt build/lt check never write lt.lock; only lt add and lt update <key>|--all resolve it again. The lock is now a graph with commits, per-file sha256, and requirement edges; v1 sources are git and path dependencies.
  • New dependency commands: lt add, lt remove, lt migrate. lt update and lt vendor no longer accept a file entry.

Fixed

  • The ban on functions in collections/Option also applies to inferred results: Some(fn(x: Int) => x + 1) and [fn(x: Int) => x + 1] are now rejected, just like the annotation Option<fn(Int) -> Int>. Previously only resolve_type checked it, so inferred result types slipped through.
  • The for error message mentions Set: for does accept List, Set, Map, and Dict; the error message now lists Set too, not only List, Map, and Dict.
  • Local names are checked for snake_case: let Bad_Name = 2 no longer passes. for variables, lambda parameters, match bindings, and destructuring results now use the same rule as functions, package bindings, fields, and ordinary parameters.
  • LSP references from local declarations: local declarations are now recorded as references to themselves, so a let total that is never read is still recognised and textDocument/references no longer points at a same-named top-level binding by mistake.
  • Struct patterns must name the struct being matched: match p { Other { x } => … } on p: Point is now rejected instead of silently reading Point’s field. A package.Struct path is compared with the scrutinee type, not just the field name.
  • LSP picks the right package within one file: hover, definition, highlight, completion, and rename now use the package block containing the cursor, not the first module with the same path. The second and later packages in one file no longer lose position features.
  • JSX children must be List even when empty: <Label /> with children: Str no longer passes and then emits NewLabel("hello", lt.NewList([]any{})) into a string field. The children field type is now checked whether or not a child is present.
  • Exported function bindings can be called through the package qualifier: lib.bump(1) is no longer rejected with package `lib` has no `bump` ; the checker and lowerer now recognise bindings of type fn(…) as callable package members, just like local bindings.
  • Local types win over the prelude: an enum Value or struct Pair in the package itself is now used for construction and patterns, instead of being shadowed by a built-in type of the same name. Resolution follows the same order as type annotations: local, destructuring import, then prelude.
  • A local enum named Ordering uses its own variants: match over a local enum is no longer given the Less/Equal/Greater variants just because it is named Ordering. ord.cmp still returns the prelude Ordering, and the checker and lowerer now match variants from the actual type, not from the name alone.
  • A block ending in return is no longer typed Unit: fn f(x: Int) -> Int { return x } and if/match branches that all return now pass, while a function that can still fall through to the end of the block is still rejected.
  • Named functions used as values use their own name: apply(inc, 1) no longer produces Apply(inc, …) in Go, and in Python/TypeScript a cross-package reference no longer loses the module prefix or the _ prefix for non-exported functions. A function reference now has its own IR node, so every target uses the same naming rules as an ordinary call.
  • match patterns emitted to Python and Go: a named catch-all arm no longer produces wrong Python indentation, and a struct pattern inside an enum payload no longer reads fields directly from any in Go.
  • Bindings may be used before they are declared: bindings are checked in dependency order, so export fn read() -> Int { total } with let total = base + 1 below it is typed correctly, not as an Error that merges with any type. Initialisation cycles are now reported as an error.
  • Dict and fn generics are now instantiated: struct Box<T> { items: Dict<T> } and fn(T) -> T parameters use concrete types, so apply(fn(v: Int) => v + 1, 1) passes and the Go emitter no longer prints func(v T) T in a non-generic function.
  • Lambdas in built-in methods have their own result type: ? inside xs.map(fn(x) => …) is no longer checked against the result type of the enclosing function, so a program that used to pass and then produced invalid Go is now rejected by the checker.
  • Receiver functions only match when the receiver type matches: Box<Str>.show() no longer calls fn show(b: Box<Int>), and receiver generics are bound through unification of the first parameter (fn swap<X, Y>(p: Couple<Y, X>)), not positional zip.
  • match with a wildcard payload is no longer considered exclusive: match o { Some(_) => 1 } over Option<Int> is now rejected with missing None, instead of being accepted and then panicking at runtime. A named catch-all arm (other => …) also no longer produces a Go type assertion on a non-interface value.

0.6.1 — 2026-12-02

Added

  • LSP: rename fields, enum variants, and import aliases: the checker’s reference table now records field access (p.x) and variant uses in values and match patterns, so rename also updates the declaration and all its uses — including same-named fields in other structs that must not be touched. An import alias (import lib as l) is replaced locally in that file together with every l. qualifier.
  • LSP: textDocument/documentLink makes https:// imports clickable in editors that support it.
  • scripts/release.sh manages versions: bumps Cargo.toml, moves ## Unreleased to ## X.Y.Z — date, updates the example commands in README.md and engineering/release.md, runs the gate, then commits and creates an annotated tag. --dry-run prints the plan without touching files; --publish now also pushes main and the tag.

Fixed

  • Neovim never loaded its LSP: the ftplugin file was named lingua_tungga.lua, while its filetype is lingua-tungga, so Neovim did not find it and lt lsp never started. The file was renamed and verified headless with Neovim 0.12.7 (filetype detected, client attached, prepareRename answers).

0.6.0 — 2026-12-02

Added

  • embed field and one-step widening: a struct with an embed name: Base field (at most one, whose type must be a struct) can be used in a position that expects Base. Widening is not transitive, not covariant, and adds no field promotion: users.name remains a field of users, while metadata remains at users.table_info. In IR the coercion is lowered to an ordinary field access (users.tableInfo / users.table_info / users.TableInfo) so TypeScript, Python, and Go stay static, without interfaces or dynamic dispatch. Construction stays named-arg and Eq/Ord/Display follow the ordinary field list. Widening applies only in positions whose lowering projects a field: function arguments, annotated bindings, return, struct field values, and list/dict elements. In other positions (if/match branches, index keys, ord.cmp, tagged-template values, fold results, and the error type of ?) it remains a compile error, because there the projection cannot be inserted and the host code would be mistyped. Design: docs/design/struct-subtyping.md.

0.5.5 — 2026-12-02

Added

  • LSP: rename and import quick fix: textDocument/rename (plus prepareRename) replaces a declaration’s name across every file that uses it through the checker’s reference table — cross-file, safe against shadowing, and rejects keywords and names that violate the PascalCase/snake_case rules with an error message. textDocument/codeAction offers “Import X from pkg” for the unknown type, unknown function, and unknown variable diagnostics whose names are exported by another module in the graph; if the file already imports that module, the name is added to the parenthesised list instead of writing a second import line (which would be a compile error).

0.5.4 — 2026-12-02

Added

  • LSP: completion, signature help, references, workspace symbol: completion v1 (keywords, parameters/locals, module functions/structs/enums/bindings, variants after Enum.), signature help from declarations resolved by Refs, cross-file textDocument/references, and workspace/symbol. Measured: lt check on a 1,500-line file ≈ 220 ms (including process start).

  • LSP: diagnostics no longer block typing: didChange hands the check to a single worker thread and returns immediately; the worker waits 150 ms, merges every job that arrives (the last text per path wins), then checks and publishes. Frames are serialised by a mutex so the Content-Length header and body are never interleaved, and results are used only when the document generation matches. shutdown/exit send a stop signal and join. didOpen stays synchronous so hover is correct from the moment a file is opened.

  • LSP: workspace & editor features: imports are resolved through the loader overlay (an open buffer wins over disk), textDocument/formatting uses the in-process formatter, textDocument/documentSymbol, textDocument/documentHighlight, and definitions/highlights based on the checker’s reference table (not name matching), so cross-file and shadowing are correct. The integration harness crates/lt-cli/tests/lsp.rs runs a real JSON-RPC session in CI.

  • More complete LSP: hover now recognises parameters, for variables, match bindings, lambda parameters, and destructuring results (not just expressions); diagnostics use the original span range so the underline lands exactly on the token, and they are published per file.

  • Highlighting: tree-sitter queries capture method names, fields, and function calls; the VS Code TextMate grammar colours ordinary identifiers and field access (previously white).

  • Editor support in editors/: a tree-sitter grammar (editors/tree-sitter-lingua-tungga) with highlight/locals/injections/brackets queries, a VS Code package (TextMate + LSP client + lt fmt + snippets), Zed, Neovim, Helix, and Emacs (tree-sitter + Eglot). All of them use the existing lt lsp/lt fmt.

  • scripts/grammar-drift.sh parses every *.lt in the repo with the grammar and fails on any ERROR node, so the grammar cannot fall behind the compiler syntax.

Note

  • Editor package status: not fully verified. What has been proven is only the tree-sitter grammar (generate + drift check + queries compile), the VS Code extension (compiles, packages, activates on .lt, runs lt lsp), and grammar loading in Zed 1.30. Zed’s Rust lib has not been loaded through the UI, and Neovim/Helix/Emacs have never been run. This release does not claim official support for those editors; verification is tracked as an issue.
  • The grammar was tested on the development machine: tree-sitter generate succeeds, scripts/grammar-drift.sh parses 114 files (1 documented exception in known-failures.txt), all queries compile, and the VS Code TextMate grammar was tested through vscode-textmate. The VS Code extension compiles, packages, activates on .lt files, and runs lt lsp --stdio. Zed 1.30 loads the language and its grammar (without query errors); the LSP server in Zed is not yet possible because it requires a Rust extension. Neovim/Helix/Emacs have not been run; the verification steps are in editors/README.md.
  • scripts/grammar-wasm.sh builds the grammar to wasm for Zed/Helix, using the wasi-sdk downloaded by tree-sitter (a workaround for tree-sitter build --wasm failing in CLI 0.27).
  • Rust extension for Zed (editors/zed/src/lib.rs): answers language_server_command with lt lsp. scripts/zed-dev-extension.sh builds the wasm, creates a local grammar repo, and prepares out/zed-extension for installation through zed: install dev extension. The crate compiles; loading the lib through the Zed UI has not been verified (see editors/README.md).

0.5.3 — 2026-11-29

Added

  • Struct patterns in match: Point { x, y }, including nested ones (Tagged { point: Point { x, y } }); match accepts a struct scrutinee and requires one irrefutable arm. Conformance struct_patterns.lt.
  • Real-world example examples/words.lt: a word-frequency report with Dict, first-class functions, sort_by, Value, and json; a conformance copy words_case.lt.
  • Benchmark bench/bench.lt + scripts/bench.sh: the cost of Map/Dict/sort/json measured across three targets (best of 3).

0.5.2 — 2026-11-29

Added

  • Snapshot capture: a lambda may capture a let mut; the value is copied when the lambda is created, so later mutations are not visible inside the lambda.
  • lt lsp: a minimal LSP server over stdio — diagnostics (didOpen/didChange → publishDiagnostics), type hover, and go-to-definition for top-level declarations. Imports are not yet resolved (one document is checked at a time).

0.5.1 — 2026-11-29

Added

  • Pair + collections: Pair<A, B>, plus List.enumerate(), List.zip(), Map.entries(), Dict.entries() returning Pair/Entry.
  • let destructuring: let Point { x, y as vertical } = p.

0.5.0 — 2026-11-29

Added

  • Indexing: xs[i], m[k], and d["k"] as partial lookups that return Option<T>; an out-of-bounds index or a missing key becomes None, and Set cannot be indexed. [ only attaches to an expression on the same line.
  • pkg.Enum.Variant in expressions and patterns, plus <pkg.Component /> in JSX. The prefix on a pattern is now verified against the enum being matched, not ignored.
  • Value + json: the prelude enum Value (Null, Bool, Int, Float, Str, Array(List<Value>), Object(Dict<Value>)) which is visible without an import, plus json.parse(Str) -> Result<Value, Str> and json.stringify(Value) -> Str. Integral numbers stay Int, objects use Dict so key order is preserved, and integral floats are printed with .0 so Int/Float do not blur.
  • Statements must now start on a new line; xs[0] is no longer silently parsed as two statements.
  • Playground cases collections/index, types/json, modules/qualified and conformance indexing.lt, qualified.lt, json.lt.

Added

  • Nested patterns: Ok(Value.Int(n)), Some(Some(x)), and other nested patterns are now accepted to arbitrary depth. Exhaustiveness is checked only at the top variant level; an arm that does not match falls through to the next arm, and when nothing matches the runtime reports unreachable.
  • break / continue as statements, valid only inside the nearest loop.
  • for over Map/Dict iterates keys (for k in m), not only List.
  • map.from(List<Entry<K, V>>) builds a map in a single sort; Entry<K, V> comes from the prelude and is visible without an import.
  • The value prelude is emitted only when a module actually mentions Value/Entry (json.*/map.from), so builds that do not touch it are unchanged.
  • Playground cases control/loops and types/nested_match, conformance control_flow.lt, map_from.lt, nested_patterns.lt.

Added

  • Benchmark bench/bench.lt + scripts/bench.sh: the cost of Map/Dict/sort/json measured across three targets (best of 3), with the note that the TS numbers are dominated by vite-node startup.
  • Real-world example examples/words.lt: a word-frequency report using Dict, first-class functions, sort_by, Value, and json. Its conformance copy (words_case) also runs across the three targets.
  • Struct patterns in match: Point { x, y }, including nested ones (Tagged { point: Point { x, y } }); match accepts a struct scrutinee and requires one irrefutable arm. Conformance struct_patterns.lt.
  • lt lsp — a minimal LSP server over stdio: diagnostics (didOpen/didChange → publishDiagnostics), type hover, and go-to-definition for declarations. Imports are not yet resolved (one document is checked at a time).
  • Snapshot capture: a lambda may now capture a let mut; the value is copied when the lambda is created, so later mutations are not visible inside the lambda. Previously this case was rejected.
  • Conformance closures.lt.
  • let destructuring: let Point { x, y as py } = p binds struct fields; the value is evaluated once. Struct patterns in match are not supported yet.
  • Pair<A, B> in the prelude, plus list.enumerate(), list.zip(ys), map.entries(), and dict.entries(). The runtime accepts the Pair constructor from the prelude module, so no tuple type needs to be added.
  • Conformance pairs.lt.
  • list.sort_by(fn(x) => key) sorts by an arbitrary key (the key may not be a function).
  • ord.cmp(a, b) -> Ordering exposes the Ordering enum (Less, Equal, Greater) from the prelude for use in match.
  • Conformance sort_by.lt.
  • First-class functions: the type fn(A, B) -> R, lambdas as values (let f = fn(x: Int) => …), calls through a function value f(x), lambda parameters either annotated or inferred from context, and ? inside a lambda returns from the lambda. Functions are disallowed in struct fields, enum payloads, and inside collections/Option/Result so that Eq/Ord stay total; functions cannot be compared; lambdas may not capture a let mut; generic functions cannot be values.
  • Playground case functions/first_class, diagnostic function_in_struct, and conformance functions.lt.
  • Str indexing: s[i] returns Option<Str> containing one code point (O(n)).
  • for over Set iterates elements in Ord order.
  • Or-patterns (E.A(n) | E.B(n) => …) and guards (Some(n) if n > 0 => …). Every alternative must bind the same names and types; a guarded arm does not count as closing exhaustiveness.
  • json.pretty(Value, Int) prints indented JSON (0 = compact).
  • Conformance cases guards.lt, str_and_set.lt, and json_pretty.lt.

0.4.0 — 2026-11-28

Added

  • Dict<V>: a Str-keyed map with the literal ["a": 1, "b": 2] (empty [:]), insertion order, last-wins on duplicate keys without shifting position, and seven methods with the same shape as Map (len, get, insert, remove, keys, values, contains_key). Its Eq ignores order while Display follows write order; its cmp is canonical so a Dict can still be a Map/Set key.
  • Playground case collections/dict and conformance tests/conformance/dicts.lt.

Fixed

  • Historical documents (PLAN.md, engineering/v2-decisions.md) were given a pointer that the syntax in them is not the latest specification, and examples in the spec now use map.empty() (not Map.empty()).

Changed

  • List/Set/Map/Dict now have lexicographic comparison, replacing the display-string comparison fallback that made [10] sort before [2].
  • Inferred result types are now resolved after the body has been checked, so map.empty().insert(k, v) emits a concrete LMap<K, V>, not unknown. If inference truly runs out of hints (let m = map.empty()), the compiler reports the error “cannot infer this type; annotate the binding” instead of letting the host compiler target fail.
  • An empty import () is now an error (“an empty import group does nothing; remove it”).
  • Map is faster: dedup went from O(n²) to a single O(n) pass (adaptive sort on a nearly sorted array makes insert/remove effectively linear in TypeScript and Python), and get/contains_key use O(log n) binary search.

0.3.1 — 2026-11-28

Added

  • Keywords are now soft in positions that are definitely names: after . every keyword is allowed (b.from, b.match), and likewise field names, labels, parameters, and JSX attributes; function/let/binding/package names and import items accept from, as, and in. Thus fn from(r: Range) + r.from() is valid, and from may also be a package name. Other keywords are still rejected with a message suggesting a _ suffix (e.g. match_).

0.3.0 — 2026-11-28 (breaking: import syntax, enum output)

Added

  • The playground shows a usage program below each language’s output: for each target, the page contains a program that imports the emitted module and calls its API, plus the actual stdout from running that program. The program is derived from IR (tests are replayed with expect.* replaced by print), so it cannot go stale against API changes.
  • lt test --usage emits a usage program together with the package + tests.
  • New playground cases about functions and variables: functions/export_fn, functions/receiver, functions/lambda, functions/mutual, functions/generic, bindings/export_let, bindings/local_let.
  • New gate: executable cases must have at least one export declaration and at least one test block; scripts/playground.sh runs every usage program on all three targets and writes playground/usage.json.

Changed

  • import syntax is trimmed to follow Go: from is removed and the path moves to the end (import money { Price, format } "./wallet/money.lt"), plus import ( … ) blocks with one entry per line and no commas. Package names are still written explicitly and still verified; destructuring, aliases, and qualifiers are unchanged. lt fmt now sorts imports by path per block and preserves blank lines as sub-block separators.
  • import . "path" (dot import) and import _ "path" (blank import) are rejected with a dedicated message; an empty {} in an import is also an error. The from keyword stays reserved even though it is no longer used.
  • Spec §13 clarified: destructuring does not disable qualifiers — the loader behaved this way all along; the document was wrong.
  • The spec §13 rule that was previously only written in the document is now enforced: an import name (qualifier or destructured result) that clashes with that package’s declaration, or that is imported twice, becomes a compile error.
  • The playground corpus (50 cases) and all sidecar metadata are now in English.
  • The 24 cases that previously contained only tests now export the function that their test calls, so the output panel is no longer empty.
  • enum output in all three backends is now one name per enum: variants are called as Shape.Circle(...) (Shape.Point for a variant without a payload), no longer as separate symbols Shape_Circle/shape_circle/ShapeCircle. The per-enum display function is removed; display and variant order become metadata shared by all values, so an enum value carries only its payload.
    • TypeScript: export type Shape + export const Shape (two namespaces, one identifier), lt.VariantMeta per variant, 3 properties per value.
    • Python: constructors become @staticmethod/ClassVar inside the enum class, _shape_display is removed. A variant without a payload stays a value (Shape.Point).
    • Go: lt.Variant loses the Display field and gains Type; LtDisplay renders Type.Tag(payload) structurally, so ShapeDisplay is gone. Constructors remain package-level functions because Go does not allow generic function values.

0.2.1 — 2026-11-27 (breaking: v2)

Decision and rationale ledger: engineering/v2-decisions.md. New specification: docs/spec.md.

Removed

  • class is removed. The single container is now package. class, pub, static, and self stay reserved as keywords; using them produces an error that names their replacement.
  • test class and test fn are removed, replaced by test "title" { … } inside a package.
  • Expect as a class is removed, replaced by the pseudo-package expect.
  • The “no free functions” rule is revoked; package-level functions are now the only form of code.

Added

  • package name { … } as the nominal unit and the import unit. One file may contain more than one package; one package = one host module = one Go package directory.
  • struct as a data type; methods become explicit receiver functions (fn len(p: Point), called as p.len()).
  • export replaces pub, and applies to struct, enum, functions, and bindings.
  • Package-level bindings (immutable, eager) that can be accessed through a path (money.default_currency).
  • Qualified paths of at most 3 segments: package.Type, package.Type.Variant, package.fn.
  • Package-first imports with destructuring and aliases: import money { Price as P } from "./money.lt".

Changed (breaking)

  • Package names must be unique per build; two files with the same package name = compile error.
  • Names within one package must be unique regardless of case.
  • Naming rules are now actually enforced by the compiler (previously only documented).
  • Shadowing an import name with a local declaration = compile error (previously the local won).
  • Stdlib pseudo-class names become lowercase pseudo-packages: math, map, set, json, expect, str, list, option, result.
  • Eq and Ord cannot be overridden; only Display (through the receiver function to_string).
  • ${…} interpolation now respects the user’s to_string. Previously the override applied only to explicit .to_string() calls, differing from what docs/spec.md promised.
  • JSX: the tag name is a struct name; a lowercase tag = compile error.
  • A path prefix on a match pattern is no longer silently ignored.
  • Output is determined by the package name, not the .lt file name.

Not changed (and why)

  • mut, assignment, while, for, break, continue are kept. Removing them would demand changes in five layers, recursion-depth guards in every emitted function, the loss of the early-exit pattern, and slower Python output — without serving the goal of removing class.
  • Nominal typing, no null, Int = wrapping i64, Str per code point, ordered Map/Set: all are kept because this is what makes three-target parity guaranteeable.

Tagged templates & enums (previously under Unreleased)

Changed (breaking)

  • Tagged templates now pass values with their static type, not their Display result. The tag signature becomes (List<Str>, List<T>) -> R, and every ${expr} must have exactly type T. There is no longer an implicit Display → Str conversion for tagged templates.
  • Mixed-type values are expressed through a user enum, for example enum SqlArg { I(Int), S(Str) }, and the tag then takes List<SqlArg>.
  • ${expr} in a plain template is now actually type-checked, and Unit is rejected in an interpolation position.
  • to_string() -> Str is available for every value of type Display. Use this (or an umbrella enum) as the migration path for old tags of type List<Str>. A user-defined to_string method wins over the built-in version.

Fixed

  • ${expr} interpolation in a tagged template was previously never type-checked; unknown variables or wrong types could pass lt check.
  • Generic enums produced invalid Go when the payload used a type parameter. Constructors are now generic and call sites send explicit type arguments.
  • A nullary variant on a generic enum produced const X<T>, which is illegal in TypeScript; the type parameter is removed and the value is given type any.