Skip to content

Latest commit

History

2,021 Commits

Folders and files

NameName
Last commit message
Last commit date

TML - To Machine Language

License: Apache 2.0C++20

TML is a batteries-included programming language built for the AI era. It ships a native MCP server inside the compiler, integrated documentation, built-in test/coverage/bench/fuzz tooling, an embedded LLVM backend with native OS linker integration, a persistent compilation daemon (22ms cached builds), Tracy profiler integration, and self-documenting syntax designed for deterministic LLM code generation.

One binary. Zero external tools. 12,000+ tests. 99% library coverage. Rust-parity performance. Everything you need from code to production.

Status: The C++ compiler is 100% functional (beta) — all language features, standard library, and tooling are fully implemented and test-covered.

Self-hosting paused by strategic decision (2026-07): the self-hosted TML compiler (written in TML itself) was not finished — work on it was deliberately paused, not abandoned. Building it surfaced foundational issues in the language's memory model (RAII drop insertion over raw-pointer smart pointers causing a double-free/use-after-free bug class) and codegen stability (invalid-IR and non-deterministic failures) that must be fixed before self-hosting can succeed. The project's current focus is the Stabilization roadmap (ERA 0): memory-model soundness, codegen reliability, and a real-application acceptance gate. Full analysis and corrective plan: docs/analysis/tml-table-analysis/.

use std::json::Json
use std::hash::fnv1a64
func main() {
let data = Json::parse("{\"name\": \"TML\", \"year\": 2026}")
let name = data.get_string("name")
let hash = fnv1a64(name)
println("Language: " + name)
println("Hash: " + hash.to_hex())
}

Build and Run

Prerequisites

  • Zig 0.14–0.15.x (recommended — fastest builds, no Visual Studio required; Zig 0.16+ is NOT supported, see note below)
  • CMake 3.20+
  • Ninja (required for Zig CC and Clang builds, recommended for MSVC)
  • LLVM 15+ (pre-built static libraries)

Alternative compilers (if Zig is not available):

  • MSVC 19.30+ (Visual Studio 2022+) — scripts\build.bat --msvc
  • Clang 15+ — scripts\build.bat --clang

Install Zig:

# Windows (winget — pin to 0.15.2)
winget install zig.zig --version 0.15.2
# Windows (scoop)
scoop install zig@0.15.2
# Linux# Download 0.15.2 from https://ziglang.org/download/# macOS (Homebrew)
brew install zig@0.15

Zig 0.16+ breaks the build. Zig 0.16 changed how it links the Windows UCRT (Universal C Runtime). When building executables with -D_DLL -D_MT, zig 0.16's lld-link fails to resolve __declspec(dllimport) symbols like strtol, fopen, getenv etc. — it finds them in libucrt.lib (static) but rejects them because they are "not an import library". Additionally, the pre-built LLVM static libraries use /MT (static CRT) which causes lld-link: error: /failifmismatch for RuntimeLibrary when TML compiles with /MD (dynamic CRT). Since lld-link does not support /FORCE:MULTIPLE (MSVC-only), there is no workaround. Use Zig 0.15.2.

Install Ninja:

pip install ninja # Works everywhere
winget install Ninja-build.Ninja # Windows
sudo apt install ninja-build # Linux
brew install ninja # macOS

Optional Dependencies

ModuleRequiresPurpose
std::cryptoOpenSSL 3.0+Cryptographic operations
std::zlibzlib, brotli, zstdCompression algorithms
vcpkg install --x-install-root=vcpkg_installed --triplet=x64-windows # or x64-linux, arm64-osx

Build

First-time bootstrap — build the vendored LLVM submodule once. Subsequent compiler builds reuse the output and take seconds.

git submodule update --init --recursive src/llvm-project
# Windows (one-time, 30-90 minutes)
scripts\build-llvm.bat # Release build of build/llvm/# Linux/Mac
./scripts/build-llvm.sh # Equivalent

Once build/llvm/ exists, CMake's find_package(LLVM CONFIG) picks it up automatically — no LLVM_DIR environment variable needed.

The compiler build system then auto-selects the best host compiler:

PriorityCompilerFlagRequirements
1 (default)Zig CC (Clang 20)--zigzig + ninja in PATH
2MSVC (cl.exe)--msvcVisual Studio 2022+
3Clang--clangclang + ninja in PATH
# Windows — auto-detects best compiler (Zig CC > MSVC > Clang)
scripts\build.bat # Debug build
scripts\build.bat release # Release build# Force a specific compiler
scripts\build.bat --zig # Zig CC (fastest, default)
scripts\build.bat --msvc # MSVC cl.exe
scripts\build.bat --clang # System Clang# Other options
scripts\build.bat --clean # Clean rebuild
scripts\build.bat --tests # Build C++ unit tests
scripts\build.bat --target tml # Build only tml.exe# Linux/Mac
./scripts/build.sh debug
./scripts/build.sh release

Usage

tml build app.tml # Compile to executable
tml run app.tml # Compile and run
tml check app.tml # Type-check only (fast)
tml test# Run test suite
tml test --suite=core/str # Run one module's tests
tml test --coverage # Tests + coverage report
tml fmt src/ # Format code
tml lint src/ # Lint code
tml daemon start # Start persistent compiler daemon
tml daemon stop # Stop daemon
tml mcp # Start MCP server
tml build app.tml --emit-ir # Emit LLVM IR
tml build app.tml --release # Optimized build

What Makes TML Different

1. Native MCP Server in the Compiler

TML is the first language with a Model Context Protocol server built directly into the compiler. Any AI assistant (Claude, GPT, local models) can programmatically compile, test, lint, format, and inspect TML code through a standardized JSON-RPC 2.0 interface.

# Start the MCP server (stdio transport)
tml mcp

The server exposes 14 tools that map 1:1 to compiler capabilities:

ToolWhat it does
compileCompile a source file to executable or library
runBuild and execute, returning program output
buildFull build with crate-type, optimization, output options
checkType-check without compiling (fast feedback)
emit-irEmit LLVM IR with optional function filtering and chunked output
emit-mirEmit Mid-level IR for debugging
testRun tests with filtering, coverage, profiling, and suite-level targeting
formatFormat source files (check or write mode)
lintLint for style and semantic issues (with auto-fix)
docs/searchHybrid BM25 + HNSW semantic search over all documentation
docs/getGet full documentation for a specific item by path
docs/listList all items in a module, grouped by kind
docs/resolveResolve a documentation item by its qualified path
cache/invalidateInvalidate compilation cache for specific files

This is not a wrapper or plugin. The MCP server links against the same compiler internals used by tml build. When an AI calls check, it runs the real type checker. When it calls emit-ir, it generates real LLVM IR. The AI gets the same diagnostics, errors, and output a human developer would see.

The docs/search tool uses hybrid retrieval combining BM25 lexical scoring with HNSW semantic vector search, merged via Reciprocal Rank Fusion. It includes query expansion (65+ TML-specific synonyms), MMR diversification, and multi-signal ranking. Indices are cached to disk for sub-10ms query latency across 6000+ documentation items.

Why this matters: Traditional languages require AI assistants to shell out to gcc, rustc, or go build and parse text output. TML gives AI assistants structured, programmatic access to every compilation stage — including semantic documentation search that understands TML's vocabulary.


2. Everything Built In - Zero External Tools

Most languages require a constellation of separate tools. TML ships everything in a single binary:

CapabilityTraditionalTML
Compilationgcc/clang + ld/lldEmbedded LLVM + native OS linker
TestingExternal frameworks (gtest, pytest, jest)@test decorator + DLL-based runner
CoverageSeparate tools (gcov, tarpaulin, istanbul)--coverage flag
BenchmarkingExternal (criterion, hyperfine)@bench decorator + baseline comparison
FuzzingExternal (AFL, libFuzzer)@fuzz decorator + corpus management
FormattingExternal (rustfmt, gofmt, prettier)tml fmt
LintingExternal (clippy, golint, eslint)tml lint (style + semantic + complexity)
DocumentationExternal (rustdoc, godoc, jsdoc)tml doc (JSON, HTML, Markdown)
ProfilingExternal (perf, valgrind, Instruments)--profile (Chrome DevTools format)
Package managementExternal (cargo, npm, pip)tml deps / tml add
Compilation daemonExternal (ccache, sccache)tml daemon (22ms cached, 4.5x faster than cargo check)
AI integrationNone / LSP workaroundsNative MCP server
# All of this is one binary
tml build app.tml # Compile
tml run app.tml # Run
tml test --coverage --profile # Test + coverage + profiling
tml fmt src/ --write # Format in-place
tml lint src/ --fix # Lint with auto-fix
tml doc src/ --format=html # Generate documentation
tml mcp # Start MCP server for AI

3. Embedded LLVM Backend (In-Process Compilation)

TML compiles source to object code entirely in-process via an embedded LLVM backend (55+ static libraries). Only the final link step uses the native OS linker:

Source (.tml) -> Lex -> Parse -> Typecheck -> Borrow Check
-> HIR -> THIR -> MIR -> LLVM IR -> Object File -> Executable
^ ^ ^
Coercions, dispatch Embedded LLVM Native OS linker
exhaustiveness (in-process) (link.exe/ld)

No clang/gcc subprocess for compilation. The LLVM IR-to-object pipeline runs in-process with O2 optimization, producing AVX-512 SIMD code competitive with Rust.

This also means cross-compilation is built in:

tml build app.tml --target=x86_64-unknown-linux-gnu # Linux
tml build app.tml --target=x86_64-apple-darwin # macOS
tml build app.tml --target=x86_64-pc-windows-msvc # Windows

4. Demand-Driven Query System with Red-Green Incremental Compilation

TML uses the same incremental compilation architecture as rustc: a demand-driven query system where each compilation stage is a memoized function with dependency tracking.

QueryContext
├── ReadSource(path) -> SourceFile [fingerprinted]
├── Tokenize(source) -> TokenStream [fingerprinted]
├── Parse(tokens) -> AST [fingerprinted]
├── Typecheck(ast) -> TypedAST [fingerprinted]
├── Borrowcheck(typed) -> Verified [fingerprinted]
├── HirLower(verified) -> HIR [fingerprinted]
├── ThirLower(hir) -> THIR [fingerprinted]
├── MirBuild(thir) -> MIR [fingerprinted]
└── CodegenUnit(mir) -> LLVM IR [fingerprinted + cached to disk]

On rebuild, the system uses a red-green algorithm:

  • GREEN: Input fingerprint unchanged -> skip entire pipeline, load cached LLVM IR from disk
  • RED: Input changed -> recompute, then check if downstream fingerprints actually changed

Change one function in a large project? Only that module's queries are recomputed. If the change doesn't affect the public API, downstream modules stay GREEN.


5. THIR — Typed High-level IR with Exhaustiveness Checking

Between HIR and MIR, TML has a THIR (Typed High-level IR) pass that makes every implicit operation explicit before MIR generation. This is inspired by rustc's THIR but integrated as a first-class query stage:

What THIR doesBefore (HIR)After (THIR)
Materializes coercionsI8 + I32 (implicit widening)CoercionExpr(I8->I32, lhs) + rhs
Resolves method dispatchx.to_string() (unresolved)Display::to_string(x) (resolved, monomorphized)
Desugars operatorsa + b (might be overloaded)Add::add(a, b) (explicit method call)
Checks pattern exhaustivenesswhen color { Red => ... }Warning: missing Green, Blue

The exhaustiveness checker uses the Maranget 2007 usefulness algorithm, supporting enum variants, ranges, literals, wildcards, tuples, and structs.

THIR is enabled by default. The --no-thir flag falls back to direct HIR-to-MIR lowering.


6. Syntax Designed for LLM Code Generation

Every syntax decision in TML eliminates ambiguity that confuses language models. The grammar is strictly LL(1) — deterministic with one-token lookahead — so both LLMs and parsers can process TML without backtracking.

Keywords & Operators

ConceptRustGoC++TMLWhy
Functionfnfuncvoid f()funcSelf-documenting
Logical AND&&&&&&andNatural language
Logical OR||||||orNatural language
Logical NOT!!!notNatural language
Pattern matchmatchswitchswitchwhenIntent-revealing
Unsafe blockunsafe {}lowlevel {}Accurate, not scary
Loop constructsfor/while/loopforfor/while/doloop (unified)One keyword
Exclusive range0..100 to 10English-readable
Inclusive range0..=100 through 10English-readable
Error propagationexpr?if err != nilthrowexpr!Visible marker
Ternaryif c { a } else { b }c ? a : bcond ? a : bC-style, readable
Pipe operatorx |> fUnix-style chaining

Generics & References

ConceptRustGoC++TMLWhy
Generic syntaxVec<T>[]Tvector<T>Vec[T][ has no dual meaning with <
Nested genericsVec<Vec<T>>vector<vector<T>>Vec[Vec[T]]No >> ambiguity
Immutable ref&T*Tconst T&ref TWords over symbols
Mutable ref&mut TimplicitT&mut ref TExplicit intent
Closures|x| x * 2func(x) {}[](x) {}do(x) x * 2| has no dual meaning
Lifetimes'a, 'staticAlways inferredZero syntax noise
Directives#[test]// +build[[nodiscard]]@testClean, unambiguous
Route decorators#[get("/")]@Get("/")Framework-integrated
Auto-derive#[derive(Debug)]@auto(debug)Self-documenting

Type System

ConceptRustGoC++TypeScriptTMLWhy
OptionalOption<T>*T / niloptional<T>T | nullMaybe[T]Intent-revealing
Some / NoneSome(x) / NoneJust(x) / NothingSelf-documenting
Result typeResult<T,E>(T, error)Outcome[T,E]Describes what it is
Traitstraitinterfaceabstract classinterfacebehaviorSelf-documenting
Heap pointerBox<T>implicitunique_ptr<T>Heap[T]Describes storage
Ref countedRc<T>shared_ptr<T>Shared[T]Describes purpose
Atomic RCArc<T>atomic shared_ptrSync[T]Describes purpose
Clone.clone().clone().duplicate()No git confusion
Unit type()voidvoidUnitNamed, explicit
Never type![[noreturn]]neverNeverNamed, explicit
Type declstruct / enumtype structstruct / enumtype / enumtype (unified)One keyword

Integers, Floats & Strings

ConceptRustGoC++TML
Signed integersi8..i128int8..int64int8_t..int64_tI8..I128
Unsigned integersu8..u128uint8..uint64uint8_t..uint64_tU8..U128
Floatsf32, f64float32, float64float, doubleF32, F64
String (owned)Stringstringstd::stringStr
Mutable stringstringstd::stringText (SSO)
Interpolationformat!("{x}")fmt.Sprintfstd::format"Hello {name}"
Raw stringr"text"`text`R"(text)"r"text"
Multiline`multi`"""multi"""

Memory & Ownership

ConceptRustGoC++TML
OwnershipMove semanticsGCCopy semanticsMove semantics
Borrow checkerYesNoNoYes
Interior mutabilityCell<T>, RefCell<T>implicitCell[T], RefCell[T]
RAII / cleanupDrop traitdeferDestructorsDrop behavior
Memory safetyCompile-timeRuntime (GC)ManualCompile-time
Null safetyNo nullnilnullptrNo null (use Maybe[T])

The result: LLMs generate TML code with significantly fewer syntax errors because there are no ambiguous tokens, no overloaded symbols, and every construct has exactly one unambiguous parse.


7. Subprocess-Based Test Runner — 11,000+ Tests in Under a Minute

TML's test runner uses a Go-inspired subprocess architecture: each test suite compiles to a standalone executable that streams results via NDJSON protocol. Combined with hash-based caching, the result is a test system fast enough to be used as a real-time feedback loop for AI-driven development:

MetricValue
Total tests12,000+ across 1,500+ files
Full suite (no cache)~43 seconds
Full suite (cached)~8 seconds
Single file (filtered)Milliseconds
Library coverage99% (15,528/15,628 functions)
# Full suite — 8 seconds with cache
tml test# Filter to one file — millisecond feedback
tml test --filter json_parse
# Run a specific module's tests only
tml test --suite=core/str --no-cache
# Full rebuild + coverage + profiling
tml test --no-cache --coverage --profile
# Profile with Tracy integration
tml test --profile

This performance is not accidental — it's designed for LLM-assisted debugging workflows. An AI assistant can run a targeted test in milliseconds, read the result, fix the code, and re-run — all within a single conversation turn. The full suite at 8 seconds means the AI can validate that nothing else broke before committing.

use test
@test
func test_json_parsing() {
let data = Json::parse("{\"key\": 42}")
assert(data.is_object(), "should parse as object")
assert_eq(data.get_i64("key"), 42 as I64, "key should be 42")
}
@bench
func bench_hash_fnv(b: Bencher) {
b.iter(do() {
fnv1a64("benchmark input string")
})
}
@fuzz
func fuzz_parser(input: Slice[U8]) {
let s = Str::from_utf8(input).unwrap_or("")
let _ = Json::parse(s) // Should never crash
}

Under the hood:

  • Subprocess isolation: Each test suite compiles to a standalone EXE, runs as a subprocess. Crashes in one suite don't affect others
  • NDJSON protocol: Results stream from subprocess to coordinator as structured JSON events
  • Hash-based caching: Source file fingerprints determine what needs recompilation — unchanged suites skip compilation entirely
  • Suite batching: Tests in the same directory are grouped into a single executable. --suite=core/str targets a specific module
  • Coverage tracking: Function-level coverage via TML_COVERAGE_FILE env var — no LLVM profiling overhead, no hangs
  • Benchmark baselines: Save and compare performance across runs
  • Crash capture: Backtraces on test failures
  • Filtered execution: --filter narrows to specific files or test names for instant feedback

8. Integrated Documentation Generation

Documentation is extracted from source comments (/// for items, //! for modules) and generated in three formats without any external tools:

//! Hash functions for data integrity and lookup tables.
//!
//! This module provides non-cryptographic hash functions optimized
//! for speed: FNV-1a (32/64-bit) and MurmurHash2 (32/64-bit).
/// Computes a 64-bit FNV-1a hash of the input string.
///
/// FNV-1a is a fast, non-cryptographic hash function with good
/// distribution properties. Suitable for hash tables and checksums.
///
/// @param input The string to hash
/// @returns A Hash64 value containing the computed hash
///
/// @example
/// let h = fnv1a64("hello")
/// println(h.to_hex()) // prints hex representation
pub func fnv1a64(input: Str) -> Hash64 { ... }
tml doc lib/ --format=html # Interactive HTML docs
tml doc lib/ --format=json # Machine-readable JSON
tml doc lib/ --format=markdown # Markdown for GitHub wikis

9. Built-In Linter with Semantic Analysis

The linter combines text-based style checking with AST-based semantic analysis:

tml lint src/
# W001: Unused variable 'temp' at line 42# S003: Line exceeds 100 characters at line 87# C001: Function 'process_data' has cyclomatic complexity 15 (max: 10)
tml lint src/ --fix # Auto-fix where possible

Rule categories:

  • Style (S): Indentation, line length, naming conventions, trailing whitespace
  • Warnings (W): Unused variables, imports, functions, parameters
  • Complexity (C): Function length, cyclomatic complexity, nesting depth

10. Conditional Compilation with Platform Symbols

Built-in preprocessor with auto-detected platform symbols:

#if WINDOWS
func get_home() -> Str { return env::var("USERPROFILE") }
#elif MACOS
func get_home() -> Str { return env::var("HOME") }
#elif LINUX
func get_home() -> Str { return env::var("HOME") }
#endif
#ifdef DEBUG
func log(msg: Str) { print("[DEBUG] {msg}\n") }
#endif

Predefined symbols include: WINDOWS, LINUX, MACOS, X86_64, ARM64, PTR_64, DEBUG, RELEASE, TEST, and more.


11. SIMD-Optimized Native JSON Engine

TML's JSON parser is not a library written in TML — it's a native C++ engine compiled into the runtime with V8-inspired optimizations:

  • SSE2/AVX2 whitespace skipping: Processes 16 bytes per cycle using _mm_cmpeq_epi8 to find spaces, tabs, and newlines in parallel
  • SIMD string scanning: Vectorized search for quotes, backslashes, and control characters — critical for large string values
  • SWAR hex parsing: Parses 4 hex digits of \uXXXX escapes in a single register operation
  • O(1) character classification: Pre-computed 256-entry lookup tables (kCharFlags) for instant character categorization
  • Zero-copy parsing: Uses std::string_view to avoid allocations during parse

The JSON engine is exposed to TML code through a handle-based FFI:

use std::json::Json
let data = Json::parse("{\"users\": [{\"name\": \"Alice\"}]}")
let name = data.get_path_string("users.0.name") // "Alice"
let json_str = data.to_string() // Round-trips cleanly

This design means JSON-heavy workloads (HTTP APIs, config parsing, data pipelines) run at near-native speed without needing a separate C library.


12. Go-Inspired Concurrency Primitives

TML's concurrency model draws directly from Go's design, implemented as native C runtime functions for zero-overhead performance:

Channels — Go-style bounded MPMC (Multi-Producer Multi-Consumer):

use std::sync::channel
let (tx, rx) = channel[I32](10) // Bounded channel, capacity 10
// Producer thread
thread::spawn(do() {
tx.send(42)
tx.send(99)
})
// Consumer
let value = rx.recv() // Blocks until data available

The channel implementation uses platform-native primitives (CRITICAL_SECTION + CONDITION_VARIABLE on Windows, pthread_mutex_t + pthread_cond_t on POSIX) with a circular buffer for efficient storage. Non-blocking variants (try_send, try_recv) are also available.

Full sync toolkit — all backed by native C:

PrimitiveImplementationInspiration
Mutex[T]SRWLOCK (Win) / pthread_mutex_tRust
RwLock[T]SRWLOCK shared/exclusiveRust
Channel[T]Circular buffer + condition varsGo
Sender[T]/Receiver[T]MPSC on top of channelsGo + Rust
Arc[T]Atomic reference countingRust
AtomicI32/I64/BoolInterlockedExchange / __sync_*Go + Rust
BarrierCount-based synchronizationGo sync.WaitGroup
ConcurrentQueue[T]Lock-free MPMC queueGo channels
ConcurrentStack[T]Lock-free push/pop
Async/AwaitTask queue + cooperative schedulerRust Futures

13. HTTP Server — 183K req/s (Beating Node.js by 32%)

TML ships a full HTTP/1.1 server built entirely in TML (52 source files), achieving 183,000 requests/second on a single machine — outperforming Node.js cluster mode by 32%:

use std::http::{HttpServer, Request, Response, Router}
func main() {
let router = Router::new()
router.get("/", do(req: Request) -> Response {
Response::ok("Hello, World!")
})
router.get("/users/:id", do(req: Request) -> Response {
let id = req.param("id")
Response::json(`{"id": {id}}`)
})
let server = HttpServer::new(router)
server.listen(8080)
}

Features:

  • Radix tree router with parameterized routes (:id, *wildcard)
  • HTTP/1.1 compliance: chunked transfer-encoding (RFC 7230), Expect: 100-continue, keep-alive, idle timeouts
  • Middleware pipeline: onRequest, preHandler, onResponse, onError hooks
  • Route decorators: @Get, @Post, @Put, @Delete, @Patch with auto-registration
  • Controller pattern for structured route organization
  • URL percent-decoding, proper 405 Method Not Allowed with Allow header, 501 Not Implemented
  • IOCP (Windows) and thread pool worker models
  • WebSocket (RFC 6455) with frame codec, masking, and handshake
  • HTTP/2 (RFC 7540) binary frame codec with HPACK header compression (RFC 7541)

14. Async Network Stack

A complete async runtime inspired by Rust's Futures and Tokio:

use std::runtime::{Executor}
use std::stream::{AsyncBufReader, AsyncBufWriter}
// Multi-threaded work-stealing executor
let executor = Executor::new(4) // 4 worker threads
executor.spawn(async_handler())
executor.run()
ComponentDescriptionInspiration
ExecutorMulti-threaded work-stealing with graceful shutdownTokio
Future[T]Cooperative async with Poll[T] (Ready/Pending)Rust
AsyncRead/AsyncWriteAsync I/O behaviors with buffered variantsTokio
select2Race two futures, return first to completeTokio select!
Promise[T]JavaScript-style resolve/reject/then/catch/all/raceJS Promises
Observable[T]Reactive streams with 8 operators + Subject variantsRxJS
PollerPlatform I/O polling (epoll/WSAPoll)mio
TimerWheelO(1) hashed 2-level timer wheelTokio
EventLoopSingle-threaded event orchestrationNode.js/libuv

15. Tracy Profiler Integration

TML integrates the Tracy profiler for zero-cost performance analysis. 70+ instrumented zones across the compiler pipeline and standard library:

# Build with Tracy profiling
scripts\build.bat --profile
# Run with profiling — connect Tracy GUI to see real-time flamegraphs
tml run app.tml --profile
tml test --profile

Instrumented zones cover: lexer, parser, type checker, HIR/MIR lowering, LLVM backend, MIR passes, query cache, HTTP hot paths, collections, I/O, and more. Profiler intrinsics are zero-cost when --profile is not enabled — no runtime overhead in production builds.


16. Pipe Operator

Left-associative pipe operator for readable data transformation chains:

// x |> f → f(x)
// x |> f(a) → f(x, a)
// x |> .method → x.method()
let result = data
|> parse_json
|> .get("users")
|> filter_active
|> .len()

Language at a Glance

// Types: I8-I128, U8-U128, F32, F64, Bool, Char, Str
let name: Str = "TML"
let mut counter: I32 = 0
// Maybe[T] (like Option) and Outcome[T, E] (like Result)
let value: Maybe[I32] = Just(42)
let result: Outcome[I32, Str] = Ok(100)
// Pattern matching with 'when'
when value {
Just(n) => println(n.to_string()),
Nothing => println("empty")
}
// Error propagation with !
func load() -> Outcome[Data, Str] {
let content = read_file("data.json")!
let parsed = parse(content)!
return Ok(parsed)
}
// Closures with 'do'
let doubled = numbers.map(do(x) x * 2)
// Behaviors (traits)
pub behavior Hashable {
pub func hash(this) -> I64
}
// Generics with [T] instead of <T>
func first[T](items: Slice[T]) -> Maybe[ref T] {
return items.get(0)
}
// Enums with data
type Message {
Text(Str),
Number(I32),
Quit
}
// Template literals
let greeting = `Hello, {name}! You have {count} messages.`
// Pipe operator
let result = input |> parse |> validate |> .to_string()

Standard Library

TML ships with a comprehensive standard library covering:

ModuleContents
Core Library
core::arrayFixed-size arrays with map, zip, get, first, last
core::iterIterator adapters (map, filter, fold, chain, zip, enumerate, ...)
core::optionMaybe[T] with combinators
core::resultOutcome[T, E] with combinators
core::str58 string functions (split, trim, contains, replace, parse, ...)
core::sliceSlice[T] and MutSlice[T] fat pointers
core::fmtDisplay, Debug, binary/hex formatting
core::cmpOrdering, PartialEq, PartialOrd, min, max, clamp
core::hashHash behavior for hash-based collections
core::cellInterior mutability (Cell, RefCell, OnceCell, LazyCell)
core::memMemory operations (size_of, align_of, swap, replace)
core::allocHeap[T], Shared[T], Sync[T], Arena, Pool[T] smart pointers
core::encodingbase64, hex, percent, base32/36/58/62/85/91 (14 formats)
core::futureFuture behavior, Poll[T], Context, Waker, select2
core::simdSSE2 intrinsics (I32x4, F32x4, U8x16)
Standard Library
std::collectionsList, HashMap, HashSet, Queue, Stack, Buffer, BTreeMap, Deque
std::fileFile I/O, Path operations, directory traversal
std::httpHTTP server (183K req/s), client, router, middleware, WebSocket, HTTP/2
std::jsonSIMD-optimized JSON parsing, serialization, builder pattern
std::netTCP/UDP sockets, DNS, TLS with ALPN
std::hashFNV-1a, MurmurHash2, ETag generation
std::cryptoSHA, AES-GCM, ChaCha20, RSA, ECDSA, Ed25519, X.509, HMAC
std::zlibDeflate, gzip, brotli, zstd compression
std::sqliteSQLite3 FFI bindings (Database, Statement, Row, Value)
std::regexThompson's NFA engine (no exponential backtracking)
std::syncMutex, RwLock, Barrier, channels, atomics
std::threadThread spawning, thread-local storage
std::streamComposable streams (Duplex, PassThrough, Pipeline, Transform)
std::aioAsync I/O event loop (epoll/WSAPoll, timer wheel)
std::mathTrig, exponential, rounding, constants (PI, E, TAU, ...)
std::datetimeDate, Time, DateTime, SystemTime, Duration
std::randomThreadRng, Random trait, distributions
std::globPattern matching and directory walking (*, ?, **, [a-z], {a,b})
std::osEnvironment variables, system info, CLI args
std::logStructured logging with levels and sinks
std::searchBM25 text index, HNSW vector index, TF-IDF vectorizer, SIMD distance
std::msgpackMessagePack binary serialization — encoder, decoder, type system
std::protobufProtocol Buffers wire format — full proto3, .proto parser, TML codegen
std::promiseJavaScript-style Promise[T] with resolve/reject/then/catch/all/race
std::observableReactive streams with 8 operators + Subject variants

Performance

TML generates code competitive with Rust via LLVM optimization:

BenchmarkTMLRustRatio
List iteration sum (10M I64, AVX-512)4.32B ops/s4.57B ops/s1.06×
Binary size (hello world)42 KB127 KBTML 3× smaller
Cold tml check (with meta cache)0.68s

The list iteration benchmark produces identical optimized IR to Rust: 5-instruction scalar loop, <8 x i64> AVX-512 SIMD with 4 accumulators (32 elements/iteration).


Compiler Architecture

tml/
├── compiler/ # C++ compiler (~240,000 lines)
│ ├── src/
│ │ ├── lexer/ # Tokenizer
│ │ ├── parser/ # LL(1) parser
│ │ ├── types/ # Type checker (Hindley-Milner)
│ │ ├── borrow/ # Borrow checker (NLL + Polonius)
│ │ ├── hir/ # High-level IR
│ │ ├── thir/ # Typed HIR (coercions, dispatch, exhaustiveness)
│ │ ├── mir/ # Mid-level IR (SSA, 30+ optimization passes)
│ │ ├── codegen/ # LLVM IR generation
│ │ ├── query/ # Demand-driven query system (red-green incremental)
│ │ ├── backend/ # Embedded LLVM backend (in-process IR → .obj)
│ │ ├── testing/ # Subprocess test coordinator (NDJSON protocol)
│ │ ├── mcp/ # MCP server (JSON-RPC 2.0, 14 tools)
│ │ ├── doc/ # Documentation generator + semantic search
│ │ ├── format/ # Code formatter
│ │ └── cli/ # CLI, builder, linter, profiler
│ └── include/ # Headers
├── lib/ # ~150,000+ lines of TML
│ ├── core/ # Core library (alloc, iter, str, fmt, cell, encoding, ...)
│ ├── std/ # Standard library (http, crypto, sqlite, stream, aio, ...)
│ └── test/ # Test framework (assert, bench, fuzz, coverage)
├── docs/ # Specs (37 files), user guide (27 chapters), package docs (44 files)
└── scripts/ # Build scripts (Zig CC, MSVC, Clang)

License

Apache License 2.0 - see LICENSE file.

Acknowledgments

  • Rust - Ownership model, borrow checking, pattern matching, THIR/MIR architecture, query-based compilation
  • V8 (Google) - JSON parser design: SIMD whitespace skipping, SWAR hex parsing, lookup-table character classification
  • Go - Channel-based concurrency, bounded MPMC channels, goroutine-inspired async runtime, thread-safe primitives design
  • LLVM - Code generation backend (55+ static libraries, in-process IR → .obj)
  • Tracy - Real-time frame profiler with 70+ instrumented zones
  • Zig - Default C/C++ compiler toolchain (Zig CC = Clang 20 + bundled libc + LLD)
  • MCP (Anthropic) - Model Context Protocol specification for AI-compiler integration

About

TML is a programming language designed specifically for Large Language Models (LLMs). It eliminates parsing ambiguities, provides stable IDs for refactoring, and uses formal contracts to make code generation and analysis deterministic.

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages