// docs
Documentation
Learn tape from the ground up — installation, language features, architecture, and API reference.
Getting Started
Download and set up the tape compiler.
Hello WorldYour first tape program — from source to executable.
ExamplesReal tape code examples — from hello world to components and error handling.
ProfilesTape's three strictness profiles: t0 (kernel), t1 (application), t2 (scripting).
Running CodeRun tape programs via the VM interpreter or compile to native executables.
CheatsheetQuick reference for all tape syntax, types, and features.
Language
Line comments, block comments, and nesting behavior.
Primitive TypesInteger, float, boolean, string, void, and color types.
StringsUTF-8 strings, interpolation, escape sequences, and the string/[]u8 boundary.
ConstantsCompile-time constant declarations evaluated before runtime.
Variables & TypesBindings, mutability, and the tape type system.
FunctionsFunction declarations, default parameters, methods, and extern/export.
Control FlowIf/else, while, for loops, match, break, continue, and return.
StructsComposite types with named fields, methods, and swizzle access.
EnumsNamed integer constants with optional description strings.
Error HandlingHow tape handles errors with T or Error — no exceptions, no hidden control flow.
Tagged UnionsDiscriminated unions with pattern matching — safe sum types.
OptionalsNullable values with ?T — safe absence without null pointer bugs.
Pointers & SlicesRaw pointers, const pointers, volatile pointers, non-null pointers, slices, and arrays.
Operators & ExpressionsArithmetic, comparison, logical, pipe, cast, and string interpolation.
Defer & ErrdeferScope-exit cleanup — run code when leaving a scope, regardless of how.
Type AliasesCreate named aliases for complex types.
Platform-Specific CodePlatform abstraction via runtime libraries and @link directives.
Build Settings@setting consts a build sets with --set: one source, a dev build and a release.
AttributesUser-defined and built-in attributes for metadata and compiler directives.
refactor() BlocksVirtual module boundaries for safe, compiler-validated code extraction.
ComponentsComponent declaration syntax and keywords.
Vectors128-bit integer vectors (u8x16 .. i64x2): lane-wise arithmetic you write out by hand.
CoroutinesFunctions that stop part way and go on later: co fn, yield, resume. Their state is a plain value.
Components
Tape's first-class component model — props, state, events, dispatch, and views.
Props & StateComponent inputs (props), reactive state (var), and interaction flags (state).
EventsTyped single-handler events — no closures, no listener lists.
Views & SlotsDeclarative view trees, conditional rendering, list rendering, and slots.
Lifecycle & RenderingComponent mount hooks, paint dispatch, and the rendering pipeline.
Component ConstraintsPolymorphic component types via dispatch-based structural constraints.
Memory
Modules
Module system, import syntax, visibility, and resolution.
Linking & FFINative library interop, extern functions, @export, @link, and output formats.
Profile Import RulesWhich profiles can import which — and what happens at the boundary.
Shared tape librariesBuild a module once as a shared library and load it from programs, keeping its whole tape interface.
Concurrency
Metaprogramming
@tape blocks replace generics — execute arbitrary code at compile time.
@emit & Code GenerationInject declarations and bindings at compile time using @emit.
Compile-Time Reflection@typeof, @sizeof, @has_field, @has_method — inspect types, methods, functions and components at compile time.
@embed & Static DataEmbed files and compute constants at compile time.
Refactoring with Virtual ModulesCompiler-validated code extraction using refactor() blocks and tape refactor.
Regions
Sub-languages within .tape files — #code, #view, #style, #test, and more.
#code RegionThe default region — standard tape logic, functions, variables, imports.
#view RegionVisual component declarations — tree syntax, props, slots, and events.
#style RegionSet component props by rule: selectors by component name, nested selectors, constants and imported styles, all resolved at compile time.
#shader RegionVertex, pixel, compute, task and mesh shaders written in tape, checked with the program and compiled to SPIR-V, GLSL and Metal at compile time for the gpu module.
#test RegionInline test cases — compiled only during tape test.
#bytecode Regionx86-64 instructions in tape functions, for t0 kernel code: port I/O, control registers, descriptor tables, MSRs.
#localization RegionTranslatable strings with compile-time verification.
#resource RegionEmbedded assets — icons, images, fonts, sounds, and binary data.
Architecture
Compiler pipeline from source to binary — scanner, parser, TAC IR, backends.
TAC IRThree-address code intermediate representation — opcodes, registers, and basic blocks.
VM BackendTAC interpreter — direct execution without bytecode encoding.
Native Backendx86-64 and ARM64 code generation — register strategy, instruction encoding, binary emission.
EmbeddingHow a tape program runs scripts with tape's own VM: the tapevm100 library, contexts and instances, host calls, time slicing, and what a script can and cannot do.
CLI
Compile tape source to a native executable or library.
tape runExecute tape source via the VM interpreter.
tape replInteractive read-eval-print loop for exploring the language.
tape testRun #test regions (a file, or every test file under a directory) in the VM and as native code, and check that both agree.
tape checkType-check source without compiling or running.
Debug Toolstape tokens, tape ast, tape deps, tape disasm — inspect compiler internals.
tape refactorMaterialize refactor() virtual module blocks into actual files.
tape setupPut tape on your PATH, so it runs from any terminal.
Standard Library
What the standard library contains, how its modules are organized, and the conventions they share.
arenaBump allocation over memory you already own: alloc, reset, mark and release, plus alignment helpers.
bitsBit counting, rotation, byte swapping, and reading and writing integers in little- or big-endian byte order.
convParse numbers from text and format numbers into buffers, exactly: integers in any radix, floats with correct rounding and shortest round-trip output.
asciiClassify bytes as digits, letters or whitespace, change their case, and read digit values.
mathInteger helpers and the floating-point library: rounding, roots, trigonometry, exponentials, logarithms and pow, interpolation and angle helpers, for f64 and f32.
bytesCopy, fill, compare, search, trim, split and cut byte views without allocating.
memHeap memory: alloc and realloc with out-of-memory as an error, alloc_or_trap, free, heap arenas, raw byte operations and leak checking.
strBuild new strings: join, repeat, replace, case mapping, padding, and a growable Builder.
cstrNUL-terminated C strings at the C boundary: view them as []const u8, make them from text, free them.
fmtFormat numbers the way interpolation can't: hex, binary, fixed decimals, byte sizes. As strings or into your own buffer.
pathJoin, split and normalize file paths as text, with the separator rules of the target platform.
ioConsole output and input, byte streams over files, pipes and sockets, buffered reading and writing, and IoError.
fsRead and write files, create and remove directories, list them, read file metadata, set permissions and owners, and ask how much space is free.
osCommand-line arguments, environment variables, exit, the working directory, host and user names, signals, the platform and OS entropy.
utf8Decode, encode, validate, count and iterate the code points of UTF-8 text.
timeMeasure elapsed time, sleep, time a game's frames, read the wall clock as dates, show times in the user's zone, format them, and read and write mail dates.
calendarDate arithmetic without a clock: days since 1970 of a date, leap years, month lengths, fixed-width digits.
logLeveled log messages with UTC timestamps, to stderr or wherever you send them.
cliCommand-line options and arguments from a declarative spec, with usage text and error messages.
hashNon-cryptographic hashes: FNV-1a, wyhash, CRC-32 and an integer mixer for hash maps.
collectionsVectors, hash maps (also in insertion order) and sets, deques, heaps, pools of generational handles, sparse sets and bit sets, for any element type, strings and structs included.
fixedContainers without a heap: fixed-capacity vectors, ring buffers, hash maps, handle pools and sparse sets stored inline, and an intrusive linked list, for t0 and kernel code.
sortSorting and binary search for slices of any type: stable and unstable sorts, is_sorted, binary_search, lower and upper bounds.
geomShapes and intersection tests for games: boxes, circles, rays, segments, planes, triangles, polygons, minimum translation, swept boxes, convex hulls, triangulation, a grid hash and a quadtree.
polygonAreas with holes: outlines added and taken away (union, subtract, intersect, xor) with shared edges and touching corners handled exactly, and triangles over a region with holes.
randSeedable random number generators: xoshiro256** and PCG32, unbiased ranges, floats, normal deviates, weighted picks, points on circles and spheres, shuffle and choice.
noiseSeeded coherent noise for procedural content: Perlin, simplex, value and Worley noise, fractal sums, and Poisson-disk point sampling.
gfxDrawing on a pixel surface: rectangles, shapes, text, blits, clipping, and reading pixels back.
jsonParse, query, build and print JSON, with exact numbers and errors that say where; or stream it token by token without allocating.
xmlRead XML documents into a tree, with errors that say where or a lenient read that keeps what it can; walk it, read attributes and text; build a tree by hand.
colorBuilding, taking apart and mixing color values: rgb, channels, lighten, darken, lerp, brightness.
encodingbase64, base64url, hex and percent-encoding, both ways: as strings or into your own buffer, with strict decoding.
serialMark a struct once, save it in any format: skip, rename and opt-in fields that every serialization format reads the same way.
hotHot reload's safe point: swap in edited components and functions while the program runs.
imageDecoding PNG, JPEG, WebP, BMP, TGA, HV3 and HV4 into surfaces and encoding surfaces as PNG, BMP, TGA, HV3 or HV4.
protobufProtocol buffers' binary format: your structs to and from the bytes gRPC and every protobuf library speak, by field number.
textureGPU texture files: DDS and KTX2 read into levels, layers and faces; BC1 to BC7 decoded to RGBA8, f32 or a surface.
gltfglTF 2.0 models and scenes: .gltf and .glb read and checked, vertex data into your arrays, node transforms, skins, animations sampled, PBR materials.
uiShowing component trees in a window or offscreen: layout, painting, input, and headless testing.
uuidUUIDs by RFC 9562: random v4 and time-ordered v7, parse and format, version and variant, ordering, and use as map keys.
widgetsReady-made components for real windows: layout, text fields and editors, buttons and switches, lists, sidebars, grids, tables, pictures, settings pages and dialogs.
localeThe active locale for @t strings: from the environment or set by the program, with fallbacks.
lookHow the widgets are drawn: one function per control, in the active theme's colors, on any pixels you hand it.
themeThe look of ui and widgets: the light and dark palettes, switching at run time, and the palette as #style constants.
processStart other programs with exact arguments, send their output to files or read it through pipes, wait with a timeout, kill them and read the exit status.
cryptoCryptography checked for constant time: SHA-256/384/512, BLAKE2b, HMAC, HKDF, PBKDF2, Argon2, ChaCha20-Poly1305, AES-GCM, X25519, P-256, Ed25519, signatures and a CSPRNG.
netTCP and UDP sockets, name resolution, the network interfaces and their addresses, connecting to a host with Happy Eyeballs, readiness polling, pollers and wakers, TCP streams as io streams, TLS connections both ways, trust sets and server certificates.
x509X.509 certificates for TLS: a strict DER reader, certificate fields, private keys, host name matching, a trust store and chain validation.
ca_rootstape's bundled root certificates: Mozilla's CA set for TLS server authentication, compiled into the program, the same on every platform.
httpAn HTTP client over http and https: requests with any method, headers and a body, whole responses in memory, opt-in redirects, timeouts and size limits; a Client keeps connections and runs many requests at once, over HTTP/2 where the server offers it. And both sides of HTTP/1.1 as engines over bytes that your own loop drives.
tlsTLS 1.3 client and server as sans-I/O engines: you move the bytes, they do the protocol, with certificate checks through x509, certificates chosen by server name, ALPN, KeyUpdate and leaf pinning.
websocketWebSocket clients and servers over ws:// and wss://: connect and accept, text and binary messages, fragments, ping/pong, the close handshake, permessage-deflate. Poll each frame from a game loop or wait with recv; or drive the frame engine yourself over any transport.
dbusD-Bus for the Linux desktop, written in tape: the session and system buses, method calls blocking or answered later, signals by match rule, exported objects with properties and introspection; the wire format and the connection as state machines over bytes.
urlURLs as browsers read them (the WHATWG URL Standard): parse, resolve a link against a base, read the parts, the origin, percent-encoding, Punycode.
regexRegular expressions over UTF-8 text, matched in linear time: compile, find, captures, matches, split, replace.
charsetText in other encodings decoded to UTF-8: windows-1252, ISO-8859, KOI8, Shift_JIS, GBK, Big5, EUC-KR, UTF-16, UTF-7 and IMAP mailbox names.
unicodeUnicode text by Unicode's rules: character properties, case mapping and folding, normalization, grapheme, word and sentence boundaries, and collation (sorting).
mimeEmail messages read and written: parts, headers, encoded words, addresses, attachments, charsets, flowed text.
filetypeMedia (MIME) types from file names and file contents, and the usual extension of a type: the same answer on every machine.
audioPlay sound: streams you write samples into as you make them, clips played once, and WAV files read into sounds. Record it from the microphone, with a level meter.
gamepadGamepads for games: one layout on every platform, read once a frame, with deadzones, edges, stable slots and rumble.
mixerA software audio mixer: voices over decoded sounds and refillable streams, gain, pan, pitch, fades, buses, distance and a limiter, written into your buffer.
secretsSmall secrets the system keeps for this user: a database key, an account token. The Credential Manager on Windows, the Keychain on macOS.
notifyThe system's notifications: show a note, withdraw it by id or tag, the user's clicks as ui events, and an unread badge.
dialogThe system's file dialogs: open a file, files or a folder, choose where to save, with filters, modal over your window.
wavRead WAV files: their rate, channels and length, and their samples as 16-bit integers into your own buffer; write a 16-bit WAV file or a header.
affine2D affine transforms: translate, scale, rotate, skew, compose, invert and apply, in CSS's matrix order.
pipeByte streams between programs on one machine: listen on a name, accept and connect with timeouts, read lines with a timeout.
math3dVectors, matrices and quaternions in f32: transforms, cameras, inverses, slerp; the types games and #shader code share.
fixedpointFixed-point numbers for lockstep games and replays: the same bits on every machine, with operators, square root, trigonometry, text and 2D/3D vectors.
desktopOther programs' windows and the screens: find a window by title or process, place it, keep it on top, ask it to close; screen bounds, work areas and DPI.
text, font, fillTrueType text on pixels: open a font, draw and measure anti-aliased UTF-8 with kerning at any size; the outline filler underneath.
colorfont, shapeColour emoji: COLR v0 and v1, CBDT and sbix glyphs as pixels, and emoji sequences (ZWJ families, skin tones, flags, keycaps) shaped into the glyphs their fonts draw.
pngPNG images decoded in tape into your buffer, without the image library: every colour type and depth, all filters, transparency; not interlaced.
drawVector paths on pixels without allocating: SVG path data, fills, round-capped strokes, solid and gradient paint through clip masks, blur.
svgSVG images and icons drawn at any size onto a gfx surface, the same surface a PNG decodes to: shapes, paths, gradients, clips, masks, markers, text, style sheets.
barcodeQR codes, Data Matrix, Aztec, PDF417 and 1D barcodes made from data and drawn: as a picture or an SVG document, in your colours, with round modules, styled eyes and a logo.
wordsWord lookup tables: a fixed list of words becomes an enum and a lookup built at compile time.
forwardForwarding methods: a type that holds another in a field gets its methods, generated at compile time.
hpackHPACK, HTTP/2's header compression: decode header blocks with their dynamic table, encode fields, Huffman both ways.
h2HTTP/2 connections as a state machine over bytes, client and server: streams, frames, flow control, trailers, GOAWAY, PING; what http and grpc run over.
grpcgRPC over HTTP/2 as a state machine over bytes, client and server: unary calls and streams, metadata, timeouts, statuses.
vmRun scripts inside your program: execution contexts that decide what a script may use, host modules it calls, instances time-sliced frame by frame, errors as data.
glOpenGL from tape: a window with a GL context, its events as ui's, shaders compiled with the driver's log as an error, and the GL functions under their Khronos names.
syncState that worker threads change together: a mutex, a condition variable, a read-write lock, a guarded value that is reached only through its lock, an atomic counter, and bytes shared by reference count.
gpuThe GPU on every platform: a window or an offscreen device, buffers, textures, render and compute pipelines from #shader stages, passes in program order, results read back.
tween and easingValues that move over time: tweens through points with an easing curve per leg, the easing curves, and animating ui components.
curveCurves for games and animation: Bézier, Hermite, Catmull-Rom and B-spline segments, arc length for constant speed, keyframe tracks and sprite-sheet frames.
compressDeflate, zlib and gzip: compress and decompress whole buffers or streams of any size, strictly checked.
pgA PostgreSQL client as a state machine over bytes: SCRAM-SHA-256 and MD5 logins, simple and extended queries, $n parameters as typed values, decoded rows, errors with every field, LISTEN/NOTIFY.
brotliBrotli: compress and decompress Content-Encoding: br bodies and .br files, whole or as a stream, strictly checked.
zstdZstandard: decompress .zst files, zstd-encoded responses and KTX2 supercompressed textures, strictly checked.
lzThe parts of an LZ77 compressor with Huffman codes: length-limited codes, a bit writer, a bit reader with rewind, hash-chain matching.
bitreadReading bits highest first, as media formats store them: peek, a Reader that marks reading past the end, and ErrMsg for a codec's error text.
h264H.264: a parser that gives every picture's parameters for a hardware decoder, and a bit-exact software decoder.
mp4An MP4 demuxer (tracks with their codec configuration, samples with their times, progressive and fragmented files, seeking) and an .m4a writer for one AAC track.
yuv4:2:0 video frames (I420, NV12) to RGB surfaces, scaled, with the stream's colour matrix and range.
aacAAC-LC audio decoded to f32 samples (the AudioSpecificConfig, ADTS frames and an MP4's raw frames) and encoded from them, mono and stereo.
oggOgg pages read and checked, and a logical stream's packets put back together: what Vorbis (and Opus) audio comes in.
vorbisOgg Vorbis audio decoded to f32 samples: whole files, music streamed from memory with seeking and loop tags, or packet by packet.
videoVideo files read and decoded: an MP4's H.264 frames onto surfaces and its AAC sound as samples, with seeking.
intlNumbers, prices, dates, lists and plurals as each language writes them (CLDR's data for 33 locales), and time zones by name with their offsets.
navPathfinding: A* and breadth-first search on grids and graphs, distance fields that steer a whole horde, a reusable search state that doesn't allocate.
keystoreP-256 keys the system keeps and never exports: made once under a name in the TPM or the Secure Enclave, found again by it, used to sign and to agree.
trayA status icon with a menu: in the notification area on Windows, the menu bar on macOS; clicks and menu choices come in the ui loop.
launchHow the program is started and what it is handed: one running instance, the arguments later ones hand over, a URL scheme of its own, links opened in the browser.