Skip to content

Home › Pipeline

Parsing & AST ​

Ouro.parse turns Luau source code into a flat numeric AST arena with zero-based half-open byte offsets ([start, finish)). When a chunk contains syntax errors, it emits structured diagnostics alongside a recovered tree so tooling can still inspect spans.

luau
--!strict
local Ouro = require("./ouro")

local parsed = Ouro.parse("local total: number = 20 + 22\nreturn total")

if parsed.status == "ok" then
	assert(parsed:kindName(parsed.root) == "AstStatBlock")
	assert(parsed:text(parsed.root) == parsed.source)
else
	print(parsed:formatDiagnostics())
end

All parser entrypoints validate arguments strictly and throw on non-string sources or unknown option keys.

text
Luau Source ──▶ Lexer (tokens + optional lossless tape)
                  │
                  ▼
                Parser (RuntimeParser / TypeParser / Declarations)
                  │
                  ▼
                ParseResult (flat SoA Arena + Diagnostics)
                  ├──▶ Tooling (:visit, :text, :reconstruct, :formatDiagnostics)
                  ├──▶ Ouro.Ast.toTables() (upstream-named Lua tables)
                  └──▶ Ouro.compile() (skip reparsing)

Slicing Node Text & Formatting Diagnostics ​

ParseResult provides built-in helpers so tooling does not need manual string.sub offset math or line-snippet formatting:

  • result:text(nodeId): Slices the exact source text covered by nodeId (converting the zero-based half-open [start, finish) span automatically).
  • result:formatDiagnostic(diag): Renders a single diagnostic with 1-based line:column coordinates, diagnostic code, source line, and caret underline.
  • result:formatDiagnostics(): Formats every diagnostic in result.diagnostics joined by blank lines (returns "" when there are no diagnostics).
luau
--!strict
local Ouro = require("./ouro")

local bad = Ouro.parse("local x = 1 +\nreturn x")
assert(bad.status == "syntaxError")

local report = bad:formatDiagnostics()
assert(string.find(report, "line 2, col 1", 1, true) ~= nil)
assert(string.find(report, "^^^^^^", 1, true) ~= nil)

Expressions, Types & Declarations ​

Use Ouro.parseExpression for standalone expressions, Ouro.parseType for standalone type annotations, and allowDeclarationSyntax = true for .d.luau definition files:

luau
--!strict
local Ouro = require("./ouro")

-- Fragment entrypoints accept a prefix by default; pass requireEOF = true for full strings
local expr = Ouro.parseExpression("a + b * 2", { requireEOF = true })
local ty = Ouro.parseType("{ [string]: number }", { requireEOF = true })
local decl = Ouro.parse("declare function ping(host: string): boolean", {
	allowDeclarationSyntax = true,
})

assert(expr.status == "ok" and ty.status == "ok" and decl.status == "ok")

Grammar Profiles ​

Built-in profile maps live in Ouro.Profiles. Pass a preset name or a custom GrammarFlags override table in ParseOptions.profile:

luau
--!strict
local Ouro = require("./ouro")

local studioResult = Ouro.parse("local value = 1", {
	profile = "studio",
})

-- Custom flags validate every key against known flags and merge onto "upstream" defaults
local customResult = Ouro.parse("local value = 1", {
	profile = { LuauSolverV2 = true },
})

assert(studioResult.status == "ok" and customResult.status == "ok")
ProfileBehavior
upstreamPinned official C++ 0.748 parser boolean defaults from UPSTREAM.json (default).
studioEnables shipping Studio flags (LuauSolverV2, LuauSingleTypeOptionalPackReturnsAttributeParens, and LuauAllowGlobalDeclarationToBeCalledClass) verified on Studio 0.748.0.7481526.
experimentalEnables every ported boolean grammar flag in src/Grammar.luau. Does not imply Studio support.

Lossless Reconstruction ​

Enable lossless = true to record a compact token and trivia tape (kinds, starts, finishes, count) alongside comments and --! hotcomments. Calling result:reconstruct() verifies contiguous coverage with zero gaps or overlaps. It returns the exact original bytes even on malformed inputs.

luau
--!strict
local Ouro = require("./ouro")

local source = "--!strict\n-- leading comment\nlocal x = 1 + 2\n"
local parsed = Ouro.parse(source, { lossless = true })

assert(parsed:reconstruct() == source)
assert(#parsed.hotcomments == 1 and #parsed.comments == 2)

If a parse aborts early due to a limit or cancellation, the tape appends a Token.Unparsed sentinel covering the remaining source tail, and lineStarts past the stop point computes on demand. Set captureComments = true when you only want comment spans without retaining the full lexical tape.

Walking the Arena ​

ParseResult stores tagged nodes alongside parallel Structure-of-Arrays metadata (kinds, starts, finishes), bindings, symbols, and flat child lists (listFirsts, listCounts, listValues). Traverse nodes in schema order without allocating tables, or materialize nested tables with Ouro.Ast.toTables:

luau
--!strict
local Ouro = require("./ouro")

local source = "local function add(a: number, b: number)\n\treturn a + b\nend"
local parsed = Ouro.parse(source)

local visited = 0
parsed:visit(function(nodeId, _kind, _depth)
	local start, finish = parsed:range(nodeId)
	local line, col = parsed:position(start)
	assert(line >= 0 and col >= 0 and finish >= start)
	visited += 1
	return true
end)
assert(visited > 0)

-- Inspect direct children of the root block without table allocation
local topLevel = 0
parsed:forEachChild(parsed.root, function(_childId)
	topLevel += 1
	return true
end)
assert(topLevel == 1)

-- Materialize conventional upstream-named Lua tables when needed
local rootTable = Ouro.Ast.toTables(parsed)
assert(rootTable ~= nil and rootTable.type == "AstStatBlock")

All spans and diagnostics keep zero-based half-open [start, finish) byte offsets for C++ Luau and LSP parity. result:position(offset) returns zero-based (line, column) byte coordinates (only LF \n advances line numbers), and result:offset(line, column) converts back to a byte offset. Node, list, symbol, and binding IDs (0 means absent) belong strictly to that ParseResult. Treat exposed arena tables as read-only.

visit accepts either a function (nodeId, kind, depth) -> boolean? or { enter?, leave? }. Returning false from enter (or the callback) skips descending into children while still invoking leave. Ast.toTables returns nil when result.root == 0 and uses false for absent unnamed argNames or paramNames slots.

Yielding Checkpoints & ParserContext ​

Ouro.newContext creates a reusable ParserContext (:parse, :parseExpression, :parseType, :reset(), busy) with pre-validated options and cooperative yielding lifecycle management. Each returned ParseResult still owns a fresh Arena, so ctx:parse and standalone Ouro.parse have similar median throughput (~1.0x). Reach for ParserContext when you want pre-validated shared options or explicit busy / reset() control around yielding checkpoints:

luau
--!strict
local Ouro = require("./ouro")

local steps = 0
local ctx = Ouro.newContext({
	profile = "studio",
	checkpointInterval = 4096,
	checkpoint = function(_offset)
		steps += 1
		-- Yield in Roblox frame budgets (e.g. task.wait) or return false to cancel
		return steps < 10_000
	end,
})

local first = ctx:parse("local a = 1")
local second = ctx:parse("local b = 2")
ctx:reset()
assert(first.status == "ok" and second.status == "ok" and not ctx.busy)

Contexts reject reentrant or overlapping calls while ctx.busy is true, though independent contexts can interleave across yielding checkpoints. Checkpoints also fire inside long strings and block comments (the lexer checks every checkpointInterval bytes and the parser checks every 256 token advances). Temporary scratch buffers larger than 256 KiB (262,144 bytes) release after completion so one huge script never pins memory. Errors thrown inside checkpoint propagate directly to the caller.

Parse Options & Statuses ​

ParseResult.status reports one of four outcomes:

  • "ok": Zero diagnostics (result.root holds the full AST).
  • "syntaxError": Recoverable syntax errors produced diagnostics alongside a recovered AST (result.root ~= 0).
  • "limit": Aborted by errorLimit, recursionLimit, or typeLengthLimit (result.root == 0).
  • "cancelled": checkpoint returned false (result.root == 0).
OptionDefault / Behavior
profile"upstream", "studio", "experimental", or a custom GrammarFlags table.
losslessfalse. Retains token/trivia tape for exact reconstruct() output and enables captureComments.
captureCommentsfalse (enabled automatically by lossless = true).
allowDeclarationSyntaxfalse. Enables .d.luau declare syntax.
requireEOFfalse on parseExpression and parseType; chunks always require EOF.
recursionLimit1,000 nested parser frames.
typeLengthLimit1,000 items in a type list or union/intersection chain.
errorLimit100 reported diagnostics before aborting with "limit".
noErrorLimitfalse. Disables errorLimit when true.
checkpointInterval4,096 scanned bytes between lexer checkpoint checks.
checkpoint(offset: number) -> boolean?. Return false to cancel, or yield to pause.