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.