Skip to content

Home › Development

Implementation Contracts ​

Reference: Luau 0.748, commit 3d91c9d5c280c95bfc4be63aac46012cf861d394. Runtime modules use relative require("./Module"), and entrypoints use @self to address child modules on both hosts. Require the root module (local Ouro = require("./ouro")). Public submodules (Ast, Profiles, Tokens, Kinds, Compiler, Bytecode, VM, PRESETS) load lazily on first access. Internal helpers (Lexer, Arena, State, Parser, RuntimeParser, TypeParser, Declarations, BytecodeBuilder, BytecodeDisassembler) stay decoupled from the root facade. Keep a cloned Roblox package instance alive until needed submodules have loaded. Only the VM folder loads its core helpers during require(VM) (while PatternMatch and Sandbox load lazily on first use). Source is portable --!strict Luau passing both old and new solvers.

Lexer (Lexer.luau) ​

Lexer.new(source, options) returns a private mutable context. :next() sets kind, start, finish, value, symbol, error and returns the numeric kind. Initial kind is EOF, and callers invoke :next() once to prime the stream. Spans are zero-based exclusive byte offsets. value is the identifier string, numeric value (nil if malformed), or decoded string (nil if invalid). symbol is the identifier's result-local symbol ID (0 for punctuation). :lookahead() returns (kind, value) without mutating public current-token fields. The lexer never allocates transient token tables. Symbols are stored in symbols and symbolMap. lineStarts = { 0, ... } tracks line offsets where each LF starts a new line. comments records { kind, start, finish }, and hotcomments records { header, content, start, finish }. When options.lossless is enabled, tape stores dense parallel arrays kinds, starts, finishes, count covering the entire source (including whitespace and comments, excluding zero-width EOF), with Token.Unparsed for any fatal tail. options.checkpoint is invoked at bounded work intervals (including inside long lexical tokens) and may return false to cancel via { parserSignal = "cancelled" }. There is no module-global mutable parser state.

Arena (Arena.luau) ​

Arena.new(symbols?, sourceBytes?, symbolMap?) creates a result-local arena. Public Arena types expose read-only tables and inspection methods (kind(id) -> number, kindName(id) -> string, listCount, listAt, listItems), while internal parser and compiler helpers also use listHasProp and construct nodes via :add(nodeRecord) -> NodeId (with numeric nodeRecord.kind tags from Arena.Kinds) and :list(values) -> ListId. Fields: nodes, parallel SoA arrays kinds, starts, and finishes, module flags hasTypeAnnotations and hasClasses, parallel listFirsts and listCounts, listValues, bindings, and symbols. A NodeId, ListId, or BindingId of 0 means absent. Binding records store name = symbolId, start, finish, annotation = NodeId, shadow = BindingId, functionDepth, loopDepth, scopeDepth, isConst, and isExported. Every parse result owns its arena, and published nodes and lists are never reused.

State (State.luau) ​

State.new(lexer, arena, options, scratch?) primes the lexer and initializes parser state (or :reset(...) when recycling a ParserContext scratch State). Fields kind, start, finish, value, symbol mirror the current token alongside previousStart and previousFinish. Methods: :advance(), :peek() -> (kind, value), :isName(text), :consume(kind) -> boolean, :expect(kind, context?), :expectClose(expected, opener, begin, search?, endMatch?), :expectName(context?) -> (symbol, start, finish), :symbolFor(text) -> SymbolId, :report(start, finish, message, code?), :node(record) -> NodeId, :list(values) -> ListId, :mark() -> number, :restore(mark), :bind(symbol, start, finish, annotation?, isConst?) -> BindingId, :lookup(symbol) -> BindingId, and :enter(context?) for recursion depth checks. State fields include source, arena, diagnostics, options, profile, functionDepth, loopDepth, blockDepth, vararg. :report suppresses duplicate locations and enforces the error limit via a structured signal. options.profile resolves to an immutable feature flag table.

Parser.luau injects state.parseType, state.parseTypePack, state.parseGenerics, state.parseTypeStatement, and state.parseTypeParams from TypeParser.luau, plus state.parseDeclaration and state.parseClass from Declarations.luau. It also injects state.parseExpression, state.parseFunction, and state.parseAttributes from RuntimeParser.luau.

RuntimeParser.luau ​

Exports parseChunk(state) -> NodeId, expression(state, limit?) -> NodeId, block(state, stopTokens?, scoped?) -> NodeId, functionBody(state, start, isMethod?, passedGenerics?, attrs?, debugname?, localName?, keywordFinish?) -> (NodeId, BindingId), attributes(state) -> ListId, and parseClassReference(state) -> NodeId. Type statements and declarations dispatch to the injected callbacks on state. Statement lists are stored as arena ListId values while preserving lexical scope, source spans, error recovery nodes, and semantic parser checks.

Profiles (Profiles.luau) ​

Profiles.resolve(nameOrTable?) resolves named profiles (upstream for official C++ bool defaults, studio for conservative shipping Studio grammar, and experimental with all ported grammar flags enabled) or validates and freezes a custom GrammarFlags table. Pass options.allowDeclarationSyntax = true to enable .d.luau definition parsing.

Parser.luau / Result ​

Exports parse, parseExpression, parseType, and newContext. Non-string sources and unknown ParseOptions keys (including internal lexer flags or compiler flags) throw validation errors. ParserContext:reset() swaps fresh scratch tables and advances an active generation counter so abandoned yielded coroutines cannot corrupt subsequent parses. ParseResult contains status, root, arena, source, diagnostics, lineStarts, comments, hotcomments, tape, profile, flags. status is "ok" | "syntaxError" | "limit" | "cancelled", with root = 0 when unavailable. Results provide kind, kindName, range, text, position, offset, formatDiagnostic, formatDiagnostics, childCount, childAt, forEachChild, visit, and reconstruct methods. forEachChild and visit traverse schema-ordered children without allocating per-node tables and throw on invalid callbacks, AstVisitor keys, or non-numeric node IDs. Ast.toTables(result) throws on invalid inputs and returns AstTable? (nil when root == 0), emitting lossless upstream-named tables (type, numeric start/finish, all parsed metadata, and false for absent unnamed entries). Diagnostics are { start, finish, message, code }.

Bytecode (BytecodeDefs, BytecodeBuilder, BytecodeCodec, BytecodeDisassembler) ​

BytecodeDefs.luau is generated from official Bytecode.h and Compiler.cpp by tools/generate.py (excluding experimental BytecodeGraph.cpp and Sccp.cpp). It exports Opcodes, opcodeNames, opLengths, isJumpD, isFastCall, isSkipC, Tags, Types, Builtins, Captures, ProtoFlags, FeedbackTypes, builtinNames, and CompilerFlags. BytecodeBuilder.luau constructs and serializes Luau bytecode (v14 by default, v100 for classes) including string tables, constant pools, protos, debug info, and typeinfo. It exposes new, newTableShape, ConstantType, kMaxConstantCount, kMaxClosureCount, kMaxTableShapeLength, getStringHash, getImportId, and DumpFlags (Code, Lines, Source, Locals, Remarks, Types, Constants). BytecodeDisassembler.luau exports standalone disassemble(input, dumpFlags?, source?, decoder?) -> (string?, string?) alongside builder dump helpers for disassembly, source remarks, and typeinfo, throwing on invalid caller arguments and returning (nil, err) on corrupt bytecode or malformed/metatable-tainted ProtoModule tables. BytecodeCodec.luau exports instruction decoders (insnOp, insnA, insnB, insnC, insnD, insnE), decomposeImportId, encodeError (requires string), decodeError, decodeLineInfo(proto) (requires table), serialize(protoModule, encoder?) -> (string?, string?), and deserialize(data, decoder?) -> (ProtoModule?, string?). Deserialization produces flat kTypes/kValues constants and compact lineData/linegaplog2. It validates constant references, child protos, debug indices, userdata indices, v11+/v12+ feedback/proto bounds, metatable cleanliness on ProtoModule tables, and EOF bounds. Because ProtoModule IR omits per-proto inline cost and feedback vectors, serialize encodes cost = 0 and an empty feedback vector. Ouro.Bytecode.verify(input, decoder?) delegates to VM/Verifier.verify and throws on invalid decoder arguments.

Compiler (Compiler.luau & Helper Modules) ​

Compiler.compile(sourceOrParseResult, compileOpts?) -> (string?, string?), Compiler.compileResult(sourceOrParseResult, compileOpts?), and Compiler.compileProto(sourceOrParseResult, compileOpts?) -> (ProtoModule?, string?) lower parsed arenas to Luau bytecode across optimization levels 0, 1, and 2, matching official Luau.Compiler. Compiling an existing ParseResult leaves parseResult.arena and lineStarts unmodified, preserving frozen and shared parse results. Compiler.CompilerFlags matches official Luau 0.748 defaults (LuauCompileCapturedCallTarget, LuauCompileLoopUnrollNegativeZero, and LuauCompileTableFoldFix default false) and omits dead upstream flags. CompileOptions.maxInstructions defaults to 2,000,000, and CompileOptions.allowDirectives defaults to true in low-level compile/load (explicitly false in "strict" and "balanced" sandboxes). Unknown CompileOptions keys, invalid option types/ranges, invalid compiler flag keys/values, and non-string/non-ParseResult inputs throw validation errors. Forward ParseOptions via compileOpts.parseOptions and custom binary opcode encoding via compileOpts.encoder (compileProto rejects encoder because ProtoModule IR always uses unencoded canonical opcodes). Six helper modules keep compiler responsibilities separate:

  • CompilerBuiltins.luau tracks mutable globals and resolves builtin fastcalls (CompilerTypes and CompilerFolding preserve GlobalState.Default per-global mutability checks, and libraryMemberTypeCb values must be integers in 0..255).
  • CompilerClass.luau emits class descriptors and lowers private field access.
  • CompilerExpr.luau lowers expressions, locals, calls, and tables, enforcing exact kMaxUpvalueCount bounds.
  • CompilerFolding.luau evaluates compile-time constants (Constant) and truthiness, cleaning scratch state via pcall if callbacks error.
  • CompilerInline.luau models inlining cost and argument bindings, matching upstream Luau 0.748 loop-unroll folding and change-stack semantics inside compileUnrolledFor.
  • CompilerTypes.luau encodes type info (LBC_TYPE_*), lowers vector constructors, and specializes typed locals using @native helpers, skipping annotation work when typeInfoLevel == 0 and arena.hasTypeAnnotations is false and releasing scratch buffers on callback errors.

VM (VM/init.luau, Sandbox, Verifier, RuntimeEnv, PatternMatch, Fastcalls, Dispatch, DispatchGuarded, HostEnv) ​

VM.run(chunk, options?, ...), VM.sandbox(options?), VM.PRESETS, VM.load(chunk, options?), VM.loadBytecode(bytecode, options?), VM.loadProto(protoModule, options?), VM.traceback(thread?, message?, level?), VM.resetBudget(fn), VM.createEnvironment(overrides?, options?), and VM.forkEnvironment(baseEnv?, overrides?) execute Luau bytecode (v3 through v14) in pure Luau and return an error tuple for experimental class bytecode (v100). VM/Sandbox.luau implements Ouro.run and the reusable Sandbox handle (:run, :load, :compile, :fork, :reset, :get, :set) over explicit frozen PRESETS (strict, balanced, trusted). It validates CompileOptions and libraries eagerly, routes argument-validation errors to the caller frame, inherits :set globals cleanly across :fork() without exposing guest writes, enforces explicit allowDirectives precedence, and clones read-only environments with fresh isolated PCG32 RNG state. Active guarded ModuleContext instances are tracked in a weak-key table across both :load() and :run() so :reset() resets surviving inner and global closures without retaining dead contexts. Low-level VM.load stays uncoupled: when options.env is omitted, it creates a fresh isolated VM.createEnvironment() without implicitly enabling DEFAULT_RESOURCE_LIMITS or rewriting compiler flags. Unnamed text chunks format debug names from source ([string "..."]), while binary bytecode and ProtoModule inputs default to "=chunk". Invalid chunk types, unknown option keys, bad option types/ranges, and mode = "text" with buffer or ProtoModule throw validation errors. VM/Verifier.luau validates proto headers (including metatable cleanliness and upvalues), operand/constant types, LOP_FASTPCALL targets, jump targets, capture trailers, and child-proto bounds before instantiation via a single-byte OP_VERIFY_META dispatch table and reusable scratch buffers. It freezes shared template tables, rejects v100 classes regardless of binary vs ProtoModule origin, and pre-seeds DUPTABLE templates with power-of-2 hash seeds (1..256 via cloneDuptableSeed). VM/init.luau caches templates only on deeply frozen ProtoModule inputs and snapshots mutable protos (code, constants, tables) on load. VM/RuntimeEnv.luau builds isolated environments, manages pooled call frames and synthetic C frames, and tracks active guest call counts per coroutine via weak-key activeThreads (unwinding dead threads automatically). It also computes O(min(|env|, 12)) per-root safeRootsMask fast paths and caches frozen ResourceLimits wrappers and fork metatables. It enforces opt-in ResourceLimits (maxStringLength, maxTableSize, maxBufferSize, maxPatternLength, maxPatternSteps, maxMemoryBytes) with pre-allocation bounds across stdlib calls (string.*, table.*, buffer.*, utf8.*, os.date, newproxy), rawget, next, table.unpack, table.remove, table.sort, xpcall, coroutine.create/wrap/resume, and stepImportChain. It formats guest stack traces (rejecting NaN levels in debug.traceback). Guest environments lock getmetatable("") to "The metatable is locked". Writable and forked environments lock their own metatables (__metatable = "locked"), whereas readOnly returns a flat frozen table (inheritHost = false) or a locked proxy (inheritHost = true). It provides collectgarbage("count" | "collect"), gives each environment, cloneReadOnlyEnv, and VM.forkEnvironment overlay a lazily seeded isolated 64-bit PCG32 math.random / math.randomseed state, and enforces cross-sandbox isolated getfenv, setfenv, debug.info, and debug.traceback across live and dead foreign coroutines. VM/PatternMatch.luau (lazy-required when ResourceLimits are active) implements a step-budgeted Luau 0.748 pattern matcher (string.find, match, gmatch, gsub) enforcing maxPatternLength, maxPatternSteps, streaming output maxStringLength, and cumulative maxMemoryBytes, while registering its chunk prefix so internal paths never leak into guest errors. VM/Fastcalls.luau executes built-in fastcalls (LBF_GETMETATABLE respects the locked string metatable; LBF_RAWGET wraps returned functions and respects ResourceLimits) and invalidates safeRootsMask when raw built-ins mutate the active environment. VM/Dispatch.luau and VM/DispatchGuarded.luau execute predecoded parallel instruction arrays (ops, argA..argD, auxVal, fcRa) through dual @native loops (runLoopFast when ctx.isGuarded is false, runLoopGuarded when limits, hooks, or ResourceLimits are active). Both loops reuse persistent per-depth frame.stack tables across calls at the same depth and maintain open/closed upvalues, varargs, fast iterator prep, and DUPTABLE templates. They enforce exact callLimit (activeCalls > callLimit) and default recursion/stack caps (LUAI_MAXCALLS = 20,000 frames and 1,000,000 active stack slots). timeout clocks start lazily on first call (VM.resetBudget clears startClock), and same-context pcall, xpcall, and coroutine.resume cannot swallow instructionLimit, timeout, interrupt, or maxMemoryBytes aborts (without duplicate onCall firing after recovery). Host call return values, custom for-in iterators (execForGLoopSlow), and __iter metamethods (execForGPrep) wrap extracted host functions and tables through wrapExtractedValue. Dispatch intercepts setGlobal across SETGLOBAL, SETTABLE, and SETTABLEKS, intercepts getGlobal across GETGLOBAL, GETIMPORT, and _G string lookups (GETTABLE/GETTABLEKS), reads meta.env directly after setfenv, validates LoadOptions in cloneFunction, and tightens resourceLimits element-wise when cloning across environments. VM/HostEnv.luau isolates host getfenv/setfenv calls outside Dispatch so @native and safeenv stay intact.