# Tangu Programming Language — Complete Documentation Reference (v0.35.0) > Canonical Index: https://tangu.dev/llms.txt > GitHub: https://github.com/tangu-dev ## Idiomatic Tangu & Agent Rules 1. **Stack annotations vertically above `(def ...)` or `(let ...)`**: `#pub`, `#inline`, `#test`, `#bench`, `#(Func ...)`, `#(doc ...)`. 2. **Function parameter forms (`Func`)**: Zero args `(Func () body)`, single arg `(Func x body)`, multiple/typed `(Func [#Int a #Int b] body)`. 3. **Universal sequence vocabulary & zero prelude imports**: `count-of`, `is-empty?`, `contains?`, `first-of`, `last-of`, `nth-of`, `rest-of`, `slice`, `push`, `pop`, `put`, `put-all`, `remove`, `swap-remove`, `sort`, `sort<-`, `reverse`, `reverse<-`, `concat`, `concat<-`. Never import prelude symbols. 4. **Strict equality & booleans**: Always `==` and `!=` (never `=`); `if`, `unless`, `while`, `cond` require strict `Bool`. 5. **Mutability**: `(let #var x 0)` + `(<- x 1)` for rebinding; `(let #mut arr [])` + `(push arr item)` for in-place mutation. 6. **Key-paths, map punning & spreading**: `obj:field` (required), `obj?field` (optional), `{_ host _ port}`, `{...base :extra 1}`. 7. **Error handling**: `(try expr (else fallback-return))` returns early on `Error` or `()`; `(ok-or expr default)` and `(some-or expr default)` compute local fallbacks. 8. **Structs, traits & `derive`**: `(derive Point Eq Hash Ord Clone To-String Default To-JSON From-JSON)`. 9. **Directory-as-module & sorted `use` imports**: Never import `.tan` filenames directly; sort `@standard` modules first, then `@scope/pkg`, then relative `./`. 10. **Databases (`/postgres/client` & `/sqlite/client`)**: Use `query-strong` / `query-one-strong` on `/postgres/client` for `INSERT/UPDATE ... RETURNING` and read-after-write flows; pass user inputs cleanly via `$1` / `?` parameters on `#sql "..."`. --- # Overview ## Why Tangu? Tangu is a high-performance, general-purpose language designed around a single core principle: **code, configuration, markup, stylesheets, and database queries should share one homoiconic s-expression representation**. - **Homoiconic & agent-native**: Every Tangu program, `.data.tan` manifest, `#shtml` UI tree, and `#css` rule sheet is an s-expression AST with zero syntactic ambiguity, making refactoring, macro expansion, formatting, and AI-assisted code generation deterministic. - **Expressive static & dynamic ergonomics**: Combine lightweight gradual type annotations (`#Int`, `#(Array String)`), rich compile-time linting, and structural pattern matching (`when`) with REPL-driven productivity. - **Batteries-included standard library**: Over 80 built-in `@standard` modules covering HTTP servers, full-stack `/web/app` routing, PostgreSQL & SQLite connection pools, ICU4X internationalization (`/i18n`), SIMD vectors (`/simd`), cryptography (`/crypto`, `/jwt`), and image codecs (`/image/*`). ## A language for humans and machines ### Application code (`.tan`) ```tangu #pub (def User (Struct #String #{:min-len 2 :max-len 50} name #(Array String) roles )) (derive User Eq Clone To-JSON From-JSON) #pub #(Func User String) (def describe-user (Func user (let badge (if (contains? user:roles "admin") "Admin" (else "Member"))) "${user:name} (${badge}): ${(join user:roles ", ")}" )) ``` ### Structured data & manifests (`.data.tan`) Configuration files, package manifests (`manifest.data.tan`), and route metadata use pure Tangu data literals without boilerplate punctuation: ```tangu { :name "tangu-site" :version "0.32.0" :server { :host "127.0.0.1" :port 8005 } :targets [:native :jit :js :rust] } ``` ### Composable UI & stylesheets (`#shtml`, `#css`, `#sql`) Reader tags specialize s-expressions for HTML components, scoped CSS rules, and parameterized SQL queries: ```tangu #pub (def (Func [label tone] #shtml [:span.inline-flex.items-center.px-3.py-1.corner-full {:class tone} label ] )) #pub (def card-styles #css [ [".status-card" { :background-color "var(--color-surface-container-low)" :border "1px solid var(--color-outline-variant)" :padding "24px" }] ]) ``` ## Multi-target execution engine Tangu decouples language semantics from the execution backend so you can iterate instantaneously in development and deploy native binaries or JavaScript bundles in production: | Mode | Command | Description | | :--- | :--- | :--- | | **Tree-walk & bytecode VM** | `tangu run main.tan` | Instantaneous startup with a compact 16-byte `Value` representation, flat `SymbolId` caches, and precise source-mapped stack traces. | | **Cranelift JIT** | `tangu run --jit main.tan` | In-memory native machine-code compilation via Cranelift from Tangu's Typed Intermediate Representation (TIR). | | **Native AOT binary** | `tangu compile --target native main.tan` | Ahead-of-time compilation into standalone native executables. | | **Rust & JavaScript transpilers** | `tangu compile --target rust\|js main.tan` | Lowers TIR into idiomatic Rust crates or ES modules with source maps. | ## Built-in developer toolchain The `tangu` CLI ships as a single self-contained binary with everything needed to build, test, document, and maintain projects: | Command | Purpose | | :--- | :--- | | `tangu run` & `eval` (`e`) | Execute a `.tan` script/package or evaluate expressions directly (`--jit`, `--opt none\|basic\|aggressive`). | | `tangu repl` | Interactive Read-Eval-Print Loop with history and tab completion. | | `tangu test` | Discover and execute `#test` functions across `*.test.tan` files in parallel. | | `tangu check` | Run fast static type checking and symbol resolution without executing code. | | `tangu lint` & `fix` | Run 110 static lint rules (`; #allow(...)`), auto-fixes, and unambiguous auto-imports (`tangu fix`). | | `tangu format` | Format `.tan`, `.data.tan`, `#shtml`, and `#css` files deterministically (`--check` in CI). | | `tangu doc` (`docs`) | Introspect documentation for any module (`tangu doc /fs`), symbol (`tangu doc count-of`), or search query (`tangu doc -s json`). | | `tangu sym` & `refactor` | Inspect outlines/references/hover types and perform workspace-wide semantic renames and moves. | | `tangu bench` | Run `#bench` performance suites across optimization levels and `--jit` / `--native` targets. | | `tangu doctor` & `upgrade` | Verify local environment setup and self-upgrade the toolchain from `tangu.dev`. | --- # Language tutorial (`https://tangu.dev/tutorial`) Progressive step-by-step guide from installation and s-expressions to structs, traits, DSLs, coroutines, and tooling. ## Installation & first steps ### Installing Tangu Install the `tangu` CLI, Language Server (`tangu-lsp`), formatter (`tangu-format`), and standard libraries with the official installer script: ```sh curl -fsSL https://tangu.dev/install.sh | sh ``` Verify your installation and inspect the active toolchain paths: ```sh tangu --version tangu doctor ``` ### Hello, Tangu Create `hello.tan` and run it with `tangu run hello.tan` (or `tangu r hello.tan`): ```tangu (let language "Tangu") (say "Hello from ${language}!") ``` - `say` prints values followed by a newline (`echo` prints without a trailing newline). - Strings support inline `${...}` interpolation for any expression implementing `To-String`. - Line comments start with `;` (or `;;` for module headers). ## Primitives, literals & sized integers Tangu provides rich literal syntax for numbers, exact decimals, strings, characters, booleans, and symbols: ```tangu (let count 42) ; Int (64-bit signed integer) (let hex-mask 0xff_00) ; Hexadecimal Int literal (0b... binary, 0o... octal) (let ratio 3.14159) ; Float (64-bit IEEE 754) (let price 19.99d) ; Dec (128-bit exact fixed-point decimal for finance) (let is-active true) ; Bool (true or false) (let letter (Char "A")) ; Char (Unicode scalar value) (let status :ready) ; Key-Symbol (self-evaluating interned keyword) (let empty ()) ; None / unit value ``` ### Explicit sized integers When interoperating with binary protocols, SIMD, or databases, use sized integer literal suffixes or explicit constructors: - **Signed**: `I8`, `I16`, `I32`, `I64` (`Int`), `I128`, `ISize` - **Unsigned**: `U8` (`Byte`), `U16`, `U32`, `U64`, `U128`, `USize` ```tangu (let port 8005u16) (let byte-val 255u8) (let idx 1000usize) (let offset (I32 -128)) ``` ## Bindings, scope & mutability ### `def` vs `let` - Use **`def`** for top-level and mutually recursive function, struct, or constant declarations (hoisted within their scope). - Use **`let`** for sequential local bindings inside functions and scripts. ```tangu ; Always stack annotations (#pub, #inline, #test) vertically above (def ...) #pub #inline (def square (Func x (* x x))) (let result (square 12)) ``` ### Rebindable variables (`#var`) vs interior mutation (`#mut`) Bindings are immutable by default. Tangu distinguishes between **rebinding a variable** (`#var`) and **mutating a collection in place** (`#mut`): ```tangu ; #var allows reassigning the variable binding with <- or +<- (let #var total 0) (<- total 10) (+<- total 5) ; total is now 15 ; #mut allows mutating the contents of a collection or struct (let #mut items [1 2 3]) (push items 4) ; items is now [1 2 3 4] ``` ## Collections, key-paths & negative indexing ### Arrays, lists, maps, sets & ranges ```tangu (let nums [10 20 30 40]) ; Array (contiguous growable vector) (let quoted '(a b c)) ; List (s-expression linked list) (let tags (Set ["web" "db"])) ; Set (unique hashed values) (let r 0..10) ; Half-open Range (0 through 9) (let evens 0..=10|2) ; Inclusive Range with step 2 (0, 2, 4, 6, 8, 10) ``` Maps (`{...}`) accept `:key` symbols or string keys without commas, and support `...` map spreading and `{_ var}` punning: ```tangu (let host "127.0.0.1") (let port 8005) (let base-config {_ host _ port}) ; Punned keys {:host host :port port} (let dev-config {...base-config :debug true}) ; Spread base-config and override/add keys ``` ### Universal sequence operations All sequence types (`Array`, `List`, `String`, `Set`, `Map`, `Range`, `Slab`) share a single vocabulary in the prelude: ```tangu (count-of nums) ; => 4 (is-empty? nums) ; => false (contains? nums 20) ; => true (first-of nums) ; => 10 (last-of nums) ; => 40 (nth-of nums 2) ; => 30 (nums -1) ; => 40 (negative index from the end) (slice nums 1 -1) ; => [20 30] (reverse nums) ; => [40 30 20 10] ``` ### Required (`:`) vs optional (`?`) key-path navigation Navigate nested maps and structs concisely using `:` for required fields and `?` for nil-safe optional traversal: ```tangu (let payload {:user {:profile {:handle "gmosx"}}}) (let handle payload:user:profile:handle) ; => "gmosx" (errors if missing) (let bio (some-or payload?user?profile?bio "No bio yet")) ``` ## Control flow & pattern matching ### Strict boolean conditions (`if`, `unless`, `cond`) Conditions in Tangu require a strict `Bool` (`true` or `false`)—never rely on truthy/falsy coercion: ```tangu ; Multi-statement if with explicit (else ...) (if (not (is-empty? items)) (say "Processing items") (first-of items) (else (say "Queue is empty") () )) ; Flat multi-branch cond with _ default arm (let label (cond (== status :ok) "Healthy" (== status :degraded) "Warning" _ "Offline" )) ``` ### Structural pattern matching (`when`) Use `when` to match literals, runtime types, array destructuring (`[head ...tail]`), map keys (`{:role r}`), and `Error` values: ```tangu (def handle-response (Func resp (when resp {:status 200 :body b} "OK: ${b}" {:status 404} "Not found" [first ...rest] "List starting with ${first} (${(count-of rest)} more)" {:variant v :message msg} "Failed (${v}): ${msg}" _ "Unhandled response" ) )) ``` ### Loops (`for`, `for->seq`, `while`) Use `for` for side effects and `for->seq` to build an `Array` comprehension (using `(continue)` to skip elements): ```tangu ; Iterate over values in a sequence (for [name ["alpha" "beta"]] (say name) ) ; Comprehension producing [4 16 36] (let even-squares (for->seq [n 1..=6] (if (!= (% n 2) 0) (continue) ) (* n n) )) ``` ## Functions, implicit closures & pipelines ### Function parameter forms (`Func`) `Func` uses three canonical parameter shapes: 1. **Zero parameters**: `(Func () body)` 2. **Single parameter**: `(Func x (* x 2))` 3. **Multiple or typed parameters**: `(Func [#Int a #Int b] (+ a b))` (with optional signature annotation `#(Func [Int Int] Int)` stacked above `def`) ```tangu ; Rest parameters (...rest) and map destructuring (def format-tag (Func [{name tone} ...children] "${name}:${tone} (${(count-of children)})" )) ``` ### Implicit closures (`%0`, `%1`) & pipelines (`|>`) For concise higher-order transforms, `%0` (or `%`), `%1`, `%2` create an implicit closure automatically, and `|>` threads a value through expression chains via `%0`: ```tangu (let doubled (map [1 2 3 4] (* %0 2))) ; => [2 4 6 8] (let big (filter doubled (> %0 4))) ; => [6 8] ; Pipeline threading (let summary (|> " hello tangu world " (trim %0) (split %0 " ") (count-of %0) )) ; => 3 ``` ## Structs, validation constraints & traits ### Defining structs & field constraints Define nominal product types with `Struct`, optional `#(Or T)` fields, default values, and declarative validation constraints (`#{...}`): ```tangu #pub (def Account (Struct #Int #{:min 1} id #String #{:format :email} email #String #{:min-len 2 :max-len 32} handle #(Or String) bio (#String status "active") )) ``` Validate dynamic maps before constructing a `Struct` using `/validation`: ```tangu (use {validate} /validation) (let raw {:id 1 :email "dev@tangu.dev" :handle "gmosx"}) (let checked (validate raw Account)) ``` ### Pure copy-update vs in-place mutation ```tangu (let acc (Account {:id 1 :email "dev@tangu.dev" :handle "gmosx"})) ; Pure copy-update (returns a new Account with updated :bio) (let updated (Account acc {:bio "Systems programmer"})) ; In-place mutation on a #mut binding (let #mut mutable-acc (clone acc)) (<- mutable-acc:bio "Updated in place") ``` ### Deriving standard traits (`derive`) Prefer `(derive ...)` over manual boilerplate for standard traits: ```tangu (def Point (Struct #Int x #Int y)) (derive Point Eq Hash Ord Clone To-String Default To-JSON From-JSON) ``` ### Custom traits & implementations (`Trait` & `impl`) ```tangu (def Renderable (Trait #(Func This String) (render (Func this)) )) (impl Renderable Point (let render (Func self "(${self:x}, ${self:y})")) ) ``` ## Error handling (`Error`, `try`, `ok-or`, `some-or`) Tangu represents recoverable failures as first-class `Error` values rather than unchecked exceptions: ```tangu #(Func String (Or Int Error)) (def parse-port (Func raw (let n (try (Int raw) (else (Error :invalid-port "Port must be an integer: ${raw}") ))) (if (or (< n 1) (> n 65_535)) (return (Error :out-of-range "Port ${n} is outside 1..65_535")) ) n )) ; Local fallback for Error values with ok-or (let port (ok-or (parse-port "8005") 8000)) ; Local fallback for None () values with some-or (let host (some-or config?host "127.0.0.1")) ``` ## Modules, testing & tooling ### Directory-as-module & `use` imports In Tangu, **a directory is a module**: all `.tan` files in a directory merge into a single module namespace. Export public symbols with `#pub` stacked above `(def ...)` or `(let ...)`: ```tangu ; Sort imports alphabetically by module path: (use /fs) (use {strip-prefix strip-suffix} /string) (use {} @acme/ui/components/cards) (use {helper} ./utils) ``` ### Writing `#test` suites (`*.test.tan`) Place tests in `*.test.tan` files alongside your code or under `tests/` and run `tangu test`: ```tangu #test (def point-equality-and-update-works (Func () (let p1 (Point 10 20)) (let p2 (Point p1 {:x 99})) (assert-eq! p1:x 10) (assert-eq! p2:x 99) (assert! (!= p1 p2)) )) ``` ## DSLs at a glance (`#shtml`, `#css`, `#sql`) Tangu replaces external template engines and string concatenation with first-class reader tags inside ordinary functions: ```tangu (use {format-css} /repr/css) #pub (def (Func name #shtml [:article.tech-card [:h2 "Hello, ${name}"] [:p "Rendered directly from native SHTML nodes."] ] )) #pub (let card-css (format-css #css [ [".tech-card" { :border "1px solid var(--color-outline-variant)" :padding "20px" }] ])) ``` For full coverage of `.data.tan`, `.schema.tan`, `#shtml`, `#css`, `#svg`, and `#sql`, see the [Data, UI & SQL DSLs guide](/guides/dsls). ## Concurrency & Async (`/coro` & `/thread`) Use cooperative coroutines (`/coro`) for concurrent I/O and typed channels, or `/thread` for parallel CPU work across OS threads: ```tangu (use {await channel recv send spawn} /coro) (let ch (channel 8)) (let worker (spawn (Func () (send ch "task-complete") ))) (await worker) (let msg (try (recv ch))) (assert-eq! msg "task-complete") ``` ## Idiomatic style & toolchain workflow Before committing or shipping changes, run Tangu's fast verification pipeline from your project root: ```sh # 1. Static type check and import analysis tangu check app/ # 2. Apply safe autofixes, unambiguous (use ...) imports, and formatting tangu fix --changed --auto-import # 3. Inspect remaining lint warnings or format check in CI tangu lint app/ tangu format --check app/ # 4. Run #test suites tangu test ``` See the [CLI & editor reference](/cli) and [Lint rules](/lints) pages for every flag, subcommand, and suppression pragma (`; #allow(...)`). --- # Data, UI & SQL DSLs (`https://tangu.dev/guides/dsls`) Unify data manifests, validation schemas, SHTML templates, scoped stylesheets, SVG graphics, and parameterized SQL in one AST. Tangu extends uniform s-expression syntax across configuration manifests, schemas, HTML templates, CSS stylesheets, inline vector graphics, and parameterized SQL queries. Every dialect parses into a single AST representation with full editor, formatter, and lint support. ## Structured data (`.data.tan`) Use `.data.tan` for application configuration, package manifests (`manifest.data.tan`), localization catalogs, and static structured datasets. Data files restrict syntax to pure literals—maps, keyword symbols, arrays, strings, numbers, and booleans—with zero arbitrary code execution. ```data { :name "billing-api" :version "1.4.0" :server { :host "0.0.0.0" :port 8080 } :features [:metrics :rate-limit :structured-logs] } ``` Keys are commonly written as keyword symbols (`:port 8080`) or strings (`"Content-Type"`). When a key name matches a bound symbol or field shorthand, `_ value` expands cleanly inside maps. ## Schema validation (`.schema.tan`) Define reusable data contracts with `Struct` and field constraint metadata (`#{...}`), then verify `.data.tan` files directly from the CLI or validate runtime inputs with `/validation`: ```tangu #pub (def Service-Config (Struct #String #{:min-len 2 :max-len 64} name #Int #{:min 1 :max 65535} (#Int port 8080) #String #{:one-of ["dev" "staging" "prod"]} (#String env "dev") )) ``` Verify data files against a schema or generate conformant sample manifests from the CLI: ```sh tangu schema check config.schema.tan manifest.data.tan tangu schema sample config.schema.tan ``` ## HTML & SHTML templates (`#shtml`, `#html`) The `#shtml` (structured HTML) and `#html` reader tags construct native HTML node trees inside Tangu functions without external string-template engines. Text nodes are HTML-escaped by default; wrap trusted pre-rendered fragments in `[:!raw ...]` only when emitting sanitized HTML or SVG markup. ```tangu (use {parse-component-params} /web/app) #pub (def (Func [...params] (let [attrs content] (parse-component-params params)) (let title (some-or attrs:title "Service")) (let badge (some-or attrs:badge "ok")) #shtml [:article.tech-card {:data-state badge} [:header.flex.items-center.justify-between.gap-2 [:h3.type-title-m title] [:span.mod-tag badge] ] (unless (is-empty? content) [:div.mt-2 content] ) ] )) ``` Template rules and best practices: - **Class shorthand**: Chain utility classes directly on element tags (`[:div.flex.items-center.gap-2]`). Avoid decimal numbers in dot-shorthand (for example, prefer `.gap-2` or `{:class "..."}`). - **Comprehensions**: Use `(for->seq [item items] [:li item])` to project arrays directly inside element bodies without intermediate string buffers. - **Formatting**: Format `#html` and `#shtml` structures with `/repr/html` (`format-html`), or pass complete documents directly to `respond-html` in `/web/app`. ## Scoped stylesheets (`#css`) Write stylesheets using `#css` s-expression vectors combining CSS selectors, property maps, nested selectors (`&:hover`, `@media` blocks), and design tokens. Compile `#css` data directly through `/repr/css` (`format-css`), which supersedes the legacy `/dialect/css-expr` module. ```tangu (use {format-css} /repr/css) (let sheet #css [ [":root" { :--surface "#fbfcfe" :--ink "#0f172a" }] [".tech-card" { :background-color "var(--surface)" :color "var(--ink)" :border "1px solid currentColor" :padding "20px" } ["&:hover" {:transform "translateY(-1px)"}] ] ["@media (min-width: 840px)" {} [".tech-card" {:padding "24px"}] ] ]) (let css-text (format-css sheet)) ``` ## Inline vector graphics (`#svg`) Author theme-aware diagrams, icons, and illustrations with `#svg`. Because attributes are standard key-value maps, you can drive stroke, fill, and label typography from CSS custom properties (`var(--color-primary)`) so inline SVGs automatically switch between light and dark themes. ```tangu #pub (def (Func () #svg [:svg {:xmlns "http://www.w3.org/2000/svg" :width "24" :height "24" :viewBox "0 0 24 24" :aria-hidden "true"} [:rect {:x "2" :y "2" :width "20" :height "20" :fill "none" :stroke "var(--color-primary)" :stroke-width "2"}] [:circle {:cx "12" :cy "12" :r "4" :fill "var(--color-primary)"}] ] )) ``` ## Parameterized SQL (`#sql`) Tag SQL queries with `#sql` and bind parameters as positional arguments to `/postgres/client` or `/sqlite/client` rather than interpolating user input into query strings. ```tangu (use {await} /coro) (use {query-one-strong} /postgres/client) #pub (def insert-event (Func [pool #String kind #String payload] (await (query-one-strong pool #sql "INSERT INTO events (kind, payload) VALUES ($1, $2) RETURNING id, created_at" kind payload )) )) ``` Static analyzers validate balanced `#sql` strings and preserve syntax highlighting inside editors and documentation blocks. --- # Web apps & databases (`https://tangu.dev/guides/web-and-db`) Build full-stack HTTP/2 apps with routing, middleware, form validation, PostgreSQL primary/replica queries, and SQLite. Tangu ships a complete server stack in `@standard`: high-performance HTTP/1.1 & HTTP/2 serving (`/http/server`), composable routing and SSR/SPA helpers (`/web/app/*`), and native connection pools for both PostgreSQL (`/postgres/client`) and embedded SQLite (`/sqlite/client`). ## Request lifecycle & routing Compose handlers from small functions using `/web/app/handlers` (`chain-handlers`, `route-map`, `route-fs`, `route-graph`, `handle-html`, `handle-css`). ```tangu (use {respond-html respond-json read-json} /web/app) (use {chain-handlers handle-not-found route-map} /web/app/handlers) (use {cors-middleware security-headers-middleware} /web/app/middleware) (def handle-home (Func _req (respond-html #shtml [:html [:head [:title "My service"]] [:body [:h1 "Service online"]] ]) )) (def handle-health (Func _req (respond-json {:status "ok"}) )) (let app-routes (chain-handlers [ (route-map { "/" handle-home "/healthz" handle-health }) handle-not-found ])) #pub (let handler (|> app-routes (cors-middleware {:origins "*"} %0) (security-headers-middleware %0) )) ``` For multi-page websites, `construct-app-graph-from-fs` in `/web/app/graph` walks `app/resources/` to power breadcrumb trails (`get-trail`), XML/text sitemaps (`/web/app/graph/sitemap`), and OpenAPI 3.1 schemas (`/web/app/graph/openapi`). ## Middleware, forms & validation Use middlewares from `/web/app/middleware` to isolate cross-cutting concerns: - **Script collection (`scripts-middleware`)**: Tracks `(use-script "...")` calls from nested UI components and injects deduplicated `