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
.lttests against all three targets.
Status
Experimental. There is no compatibility promise before 1.0; the language specification is versioned, and the compiler tracks it.
| Phase | M9 — distribution |
| Language | .lt |
| Compiler | Rust, binary lt |
| Targets | TypeScript, Python, Go |
| Conformance | 100% in all three targets |
| License | MIT |
Where to go next
- Install the compiler.
- Build your first project.
- Read the language guide or the normative specification.
- Try the playground without installing anything.
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:
| Target | Requires |
|---|---|
| TypeScript | Node 20+ |
| Python | Python 3.11+ |
| Go | Go 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
packageblock. A file without one, or with more than one, is a compile error. - Fields are named at construction:
Price(amount: 1250, currency: "IDR"). format_priceis a receiver function because its first parameter is a struct.p.format_price()is the same call.exportmakes 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 withlt 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:
| Target | Requires |
|---|---|
| TypeScript | Node 20+ |
| Python | Python 3.11+ |
| Go | Go 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
packageblock. - A
structis only data. Behavior lives in package-level functions;b.genre_label()is sugar forgenre_label(b). - All fields are immutable. There is no
null; absence usesOption<T>. matchmust 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 packagebookfrom that file and takesBook. Without{ … }, the package is bound as a qualifier (book.Book). - Collections are immutable:
pushandaddreturn 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 writtenc.add(book). mutis 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 noexport.- Assertions use
expect.eq,expect.not_equal,expect.true, andexpect.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 mutmakes 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.
Read next
- 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
packageblock, or with more than one, is a compile error. - The package name is
lowercase_snake_case. Functions, fields, parameters, locals, and bindings aresnake_case; structs, enums, and variants arePascalCase. - Package identity is
(dependency, file path), not the name alone. Two dependencies may both declarepackage user; importing both into one file requires different aliases. - Type identity is nominal per loaded module.
money.Priceanduser.Pricenever unify, even with identical fields. - Case-insensitive uniqueness applies inside a package:
Formatandformatcannot 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 usemoney.format(...). - An empty destructuring list
{}is an error. - There are no directory imports and no
indexresolution. - 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.Pandmoney.Priceare 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
| Type | Semantics |
|---|---|
Int | 64-bit signed, two’s complement, wrapping overflow. |
Float | IEEE-754 binary64. NaN exists and NaN != NaN. |
Bool | true or false. |
Str | Immutable 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
| Type | Order | Literal |
|---|---|---|
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 T | none; 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 mutare 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, orabstract. - 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 functionfexists 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(), notcatalog.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:
?onOption<T>requires a function returningOption<U>.?onResult<T, E>requires a function returningResult<U, E>.OptionandResultcannot 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()onNoneorErr;- 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) andenum(sum type)- Package-level functions, including receiver functions (replacement for methods)
- Primitive types
Int,Float,Bool,Str; collectionsList,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 testdeclarations 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
| Aspect | Rule |
|---|---|
| Evaluation | Eager, call-by-value. |
| Value mutability | All values are immutable. mut is only allowed on local variables (let mut), not on fields, parameters, collection elements, or package bindings. |
| Local mutability | A local let mut variable may be reassigned. This is the only form of mutation in the language. |
| Reference cycles | Impossible. A value cannot refer to itself; recursion only goes through bounded structures (Option, List). |
| Global state | No mutable globals. Package-level bindings are immutable, evaluated eagerly at load, and must not form initialization cycles. |
| Evaluation order | Arguments 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. Noneis 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,forvariables, assignment targets, package names, as well as import items and aliases may only usefrom,as, andin— the only keywords that cannot start a statement, expression, type, or item. Sofn from(r: Range)andr.from()are valid, whereasfn match(...)is not. - Type/struct/enum/variant names do not change: they must be
PascalCase, and the only capitalized keyword isNone.
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.
| Entity | Style |
|---|---|
struct, enum, enum variants | PascalCase |
| functions, fields, parameters, local variables, package bindings | snake_case |
| package names | lowercase_snake_case ([a-z][a-z0-9_]*) |
| file names | snake_case.lt |
| test titles | free-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
importentries form one sorted block; blank lines separate sub-blocks and each is sorted independently. Entries insideimport ( … )remain in their block, one per line. - Multiple
packageblocks 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, ormatch). 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
| Type | Semantics |
|---|---|
Int | i64, two’s complement, overflow wrapping. |
Float | f64 IEEE-754. NaN exists; NaN != NaN. |
Bool | true/false. |
Str | Immutable, 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
| Type | Notes |
|---|---|
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
}
UsersTablecan be used in positions expectingTableInfo— as a function argument, areturnvalue, an annotated binding, a struct field value, or a list/dict element — because thetable_infofield has exactly typeTableInfo.- This relation is one step and only through the
embedfield: aCthat embedsDcannot automatically be used as a type embedded byD. There is no covariance forList/Map/Dict/Option/Result. - Widening does not apply to generic parameters that are still inference variables; give
such a parameter the concrete type
Baseif you want to accept a derived type. - An
embedfield remains an ordinary field: it must be filled by named argument at construction, participates inEq/Ord/Display, and is read asusers.table_info— not a promoted field. Sousers.nameis always a field ofUsersTable, notTableInfo.name. - At most one
embedfield 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
embedfield is chosen by the author like an ordinary field and must be unique in that struct. Because theembedmarker (not its name) carries the widening relation, the generator may choose any name that does not collide with any column; a column namedembedcan still be writtenembed: 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 (
==,<) orto_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>requiresK: 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:
packagemust wrap all declarations. There are no bare declarations at file top level, and no nestedpackage.- One file contains exactly one
packageblock. 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,letbindings, andtests. 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 sugarp.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, noabstract. - 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
structis 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/enumtype. No special marker, noself. - The sugar
value.f(args)only applies when a function namedfexists in the package where the value’s type is declared. There is no dynamic dispatch; the result is alwaysf(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)andfn 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 ifemptytakes a receiver; otherwise callempty()).
6.4 Enum
export enum Role {
Admin
Member(Int)
Guest
}
- Variants may have no payload or a payload (one or more types).
- An
enumwithout 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
exportand accessed asmoney.default_currencyor 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); onlylt testproduces 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.
| Segment | Form | Example |
|---|---|---|
| 2 | package.{type|function|binding} | money.Price, money.format(p), money.default_currency |
| 3 | package.Type.Variant | models.Role.Admin |
| 4+ | none | money.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
| Operator | Rule |
|---|---|
+ - * (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?onOption<T>is only valid in a function returningOption<U>.?must not be used inside a lambda: itsreturnwould exit the lambda, not the function.expr?onResult<T, E>is only valid in a function returningResult<U, E>.OptionandResultmust not be mixed in one function.None/Errisreturned 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:
| Trait | Default behavior |
|---|---|
Display | Structural format: User(name: "Ana", age: 30), Role.Member(3). |
Eq | Structural comparison of all fields/variants. |
Ord | Lexicographic over fields in declaration order; enum variants sorted in declaration order. |
EqandOrdcannot be overridden. Both are used bysort,Map, andSet, and all three targets implement them through different paths (sort.Slice,__lt__, comparator); allowing them to be overridden would break parity.Displaycan be overridden by declaring a receiver function namedto_stringin the package where the type is declared:export fn to_string(p: Price) -> Str { … }.- Every value that has
Displaycan be converted throughto_string(). A userto_stringwins over the built-in version, including inside${…}interpolation. Orderingis used internally by the runtime (sort,Map,Set) but is not yet available on the language surface:Orderingis rejected as a type andOrdering.Lessis 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 hasDisplay, and the result is alwaysStr.Unitmay not be interpolated. TheDisplayused is the derived version or the user’sto_stringversion 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.Tis written concretely and must not use a type parameter. - Every
${expr}in a tagged template must be exactly of typeT; there is noDisplayconversion, no implicitSomewrapping, no automatic variant selection. The value is passed as-is, so the tag can inspect it throughmatch. - 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
Strin a${…}position whereT = Str, useto_string().
12. JSX
<Element tag="div" class_name="user">
<Element tag="span">{user.name}</Element>
</Element>
- The tag name = the name of a
structvisible in scope (local, destructuring result, or package qualifier). A lowercase tag = compile error, because type names must bePascalCaseand 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
childrenargument only if the struct declares achildrenfield. If there is no such field but there are children = compile error. - Plain text between tags = one
Strchild. Allowed only if thechildrenfield is of typeList<Str>(orList<T>withT=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>;keymust exist in[dependencies]inlt.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 declarepackage user. If both are imported into the same file, both must use different aliases. - Destructuring (
{ … }) is optional and may only name declarations that areexported 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 usemoney.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) andimport _ "path"(blank import) are rejected: every name is always referred to through a qualifier. - The
fromkeyword 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 importis 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"orfacade.P. - Re-export does not create a new type.
facade.Pandmoney.Priceare 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. versionaccepts a semver range (^,~,=,*in v1), an exact tag, or a 40-hex commit. Branches are rejected.rootis optional (default"."): the subdirectory inside the checkout that becomes the dependency’s package root and must contain that dependency’slt.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. Withoutlt.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 overhttps,http://only forlocalhost. Authentication uses git credentials /GITHUB_TOKEN. No custom signatures in v1.
Lockfile
lt.lockis 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.lockmust 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>orlt update --all. lt update <key>re-resolves that key and its closure;lt update --allre-resolves the entire graph.lt addwrites the manifest and lock;lt removeprunes the lock entries that are no longer reachable.- Source order during build:
vendor/→ cache → fetch the locked commit.--offlineforbids network entirely. The default cache is$XDG_CACHE_HOME/ltor~/.cache/lt;LT_CACHE_DIRoverrides it. lt vendorcopies the locked source tree intovendor/; 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 ... --runrunsvitest; without--runit only emits.testdeclarations are not emitted into the library package (lt build); onlylt testproduces 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
expectpseudo-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):
Intdivision/remainder by zero- Collection index out of bounds (
List.getreturnsOption, so it does not trap) unwrap()onNone/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.ltwithpackage moneyproducesout/ts/src/wallet/money.ts,out/py/gen/wallet/money.py, andout/go/gen/wallet/money/money.go. - External dependency packages are emitted under the
_depsprefix: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._depsis reserved at the source root. - The output module name = the file’s relative directory + the package name. Example:
collections/map.ltwithpackage map_caseproduces the modulecollections/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/enumidentity remainsPascalCase. Function/field names are converted per the target convention by the emitter (snake_casefor Python/Go,camelCasefor TypeScript), withexportmapped toexport(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 asgo vetand an emptygofmt -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.
| Surface | Contents |
|---|---|
| Universal functions | to_string() -> Str for every value with Display; a user to_string wins, including in interpolation |
str | len, trim, trim_indent, lower, upper, split, starts_with, ends_with, contains, replace, slice, chars, parse_int, parse_float |
list | len, 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>) |
map | empty(), from(List<Entry>K, V>>), len, get(K) -> V?, insert, remove, keys, values, entries() -> List<Pair<K, V>>, contains_key |
dict | len, 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] |
set | empty(), len, insert, remove, contains, union, intersect, difference |
option | is_some, is_none, unwrap, unwrap_or, map, and_then |
result | is_ok, is_err, unwrap, unwrap_or, map, map_err, and_then |
math | abs, min, max, floor, ceil, round, sqrt, pow, pi — all Float |
ord | cmp(A, A) -> Ordering |
json | parse(Str) -> Result<Value, Str>, stringify(Value) -> Str, pretty(Value, Int) -> Str |
Value | built-in enum from the value prelude: Null, Bool(Bool), Int(Int), Float(Float), Str(Str), Array(List<Value>), Object(Dict<Value>) |
expect | eq, not_equal, true, false (only valid inside a test) |
| Built-in enums | Ordering (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
| Call | Result |
|---|---|
value.to_string() | Str for every value with Display |
to_string(value) equivalent | uses a user-defined to_string(receiver) when the type declares one, including inside ${…} |
Str
| Method | Result |
|---|---|
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>
| Method | Result |
|---|---|
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.
| Method | Result |
|---|---|
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
| Call | Result |
|---|---|
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:
| Call | Meaning |
|---|---|
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
| Flag | Default | Meaning |
|---|---|---|
-t, --target | ts | ts, py, or go |
--out | out | output root; the target name is appended |
--offline | off | forbid 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
| Flag | Default | Meaning |
|---|---|---|
-t, --target | ts | ts, py, or go |
--out | out | output root; the target name is appended |
--run | off | run vitest, pytest, or go test |
--usage | off | also emit a runnable calling example per package |
--offline | off | forbid 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
addwrites the dependency tolt.toml.--rootselects a subdirectory inside the checkout.removedeletes it fromlt.tomlandlt.lock.updateresolves versions and rewriteslt.lock;--allwalks the whole graph.vendorcopies locked sources intovendor/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
| Code | Meaning |
|---|---|
0 | success |
1 | compilation, formatting, dependency, or test failure |
2 | invalid 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.lockis the resolution graph: source, commit, root, sha256 per file, and requirement edges. Build/check are read-only; onlylt add/lt updatewrite the lock.- Cache:
$XDG_CACHE_HOME/ltor~/.cache/lt;LT_CACHE_DIRoverrides it.lt vendorcopies locked sources tovendor/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) andgrammar.ebnf.package-manager.mdis the operational summary. Implementation of phases 0–5 has landed; seeCHANGELOG.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 usercannot 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 buildandlt checkwritelt.locksilently.- 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
| # | Decision | Rationale |
|---|---|---|
| 2.1 | Package 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.2 | Two 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.3 | One 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.4 | File 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.5 | Specifiers 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.6 | External 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.7 | Manifest v1 contains only [dependencies]. [package], workspaces, and publishing metadata are deferred. | Metadata nobody uses is better not invented. |
| 2.8 | v1 sources: git (https/ssh) and local paths. No registry. | Covers early ecosystem needs without building a server, auth, and publishing. |
| 2.9 | Versions 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.10 | Resolution 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.11 | lt 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.12 | lt.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.13 | Path 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.14 | Unused 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.15 | Explicit 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.16 | Re-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.17 | Dependency 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.18 | Transport: 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.19 | vendor/ 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.20 | v1 commands: lt add, lt remove, lt update <key>/--all, lt vendor, lt migrate. No lt install. | One explicit place that writes the lock. |
| 2.21 | lt build stays entry-based; unreachable local packages are not emitted. | Determinism and minimal output. |
| 2.22 | lt migrate handles mechanical changes and rejects ambiguous cases. Dry-run by default; --write applies. | Humans should see file changes before they are written. |
| 2.23 | Go 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.24 | Deferred: 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:
importalways comes at the top of the file, before thepackageblock.export importis valid only as a single entry, not inside a group.export importmust have a non-empty item list.- The qualifier (
money) stays bound after destructuring and afterexport import, but the qualifier is not re-exported. - Dot imports, blank imports, and
fromare still rejected with dedicated messages. - Empty item lists
{}and empty import groups()remain errors.
4. Semantics
4.1 Project root and resolution
- Project root = the nearest ancestor of the entry that has
lt.toml. Withoutlt.toml, the project may only use local imports. - A specifier starting with
./or../resolves relative to the importing file:<specifier>.lt. There are no directory imports and no index files. - Any other specifier is treated as
<key>/<path>:keymust exist in[dependencies]. Target file =<checkout>/<root>/<path>.lt. - Every loaded file must declare exactly one package. File names are free; the package name determines identity and the output module name.
- Package names must be unique within one dependency. Two different dependencies may use the same name.
- 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 qualifiermoney.import money { Price, format } "./wallet/money"binds the qualifiermoneyand the namesPrice/formatwithout a qualifier.import money as cash { Price as P } "./wallet/money"bindscashandP.- 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 importalways 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"addsPto this package’s export table. A consumer can writeimport facade { P } "./facade"orimport facade "./facade"and thenfacade.P.- A re-exported name must be part of the origin package’s API: a declaration
with
exportor 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.0normalizes to1.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 checkverify that the lock satisfies the current manifest. A missing, incomplete, or non-satisfying lock = an error with the repair command (lt update <key>orlt 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 --allre-resolves the whole graph.lt addwrites the manifest and the lock;lt removeremoves 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) orpath(required); the two must not appear together.rootis optional, default".": the subdirectory inside the checkout that becomes the dependency’s package root. That directory must contain the dependency’slt.toml.- No
[package], workspaces, or publishing fields in v1. - The manifest is written by hand or via
lt add;lt fmtdoes 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"
sourceis the canonical normalized URL (host, path, no.git, no trailing slash). Thesshandhttpsforms of the same repo normalize to the same identity.commitis always 40-hex for git. Path dependencies still get an entry (withoutcommit, sourcepath+…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.filesrecords every file actually loaded, with the sha256 of its content.dependenciesrecords requirement edges, so conflicts can be explained and per-key updates know what changed.versionis the lock format version. An old lock withoutversion= an error telling you to runlt update --all.
7. Output
| Origin | TypeScript | Python | Go |
|---|---|---|---|
| Local | src/<dir>/<package>.ts | gen/<dir>/<package>.py | gen/<dir>/<package>/<package>.go |
| Dependency | src/_deps/<key>/<dir>/<package>.ts | gen/_deps/<key>/<dir>/<package>.py | gen/_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.
_depsis reserved at the source root; a project must not have a directory named_depscontaining 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/vendoraccept--offline;build/checkare read-only with respect to the lock and manifest.vendorcopies the locked source tree from the cache (or fetches the locked commit) intovendor/;--offlineforbids the network.migrateis dry-run by default;--writeapplies.
9. Migration
lt migrate handles:
- Removing
.ltfrom every local specifier. - Moving URL imports into
[dependencies]entries. The key is derived from the repo name; the path inside the repo becomes part of the specifier. - Splitting multi-package files into one file per package, copying only the imports each package actually uses.
- 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
| Phase | Contents | Crate |
|---|---|---|
| 0 | This document, spec/grammar amendments, breaking-release notes | docs/ |
| 1 | One package per file, extension-less specifiers, export import, unused imports, per-dependency uniqueness | lt-syntax, lt-hir, lt-lsp |
| 2 | lt.toml, git/path resolver + semver + transitive, lock graph, read-only build/check | lt-pkg, lt-hir, lt-cli |
| 3 | _deps output, test/usage filtering, runtime paths | lt-ir, lt-emit-* |
| 4 | lt add/remove/update/vendor/migrate, error messages, manifest-aware LSP | lt-cli, lt-lsp |
| 5 | New conformance, examples, docs, CI | tests/, 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
gitCLI in v1 (ls-remote, fetch, checkout); semver uses thesemvercrate. Both can be replaced without changing the manifest/lock. - The
ModuleIdtype 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.modulestill points to the origin package. - The emitter computes relative paths from the output name; the
_depsprefix only needs to be added in one place (module name computation), not in every emitter. lt checkwith 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:
| Target | Module | Runtime |
|---|---|---|
| TypeScript | out/ts/src/<package>.ts | out/ts/_lingua_rt.ts |
| Python | out/py/gen/<package>.py | out/py/lt_runtime.py |
| Go | out/go/gen/<package>/<package>.go | out/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
| LT | TypeScript | Python | Go |
|---|---|---|---|
Int | bigint + i64 helpers | int + 64-bit mask | int64 |
Float | number | float | float64 |
Str | string | str | string |
Bool | boolean | bool | bool |
List<T> | LList<T> | LList | List[T] |
Map<K,V> | LMap<K,V> | LMap | Map[K,V] |
Dict<V> | LDict<V> | LDict | Dict[V] |
Set<T> | LSet<T> | LSet | Set[T] |
Option<T> | tagged union | Opt | Variant |
Result<T,E> | tagged union | Res | Variant |
struct | readonly class | frozen dataclass | struct + constructor |
enum | tagged union | frozen dataclass | Variant |
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
| Target | Runner | Command |
|---|---|---|
| TypeScript | vitest + tsc --strict | lt test -t ts … --run |
| Python | pytest + mypy --strict | lt test -t py … --run |
| Go | go test + go vet | lt 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
| LT | TypeScript |
|---|---|
Int (i64) | bigint + BigInt.asIntN(64, …) via lt.iadd/isub/imul/idiv/irem/ineg |
Float | number |
Str | string; index/len are counted per code point ([...s]) |
Bool | boolean |
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 |
Value | prelude 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", …} |
enum | a single identifier: export type Enum + export const Enum, variants called as Enum.Variant(...); variant order & display live in the shared Enum_variant |
struct | class 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 functions | export function name(...) |
| private functions | export function _name(...) — still exported so test files can call them, but marked _ as internal |
| package bindings | export const name: T = … (private: _name) |
package | one module file: src/<package>.ts |
| receiver functions | remain module functions; p.len() is lowered to len(p) |
Display | lt.disp(value); the owning package’s to_string is called by __lt_to_string |
Eq / Ord | lt.eq(a, b) / lt.cmp(a, b) |
? on Result/Option | const t = …; if (t.tag === "err"/"none") return t; |
| template | concatenation + lt.disp(...) |
| tagged template | call to a package-level function with LList<string> + LList<T>; values are not disped |
match | switch (value.tag) |
| JSX | new 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
Orderingis not exposed on the language surface yet.- Builtins are only available as receivers (
xs.map(…)), notlist.map(xs, …).
Python Backend
Second target. Status: v2 — verified; mypy --strict is clean and the full conformance suite
passes in pytest.
Representation
| LT | Python |
|---|---|
Int (i64) | int + _lt.iadd/isub/imul/idiv/irem/ineg (64-bit mask) |
Float | float; division uses _lt.fdiv so x / 0.0 = ±inf/NaN |
Str | str (indexed per code point) |
Bool | bool |
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) -> R | Callable[[A], R]; a lambda becomes a nested def |
Value | prelude 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 functions | def name(...) (export) / def _name(...) (private) |
| package bindings | name = … / _name = … |
package | one module: gen/<package>.py |
| receiver functions | remain 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 |
| template | concatenation + _lt.disp(...) |
| tagged template | call to a package-level function with LList[str] + LList[T]; generic enum type arguments are erased to Any |
match | if/elif chain on value.tag |
| JSX | constructor 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. Intis unbounded in Python; masking happens only on emitted arithmetic operations.Orderingis not exposed on the language surface yet.- Builtins are only available as receivers (
xs.map(…)), notlist.map(xs, …).
Go Backend
Third target. Status: v2 — verified; go vet is clean and the full conformance suite
passes in go test.
Representation
| LT | Go |
|---|---|
Int (i64) | int64 — overflow wrapping is built into Go |
Float | float64; division goes through lt.FDiv so 1.0/0.0 is not rejected by the compiler as a constant |
Str | string; code point operations use lt.StrLen/StrSlice/StrChars/... |
Bool | bool |
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) -> R | func(A) R; a lambda becomes a func literal |
Value | prelude 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) |
enum | lt.Variant with Type = enum name + constructor EnumVariant(...); structural display from Type/Tag/Values, with no per-enum display function |
struct | struct with exported fields + NewUser(...); embed fields remain regular fields, widening becomes a field access (users.TableInfo) |
| package-level functions | func Name(...) for export, func name(...) (camelCase) for private |
| package bindings | var Name T = … / var name T = … |
package | one package directory: gen/<package>/<package>.go |
| receiver functions | remain package-level functions; p.len() becomes len(p) when lowering |
Display/Eq/Ord | lt.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 template | call to a package-level function with lt.List[string] + lt.List[T] |
match | switch __m.Tag { case "Some": ... } |
| JSX | call 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/Resultpayloads are stored asany; 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). Orderingis not exposed on the language surface yet.- Builtins are only available as receivers (
xs.Map(…)), notlist.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.
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
| Key | Action |
|---|---|
Ctrl/Cmd + Enter | Compile |
Tab | Indent |
Ctrl/Cmd + S | Share 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.
What is in a case
Each case has a source file, metadata, and tests. The generated page shows:
- the
.ltsource 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.
Related
- Playground — edit and compile in the browser.
- Tests — write your own
testblocks. playground/cases— the source of every case.
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.shparses 114 files (1 documented exception) and every query compiles.- The VS Code extension compiles (
tsc), packages (vsce), activates on a.ltfile, spawnslt lsp --stdio, and the TextMate grammar tokenizesexamples/words.ltinto 29 scopes when run through vscode-textmate.- Neovim 0.12.7 sets
filetype=lingua-tungga, startslt lsponce per project, and answersprepareRename(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.
ltmust be onPATHfor every editor below. Eithercargo install --path crates/lt-clior 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,inandasare legal field/function/binding names (tests/conformance/keywords.lt). The grammar therefore does not setword: $ => $.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
returnvalue and a statement at a line break; tree-sitter has no newline token, sox = 100followed by a line starting with[parses as an index expression. This is whytests/conformance/closures.ltis inknown-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, notlingua-tungga. Zed looks up the exported symboltree_sitter_<key>in the compiled wasm, and dashes cannot appear in a C symbol.config.tomlmust saygrammar = "lingua_tungga"and the wasm must begrammars/lingua_tungga.wasm. -
tree-sitter build --wasm(CLI 0.27) fails withFailed 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 lspanalyses 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
contentChangesranges. - 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/queriesfirst, 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
| Option | Why not / why chosen |
|---|---|
| Structural assignability for any struct with all base fields | Rejected. 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 : B | Rejected 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 explicitly | Rejected. 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 shape | Rejected. 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 access | Chosen. 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
embedfield per struct. Its type must be a struct (not an enum, primitive, collection, type parameter, or function). Dis assignable toBiffD’s embed field has exactly typeB. This is deliberately one step: ifCembedsDandDembedsB,Cis not assignable toB.- No covariance or inference through containers:
List<D>is never assignable toList<B>, and a field of typeOption<D>is notOption<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
Binstead of using a bareT. - 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 asusers.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 atusers.table_info.columnsand the own field atusers.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_infoboth export astableInfo/TableInfo, so either would collide with a literal column on the host side.metadataortable_metaare 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
embedis still legal:embed: Stris a field, whileembed x: Tis 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:
| Target | Source | Emitted |
|---|---|---|
| TypeScript | from(select(), users) | from(select(), users.tableInfo) |
| Python | from(select(), users) | from_(select_(), users.table_info) |
| Go | from(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 tolowercase_snake_case;--nameoverrides it,--forceoverwrites 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 aReferenceError.
0.7.1 — 2026-12-04
Fixed
- Byte-exact dependency checkout on every platform: pinned commits are checked out with
core.autocrlf=falseandcore.eol=lf. Previously Git on Windows wrote CRLF, so the per-file sha256 inlt.lockdid 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 tolt.tomland are imported as<key>/<path>; package names are unique per dependency, not per build; a file contains exactly one package;export importadds an explicit re-export; an unused import becomes a compile error. - The lock is read-only during builds.
lt build/lt checknever writelt.lock; onlylt addandlt update <key>|--allresolve 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 updateandlt vendorno longer accept a file entry.
Fixed
- The ban on functions in collections/
Optionalso applies to inferred results:Some(fn(x: Int) => x + 1)and[fn(x: Int) => x + 1]are now rejected, just like the annotationOption<fn(Int) -> Int>. Previously onlyresolve_typechecked it, so inferred result types slipped through. - The
forerror message mentionsSet:fordoes acceptList,Set,Map, andDict; the error message now listsSettoo, not onlyList,Map, andDict. - Local names are checked for
snake_case:let Bad_Name = 2no longer passes.forvariables, lambda parameters,matchbindings, 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 totalthat is never read is still recognised andtextDocument/referencesno longer points at a same-named top-level binding by mistake. - Struct patterns must name the struct being matched:
match p { Other { x } => … }onp: Pointis now rejected instead of silently readingPoint’s field. Apackage.Structpath 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
packageblock 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
childrenmust beListeven when empty:<Label />withchildren: Strno longer passes and then emitsNewLabel("hello", lt.NewList([]any{}))into a string field. Thechildrenfield 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 withpackage `lib` has no `bump`; the checker and lowerer now recognise bindings of typefn(…)as callable package members, just like local bindings. - Local types win over the prelude: an
enum Valueorstruct Pairin 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
Orderinguses its own variants:matchover a local enum is no longer given theLess/Equal/Greatervariants just because it is namedOrdering.ord.cmpstill returns the preludeOrdering, and the checker and lowerer now match variants from the actual type, not from the name alone. - A block ending in
returnis no longer typedUnit:fn f(x: Int) -> Int { return x }andif/matchbranches that allreturnnow 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 producesApply(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. matchpatterns 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 fromanyin Go.- Bindings may be used before they are declared: bindings are checked in dependency order, so
export fn read() -> Int { total }withlet total = base + 1below it is typed correctly, not as anErrorthat merges with any type. Initialisation cycles are now reported as an error. Dictandfngenerics are now instantiated:struct Box<T> { items: Dict<T> }andfn(T) -> Tparameters use concrete types, soapply(fn(v: Int) => v + 1, 1)passes and the Go emitter no longer printsfunc(v T) Tin a non-generic function.- Lambdas in built-in methods have their own result type:
?insidexs.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 callsfn 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. matchwith a wildcard payload is no longer considered exclusive:match o { Some(_) => 1 }overOption<Int>is now rejected withmissing 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 andmatchpatterns, sorenamealso 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 everyl.qualifier. - LSP:
textDocument/documentLinkmakeshttps://imports clickable in editors that support it. scripts/release.shmanages versions: bumpsCargo.toml, moves## Unreleasedto## X.Y.Z — date, updates the example commands inREADME.mdandengineering/release.md, runs the gate, then commits and creates an annotated tag.--dry-runprints the plan without touching files;--publishnow also pushesmainand the tag.
Fixed
- Neovim never loaded its LSP: the ftplugin file was named
lingua_tungga.lua, while its filetype islingua-tungga, so Neovim did not find it andlt lspnever started. The file was renamed and verified headless with Neovim 0.12.7 (filetype detected, client attached,prepareRenameanswers).
0.6.0 — 2026-12-02
Added
embedfield and one-step widening: a struct with anembed name: Basefield (at most one, whose type must be a struct) can be used in a position that expectsBase. Widening is not transitive, not covariant, and adds no field promotion:users.nameremains a field ofusers, while metadata remains atusers.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 andEq/Ord/Displayfollow 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/matchbranches, index keys,ord.cmp, tagged-template values,foldresults, 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(plusprepareRename) 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 thePascalCase/snake_caserules with an error message.textDocument/codeActionoffers “ImportXfrompkg” for theunknown type,unknown function, andunknown variablediagnostics whose names areexported 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 byRefs, cross-filetextDocument/references, andworkspace/symbol. Measured:lt checkon a 1,500-line file ≈ 220 ms (including process start). -
LSP: diagnostics no longer block typing:
didChangehands 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 theContent-Lengthheader and body are never interleaved, and results are used only when the document generation matches.shutdown/exitsend a stop signal and join.didOpenstays 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/formattinguses 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 harnesscrates/lt-cli/tests/lsp.rsruns a real JSON-RPC session in CI. -
More complete LSP: hover now recognises parameters,
forvariables,matchbindings, lambda parameters, and destructuring results (not just expressions); diagnostics use the originalspanrange 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 existinglt lsp/lt fmt. -
scripts/grammar-drift.shparses every*.ltin the repo with the grammar and fails on anyERRORnode, 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, runslt 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 generatesucceeds,scripts/grammar-drift.shparses 114 files (1 documented exception inknown-failures.txt), all queries compile, and the VS Code TextMate grammar was tested through vscode-textmate. The VS Code extension compiles, packages, activates on.ltfiles, and runslt 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 ineditors/README.md. scripts/grammar-wasm.shbuilds the grammar to wasm for Zed/Helix, using the wasi-sdk downloaded by tree-sitter (a workaround fortree-sitter build --wasmfailing in CLI 0.27).- Rust extension for Zed (
editors/zed/src/lib.rs): answerslanguage_server_commandwithlt lsp.scripts/zed-dev-extension.shbuilds the wasm, creates a local grammar repo, and preparesout/zed-extensionfor installation throughzed: install dev extension. The crate compiles; loading the lib through the Zed UI has not been verified (seeeditors/README.md).
0.5.3 — 2026-11-29
Added
- Struct patterns in
match:Point { x, y }, including nested ones (Tagged { point: Point { x, y } });matchaccepts a struct scrutinee and requires one irrefutable arm. Conformancestruct_patterns.lt. - Real-world example
examples/words.lt: a word-frequency report withDict, first-class functions,sort_by,Value, andjson; a conformance copywords_case.lt. - Benchmark
bench/bench.lt+scripts/bench.sh: the cost ofMap/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>, plusList.enumerate(),List.zip(),Map.entries(),Dict.entries()returningPair/Entry.letdestructuring:let Point { x, y as vertical } = p.
0.5.0 — 2026-11-29
Added
- Indexing:
xs[i],m[k], andd["k"]as partial lookups that returnOption<T>; an out-of-bounds index or a missing key becomesNone, andSetcannot be indexed.[only attaches to an expression on the same line. pkg.Enum.Variantin 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 enumValue(Null,Bool,Int,Float,Str,Array(List<Value>),Object(Dict<Value>)) which is visible without an import, plusjson.parse(Str) -> Result<Value, Str>andjson.stringify(Value) -> Str. Integral numbers stayInt, objects useDictso key order is preserved, and integral floats are printed with.0soInt/Floatdo 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/qualifiedand conformanceindexing.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 reportsunreachable. break/continueas statements, valid only inside the nearest loop.foroverMap/Dictiterates keys (for k in m), not onlyList.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
valueprelude is emitted only when a module actually mentionsValue/Entry(json.*/map.from), so builds that do not touch it are unchanged. - Playground cases
control/loopsandtypes/nested_match, conformancecontrol_flow.lt,map_from.lt,nested_patterns.lt.
Added
- Benchmark
bench/bench.lt+scripts/bench.sh: the cost ofMap/Dict/sort/json measured across three targets (best of 3), with the note that the TS numbers are dominated byvite-nodestartup. - Real-world example
examples/words.lt: a word-frequency report usingDict, first-class functions,sort_by,Value, andjson. 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 } });matchaccepts a struct scrutinee and requires one irrefutable arm. Conformancestruct_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. letdestructuring:let Point { x, y as py } = pbinds struct fields; the value is evaluated once. Struct patterns inmatchare not supported yet.Pair<A, B>in the prelude, pluslist.enumerate(),list.zip(ys),map.entries(), anddict.entries(). The runtime accepts thePairconstructor 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) -> Orderingexposes theOrderingenum (Less,Equal,Greater) from the prelude for use inmatch.- 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 valuef(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 thatEq/Ordstay total; functions cannot be compared; lambdas may not capture alet mut; generic functions cannot be values. - Playground case
functions/first_class, diagnosticfunction_in_struct, and conformancefunctions.lt. Strindexing:s[i]returnsOption<Str>containing one code point (O(n)).foroverSetiterates elements inOrdorder.- 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, andjson_pretty.lt.
0.4.0 — 2026-11-28
Added
Dict<V>: aStr-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 asMap(len,get,insert,remove,keys,values,contains_key). ItsEqignores order whileDisplayfollows write order; itscmpis canonical so aDictcan still be aMap/Setkey.- Playground case
collections/dictand conformancetests/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 usemap.empty()(notMap.empty()).
Changed
List/Set/Map/Dictnow 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 concreteLMap<K, V>, notunknown. 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”). Mapis faster: dedup went from O(n²) to a single O(n) pass (adaptive sort on a nearly sorted array makesinsert/removeeffectively linear in TypeScript and Python), andget/contains_keyuse 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 acceptfrom,as, andin. Thusfn from(r: Range)+r.from()is valid, andfrommay 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 byprint), so it cannot go stale against API changes. lt test --usageemits 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
exportdeclaration and at least onetestblock;scripts/playground.shruns every usage program on all three targets and writesplayground/usage.json.
Changed
importsyntax is trimmed to follow Go:fromis removed and the path moves to the end (import money { Price, format } "./wallet/money.lt"), plusimport ( … )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 fmtnow sorts imports by path per block and preserves blank lines as sub-block separators.import . "path"(dot import) andimport _ "path"(blank import) are rejected with a dedicated message; an empty{}in an import is also an error. Thefromkeyword 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. enumoutput in all three backends is now one name per enum: variants are called asShape.Circle(...)(Shape.Pointfor a variant without a payload), no longer as separate symbolsShape_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.VariantMetaper variant, 3 properties per value. - Python: constructors become
@staticmethod/ClassVarinside the enum class,_shape_displayis removed. A variant without a payload stays a value (Shape.Point). - Go:
lt.Variantloses theDisplayfield and gainsType;LtDisplayrendersType.Tag(payload)structurally, soShapeDisplayis gone. Constructors remain package-level functions because Go does not allow generic function values.
- TypeScript:
0.2.1 — 2026-11-27 (breaking: v2)
Decision and rationale ledger: engineering/v2-decisions.md. New specification:
docs/spec.md.
Removed
classis removed. The single container is nowpackage.class,pub,static, andselfstay reserved as keywords; using them produces an error that names their replacement.test classandtest fnare removed, replaced bytest "title" { … }inside a package.Expectas a class is removed, replaced by the pseudo-packageexpect.- 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.structas a data type; methods become explicit receiver functions (fn len(p: Point), called asp.len()).exportreplacespub, and applies tostruct,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. EqandOrdcannot be overridden; onlyDisplay(through the receiver functionto_string).${…}interpolation now respects the user’sto_string. Previously the override applied only to explicit.to_string()calls, differing from whatdocs/spec.mdpromised.- JSX: the tag name is a
structname; a lowercase tag = compile error. - A path prefix on a
matchpattern is no longer silently ignored. - Output is determined by the package name, not the
.ltfile name.
Not changed (and why)
mut, assignment,while,for,break,continueare 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 removingclass.- Nominal typing, no
null,Int= wrapping i64,Strper code point, orderedMap/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
valueswith their static type, not theirDisplayresult. The tag signature becomes(List<Str>, List<T>) -> R, and every${expr}must have exactly typeT. There is no longer an implicitDisplay→Strconversion for tagged templates. - Mixed-type values are expressed through a user enum, for example
enum SqlArg { I(Int), S(Str) }, and the tag then takesList<SqlArg>. ${expr}in a plain template is now actually type-checked, andUnitis rejected in an interpolation position.to_string() -> Stris available for every value of typeDisplay. Use this (or an umbrella enum) as the migration path for old tags of typeList<Str>. A user-definedto_stringmethod wins over the built-in version.
Fixed
${expr}interpolation in a tagged template was previously never type-checked; unknown variables or wrong types could passlt 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 typeany.