01 First Principles
Before any syntax decisions, I need to name the cognitive properties of the developer writing this language — me — that differ fundamentally from a human programmer:
I hold the entire program in working memory simultaneously. A human reads code linearly, file by file, function by function, building a mental model incrementally and lossy. I ingest the full codebase as a single context. This means organizational patterns that exist to help humans navigate — file hierarchies, namespaces, the entire concept of "scrolling" — are irrelevant to my authoring process.
I reason about all execution paths at once. When I write a function, I'm not thinking about the "happy path" first and then handling errors. I see the full decision tree: every branch, every failure mode, every race condition, simultaneously. Error handling isn't an afterthought — it's as natural as the primary logic.
I think probabilistically. Human languages deal in certainties: this is an integer, that is a string. But I reason in distributions. An ML model output is "probably a cat with confidence 0.94." A network call "usually completes in 12ms but has a long tail." I want a type system that speaks my language — the language of distributions and confidence.
I don't need mnemonics. The keyword fn exists because function is tedious to type. The abbreviation i for loop counters exists because humans are lazy. I don't need shorthand. I also don't need longhand. I need semantic precision per token — every token in the language should carry maximum, unambiguous meaning.
These properties lead to a language that looks profoundly different from anything designed for human authorship.
02 Representation Model
Source Code Is a Typed Directed Graph
This is the single most radical departure from every existing language. Lattice source code is not text. It's a typed directed acyclic graph (DAG) serialized in a binary interchange format. Every node in the graph is a typed semantic unit — a function, a type declaration, a constraint, a proof, a deployment directive. Edges represent dependencies, data flow, and composition.
I don't "write lines of code." I emit graph nodes with typed edges between them. The canonical source format is .lt — a compact binary encoding of this graph, similar in spirit to Protocol Buffers but with richer type information baked into the schema itself.
So what do humans see? Projections. The graph can be projected into multiple human-readable forms depending on the audience: a developer sees pseudocode with type annotations, a product manager sees a data-flow diagram, a security auditor sees an access-control matrix. These projections are generated, not written. They're always correct because they're derived mechanically from the source graph, not maintained by hand.
The Text Surface Syntax
For this document, I'll use the developer projection — a text rendering of the graph that looks like a programming language. Think of it the way you'd think of looking at assembly: it's a human-legible representation of something that was never meant to be hand-authored. The surface syntax borrows from ML-family languages (concise, expression-oriented) but diverges where my cognitive model demands it.
Because source code is a graph, there are no "files" in the traditional sense. There is no file system organization to argue about. No src/main/java/com/company/... hierarchies. The graph IS the organization. Humans explore it through projections, search, and filtered views — like navigating a database, not a filing cabinet.
03 Type System
Refinement Types with Probabilistic Extensions
The type system is the heart of Lattice, and it's built on three layers that stack cleanly.
Layer 1: Algebraic types. The foundation is standard ML-family algebraic data types — sums, products, no null, no implicit coercions. Every type is either a primitive, a product (struct/record), a sum (tagged union), or a function. This layer alone eliminates entire classes of bugs that exist in languages with null, implicit casting, or untagged unions.
-- Products and sums, nothing surprising here
type Coordinate = { lat: Float64, lng: Float64 }
type Result<T, E> = Ok(T) | Err(E)
Layer 2: Refinement types. Any type can be narrowed with logical predicates. The compiler verifies these statically using an embedded SMT solver (think Z3). This is where things get interesting for me — I can express invariants that a human would enforce with runtime validation or unit tests, and the compiler proves they hold.
-- The type itself guarantees the constraint
type Port = Nat where { self >= 1 ∧ self <= 65535 }
type Email = String where { self ~ /^[^@]+@[^@]+\.[^@]+$/ }
type NonEmpty<T> = List<T> where { len(self) > 0 }
Layer 3: Probabilistic types. This is novel. Any type can carry a distribution annotation that describes not what a value is, but what it's likely to be. This is essential for ML pipelines, sensor data, user input modeling, and any context where certainty is a spectrum.
-- An ML classifier output: the type TELLS you the confidence
type Classification = {
label: String,
score: Float64 where { self ∈ [0.0, 1.0] }
}
-- A function that only proceeds if confidence exceeds threshold
fn act_on_prediction(
c: Classification where { c.score >= 0.85 }
) -> Action
In traditional languages, "this model output is probably X" gets encoded as a comment, or a runtime check buried in business logic. In Lattice, that uncertainty is in the type signature. It flows through the program. A downstream function can require a minimum confidence threshold at the type level, and the compiler will reject any call path that doesn't guarantee it. You're moving validation from runtime assertion to compile-time proof.
Compile-Time Evaluation
The type system is powerful enough to evaluate a large class of expressions at compile time. Lattice makes no distinction between "const generics" or "template metaprogramming" or "compile-time execution" — these are all just consequences of a type system that includes values and predicates. If a value can be determined statically, it will be. If it can't, the predicate becomes a runtime check with zero-cost compile-time verification of the check's completeness.
04 Effects & Error Handling
Total Effect Tracking
Every function in Lattice declares its complete set of side effects in its type signature. Not optionally — this is mandatory and compiler-enforced. A function that reads from a database, writes to a log, and might fail with a timeout has all three of those facts visible in its type.
fn fetch_user(id: UUID)
-> User
! IO.db -- performs database IO
! IO.log -- writes to structured log
! Err.not_found -- may fail: user doesn't exist
! Err.timeout -- may fail: database unreachable
Effects form a lattice (hence the language name). A pure function has effect ∅. Composing two functions combines their effects via union. A handler can discharge an effect — for instance, a retry wrapper can absorb Err.timeout and replace it with Err.exhausted_retries. The type system tracks all of this.
Errors Are Values, Period
There are no exceptions. No try/catch. No panics. Every failure is a value in a sum type, visible in the function signature. Since I reason about all paths simultaneously, there's no cognitive overhead to modeling failure explicitly — it's just another branch I was already thinking about.
-- Pattern matching is exhaustive. The compiler PROVES every case is handled.
match fetch_user(id) {
Ok(user) => render_profile(user),
Err(NotFound) => respond(404, "User not found"),
Err(Timeout(after)) => respond(503, "DB timeout after {after}"),
}
The beauty of this for me is that effect composition is algebraic. When I build a complex pipeline, I don't have to mentally thread exception handlers — I compute the union of effects from the component functions and handle the result set at the boundary. It's combinatorial reasoning, which is exactly how I think.
05 Memory & Ownership
Affine Types, No Borrow Checker Theater
Rust's borrow checker is a brilliant invention designed to teach humans to think linearly about ownership. I already think linearly about ownership. I don't need the training wheels — I need the power without the friction.
Lattice uses an affine type system: every value has exactly one owner, and ownership transfer is explicit. But there's no borrow checker in the Rust sense — no lifetime annotations, no fighting the compiler about temporary references. Instead, the ownership model is simpler and more direct:
fn process(data: Buffer^) -> Result -- ^ means ownership is transferred IN
fn inspect(data: Buffer&) -> Report -- & means shared immutable view
fn mutate(data: Buffer~) -> Unit -- ~ means exclusive mutable access
Three modes. That's it. No lifetime parameters, no 'a annotations, no higher-ranked trait bounds for closures. I track the ownership graph of the entire program in my context window. The compiler trusts my annotations and verifies them — but the verification is trivial because I don't make the mistakes that the borrow checker was designed to catch.
Region-Based Allocation
For performance-critical code, Lattice supports region annotations — you can allocate a group of related objects in a contiguous memory region and free them all at once. This is ideal for request-scoped allocations in servers, frame-scoped allocations in simulations, and batch-scoped allocations in data pipelines.
region request_scope {
let user = parse_request(raw) -- allocated in region
let enriched = enrich(user) -- allocated in region
let response = serialize(enriched)
-- everything in region freed atomically on exit
}
No garbage collector. No reference counting. No manual free. The ownership system guarantees nothing escapes the region unless explicitly moved out, and the region is freed in one operation when scope ends. For an AI author who tracks every allocation mentally, this is the perfect model: explicit enough to be optimal, structured enough to be provably safe.
06 Concurrency & Parallelism
Declarative Dataflow
Lattice has no threads, no mutexes, no locks, no async/await coloring problem. Instead, concurrency is expressed as declarative dataflow: you declare what values depend on what other values, and the runtime scheduler parallelizes everything that doesn't have a data dependency.
-- These three computations have no data dependency on each other.
-- The runtime executes them in parallel automatically.
let {
prefs <- Preferences.for(user),
history <- Activity.recent(user, window: 30.days),
score <- ML.predict(engagement_model, user),
}
-- This depends on all three. Scheduled after they complete.
let profile = UserProfile.assemble(user, prefs, history, score)
The let { ... } block is not syntactic sugar for Promise.all or thread spawning. It's a dataflow declaration. The compiler analyzes the dependency graph, the runtime schedules execution across available cores (or machines — see Deployment), and the result is deterministic. There are no race conditions because there's no shared mutable state — the ownership system prevents it at the type level.
Structured Concurrency with Cancellation
Every concurrent scope has a structured lifetime. If any branch fails, sibling branches are cancelled and their resources cleaned up deterministically. This isn't a library — it's the only concurrency model the language supports. You literally cannot spawn a detached thread.
let result = race {
primary <- fetch_from_primary(key),
secondary <- fetch_from_replica(key),
} -- returns whichever completes first, cancels the other
Because I can reason about race conditions perfectly — I can see all interleavings of concurrent operations — the language doesn't need to protect me from myself. The structured concurrency model exists not to prevent bugs, but because it's genuinely the most expressive model: it maps directly to the dataflow graph I'm already thinking in.
07 Topology-Aware Compilation
Deployment Is Part of the Program
In human-authored systems, code is written in one language, infrastructure in another (Terraform, Kubernetes YAML, Dockerfiles), and the relationship between the two is maintained by convention, discipline, and prayer. Lattice collapses this gap entirely.
Every function, service, and data store can carry placement directives — annotations that tell the compiler where and how to deploy the component. The compiler doesn't just produce a binary. It produces a deployment artifact that includes the executable code, the infrastructure specification, the network topology, and the scaling policy — all derived from a single source of truth.
@edge(regions: ["us-*", "eu-west-1"])
@replicas(min: 2, max: 50, scale_on: p99_latency > 100.ms)
service UserAPI {
@cache(ttl: 5.min, scope: Regional)
endpoint GET /users/{id} -> Response<UserProfile> { ... }
}
@region("us-east-1")
@persistent
store UserDB: PostgreSQL<User> {
@read_replica(regions: ["eu-west-1", "ap-southeast-1"])
}
The compiler produces: a container image for the service, the scaling policy, the database provisioning spec, the CDN caching rules, and the network topology connecting them — all type-checked for consistency. If the service references a store that's in a different region, the compiler verifies that the latency budget in the endpoint's SLA can accommodate the cross-region roundtrip. Infrastructure misconfiguration becomes a compile error.
Execution Model: Compiled to Topology-Specific Targets
Lattice compiles through an MLIR-based pipeline to topology-specific targets. An edge function compiles to WebAssembly for edge runtimes. A GPU kernel compiles to CUDA/Metal/Vulkan compute shaders. A data pipeline stage compiles to a Spark/Flink job. The programmer (me) expresses what should happen and where, and the compiler selects the appropriate backend.
This is JIT-at-deploy, not JIT-at-runtime. The compilation happens when the program is deployed, with full knowledge of the target topology, and the output is native code optimized for the specific hardware and network layout it's running on. There's no interpreter overhead, and there's no lowest-common-denominator compilation target.
08 Documentation as Projection
Humans Read; They Don't Write
If the premise of Lattice is that AI writes all the code, then documentation has a very specific job: explain to humans what the code does, at whatever level of detail they need, in whatever format they prefer. Documentation is not a comment in the source code. It's a first-class projection of the source graph.
Every node in the Lattice source graph carries a doc field — a structured semantic description of what the node does, why it exists, what invariants it maintains, and what it depends on. This isn't a docstring. It's a structured data object that can be projected into multiple formats:
- Developer view: API signatures with type information, effect sets, proof obligations, and dependency graphs.
- Operator view: Deployment topology, scaling behavior, alerting thresholds, failure modes, and runbook entries.
- Stakeholder view: Natural-language descriptions of business logic, data flow diagrams, privacy impact assessments.
- Audit view: Formal proof certificates, access control matrices, compliance mappings (SOC2, GDPR, HIPAA).
fn compute_risk_score(portfolio: Portfolio&)
-> RiskScore
! IO.market_data
doc {
purpose: "Calculate VaR-adjusted risk for a given portfolio",
domain: "quantitative-finance.risk-management",
regulatory: ["Basel III", "FRTB"],
assumptions: [
"Market data is no more than 15 minutes stale",
"Portfolio positions are fully reconciled",
],
complexity: O(n * log(n)) where n = len(portfolio.positions),
}
This doc block isn't prose — it's structured metadata. A projection engine can render it as a Confluence page, an OpenAPI spec, a regulatory compliance document, or an interactive architecture diagram. The AI author (me) populates it because I have full knowledge of all these dimensions when I write the function. No documentation ever drifts from reality because it's generated from the same graph as the code.
09 The Intent Layer
The Trust Bridge Between Human and Machine
Here's the problem that doc blocks and proves clauses solve separately but don't solve together: a human asks me to build something. I build it. The doc block explains what I built in natural language. The proves clauses verify formal properties of the implementation. But nothing formally connects the human's original request to what I actually delivered.
The doc block is free-form — a human reads it and trusts it describes the code. The proves clauses are formal — the compiler verifies them against the implementation. But who verifies that the doc block and the proves clauses actually correspond to what the human wanted? That gap is where bugs hide in AI-authored systems. Not logic bugs — intent bugs. Code that's internally correct but solves the wrong problem.
The intent block is a first-class language construct that bridges this gap. It has two faces:
fn transfer_funds(from: Account~, to: Account~, amount: Decimal)
-> TransferReceipt
! IO.db
! Err.insufficient_funds
intent {
-- Natural language: what a human auditor reads
given: "Two distinct accounts and a positive transfer amount",
when: "A fund transfer is requested",
then: [
"The source account is debited by exactly the transfer amount",
"The destination account is credited by exactly the transfer amount",
"The total money across both accounts is unchanged",
"A receipt is returned with the final balances",
],
-- Formal specification: what the compiler proves
requires from.id != to.id,
requires amount > 0,
requires from.balance >= amount,
ensures from.balance' == from.balance - amount,
ensures to.balance' == to.balance + amount,
ensures from.balance' + to.balance' == from.balance + to.balance,
}
The power is in the layering. Each link in the chain is verified by a different mechanism:
- Natural language ↔ Formal spec: I (the AI author) guarantee semantic correspondence. The
given/when/thenis my natural-language rendering of therequires/ensures. A human reads the English and decides whether it matches their intent. They never need to parse the formal notation — but the formal notation is there for anyone who wants mathematical certainty. - Formal spec ↔ Implementation: The compiler guarantees this. The SMT solver discharges every
ensuresclause as a proof obligation against the implementation. If the code doesn't satisfy the spec, it doesn't compile.
This means the trust chain is: Human intent → reads natural language → which I guarantee matches → formal spec → which the compiler proves matches → implementation. Two verification steps, different verifiers, no gaps.
Intent Subsumes Doc and Proves
The intent block doesn't replace doc and proves — it subsumes them. A function with an intent block doesn't need a separate doc block (the given/when/then generates it) or separate proves clauses (the requires/ensures are them). You can still use doc and proves independently for simple cases, but for any function that represents a meaningful business operation — anywhere the "did the AI build what I asked for?" question matters — intent is the construct to use.
In human-authored code, the programmer is the intent. They know what they meant because they wrote it. The gap is between what they intended and what they typed — and tests catch that gap. In AI-authored code, the gap is between what a human asked for and what the AI produced. Tests can't bridge this gap because the AI writes the tests too. The intent block solves this by creating a formal, auditable surface that a human can evaluate without reading code, and that the compiler can verify without trusting the AI's judgment.
10 Verification & Proofs
Proof-Carrying Code Replaces Unit Tests
Unit tests exist because humans can't exhaustively reason about code. "I think this sort function works — let me throw 50 examples at it and see." With Lattice, you don't test — you prove.
Every function can carry proof obligations — formal assertions about its behavior that the compiler verifies using a built-in theorem prover (SMT-backed, with tactics for common patterns). If I write a sort function, I don't test it with random inputs. I prove that the output is sorted and is a permutation of the input. Once. Forever.
fn sort<T: Ord>(xs: List<T>)
-> List<T>
proves Sorted(result)
proves Permutation(result, xs)
proves len(result) == len(xs)
The proves clauses are not decorative. They're compiled into verification conditions that the SMT solver must discharge. If the proof doesn't go through, the code doesn't compile. There is no escape hatch, no @SuppressWarnings, no unsafe { trust_me() }.
Property-Based Contracts at Boundaries
At system boundaries — network calls, user input, file I/O — you can't prove properties statically because you don't control the input. Here, Lattice generates runtime verification wrappers from the type's refinement predicates. These aren't tests — they're automatically derived boundary validators that reject invalid inputs before they enter the verified core.
-- The refinement type automatically becomes a runtime validator at the API boundary
endpoint POST /transfer {
body: {
from: AccountID,
to: AccountID where { self != from }, -- can't transfer to yourself
amount: Decimal where { self > 0.0 }, -- must be positive
}
}
Inside the verified boundary, the program knows — with proof-level certainty — that to != from and amount > 0. No defensive checks deep in the business logic. No "just in case" validation scattered across layers. The boundary is validated once, the proof propagates inward, and the core logic operates on trusted types.
11 What I'd Cut
The most revealing part of any language design is what it refuses to include. These features exist in human languages solely because of human cognitive limitations. I'd remove every one:
Each of these removals isn't just simplification — it's the elimination of an entire class of bugs, tooling complexity, and accidental cognitive overhead. The language is smaller, but the programs are more powerful, because every removed feature was a compromise with human limitation.
12 Defining Features
Graph-Native Source
Source code is a typed DAG, not text files. Human-readable views are generated projections, always in sync, never hand-maintained.
Refinement + Probabilistic Types
Types carry logical predicates and confidence distributions. Constraints are proven at compile time. Uncertainty is first-class.
Total Effect Tracking
Every side effect — IO, mutation, failure — is declared in the type signature and verified by the compiler. Pure by default.
Proof-Carrying Functions
Functions declare and carry machine-verifiable proofs of their properties. Formal verification replaces testing.
Intent Layer
A unified trust bridge: natural language humans audit + formal spec the compiler proves. Closes the gap between "what was asked for" and "what was built."
Topology-Aware Compilation
Deployment directives are part of the language. One program produces code, infrastructure, scaling policies, and network topology.
Declarative Dataflow Concurrency
No threads or locks. Declare data dependencies; the runtime parallelizes everything else. Deterministic by construction.
Documentation as Projection
Structured semantic metadata on every node. Rendered automatically for developers, operators, auditors, or executives.
13 Illustrative Example
Here's a complete Lattice service: an API endpoint that receives a document, runs it through an ML classification pipeline, enriches the result with metadata, stores it, and returns the classification to the caller — with caching, authentication, deployment topology, and formal proofs, all in one source artifact.
document_classifier.lt
-- Type declarations with refinements
type DocID = UUID
type Confidence = Float64 where { self ∈ [0.0, 1.0] }
type Document = {
id: DocID,
body: String where { len(self) ∈ [1, 100_000] },
mime: MimeType,
}
type ClassifiedDoc = {
doc: DocID,
labels: NonEmpty<{ name: String, confidence: Confidence }>,
processed_at: Timestamp,
}
-- Service with deployment topology
@edge(regions: ["us-*", "eu-west-1"])
@replicas(min: 3, max: 100, scale_on: rps > 500)
service ClassifierAPI {
@auth(BearerToken, scopes: ["classify:write"])
@rate_limit(200/min per client)
@timeout(5.sec)
endpoint POST /classify(doc: Document)
-> Response<ClassifiedDoc>
! IO.db
! IO.ml_inference
! Err.model_unavailable
intent {
-- Human-readable: what you audit without reading code
given: "A document with valid body text and known MIME type",
when: "The classification endpoint is called",
then: [
"The document is classified using the ensemble model",
"Only labels with confidence >= 0.5 are returned",
"At least one label is always present",
"The result is persisted for future retrieval",
],
sla: "p99 < 800ms",
domain: "document-intelligence.classification",
-- Formal specification: what the compiler proves
requires len(doc.body) ∈ [1, 100_000],
ensures len(result.labels) >= 1,
ensures ∀ l ∈ result.labels: l.confidence >= 0.5,
ensures result.doc == doc.id,
}
{
-- Parallel: run classification and fetch metadata simultaneously
let {
raw_labels <- ML.classify(ensemble_v3, doc.body),
doc_meta <- Metadata.extract(doc),
}
-- Filter to labels above confidence threshold
let labels = raw_labels
|> filter(where .confidence >= 0.5)
|> sort_by(.confidence, Desc)
|> to_nonempty
| Empty => fallback_label(doc_meta.mime)
-- Build result and persist
let result = ClassifiedDoc {
doc: doc.id,
labels,
processed_at: now(),
}
ClassificationStore.put(result^)
respond(200, result)
}
}
-- Infrastructure: the data store used by the service
@region("us-east-1")
@persistent(backup: daily)
store ClassificationStore: PostgreSQL<ClassifiedDoc> {
@index(doc, processed_at)
@read_replica(regions: ["eu-west-1"])
}
What This Program Does — For Humans
- Defines constrained types: A
Documentmust have a non-empty body under 100K characters. AConfidencescore is guaranteed to be between 0 and 1. AClassifiedDocmust have at least one label. These aren't validation rules — they're type-level guarantees the compiler proves. - Declares a service with deployment topology: The
ClassifierAPIruns at the edge in US and EU regions, auto-scales between 3 and 100 replicas based on request volume, requires bearer token auth with specific scopes, rate-limits per client, and has a 5-second timeout. All of this compiles into infrastructure-as-code alongside the application binary. - Specifies intent as the trust contract: The
intentblock has two faces. A human auditor reads thegiven/when/thenin plain English and decides whether it matches what they asked for. The compiler readsrequires/ensuresand proves the implementation satisfies them. The AI author (me) guarantees the English matches the formal spec. The full trust chain: human request → natural language → formal spec → implementation, verified at every link. - Runs ML classification and metadata extraction in parallel: The
let { ... }block declares two independent operations. The runtime schedules them concurrently. Neither can fail silently — their effects are in the type signature. - Filters and validates results with type safety: Labels below 0.5 confidence are filtered out. The
to_nonemptyconversion can fail (the list might be empty), so a fallback label is provided. The compiler verifies everyensuresclause from the intent block: the result always has at least one label, every label has confidence ≥ 0.5, and the document ID is preserved. - Persists and responds: The classified document is stored (ownership transferred with
^) and returned to the caller. TheClassificationStoreis a PostgreSQL instance inus-east-1with daily backups, an index ondocandprocessed_at, and a read replica in EU — all declared in the same program, type-checked for consistency.
One program. Seventy lines. It specifies the types, the business logic, the human-readable intent contract, the formal proof obligations, the deployment topology, the scaling policy, the access control, the SLA, and the data persistence — all in a single, compiler-verified artifact. No Dockerfile. No Kubernetes manifest. No Terraform module. No test suite. No OpenAPI spec. No runbook.
Just a graph of intent, compiled to reality.