Files
rosetta/src/Rosetta/model/usda/Parse.luau
T

797 lines
18 KiB
Luau

--!strict
-- model/usda/Parse: USD ASCII ("#usda 1.0") to prim specs, from the Sdf text grammar as Pixar's USD writes and reads
-- it; new code. .spline blocks and unknown constructs are skipped by bracket matching. Never throws.
local Parse = {}
export type Arr = { t: "arr", w: number, v: { number } } -- w numbers per element (tuples flattened)
export type Value = any
export type Prop = {
name: string,
rel: boolean,
typeName: string?,
array: boolean?,
uniform: boolean?,
custom: boolean?,
value: Value?, -- relationships: { path strings }
hasValue: boolean?,
samples: { times: { number }, values: { Value } }?,
connect: { string }?,
meta: { [string]: Value }?,
}
export type Prim = {
specifier: string,
typeName: string?,
name: string,
meta: { [string]: Value },
props: { [string]: Prop },
order: { string },
children: { Prim },
variantSets: { [string]: { [string]: Prim } }?,
}
export type Layer = { meta: { [string]: Value }, prims: { Prim } }
local NONE = table.freeze({ t = "none" })
Parse.NONE = NONE
local sfind, ssub, sbyte, smatch, gmatch = string.find, string.sub, string.byte, string.match, string.gmatch
local LISTOPS = { prepend = true, append = true, add = true, delete = true, reorder = true }
local VARIABILITY = { uniform = true, varying = true, config = true }
local MAX_DEPTH = 200
local function fail(msg: string, at: number): never
error({ usda = msg, at = at }, 0)
end
local function parser(s: string, maxBytes: number)
local n = #s
local depth = 0
local function ws(i: number): number
while true do
local _, e = sfind(s, "^[ \t\r\n]+", i)
if e then
i = e + 1
end
local c = sbyte(s, i)
if c == 35 then
local nl = sfind(s, "\n", i, true)
i = if nl then nl + 1 else n + 1
elseif c == 47 and sbyte(s, i + 1) == 47 then
local nl = sfind(s, "\n", i, true)
i = if nl then nl + 1 else n + 1
elseif c == 47 and sbyte(s, i + 1) == 42 then
local _, ce = sfind(s, "*/", i + 2, true)
if not ce then
fail("unterminated comment", i)
end
i = (ce :: number) + 1
else
return i
end
end
end
local function expect(i: number, ch: string): number
i = ws(i)
if ssub(s, i, i) ~= ch then
fail("expected '" .. ch .. "'", i)
end
return i + 1
end
local function ident(i: number): (string?, number)
local a, e = sfind(s, "^[%a_][%w_:]*", i)
if not a then
return nil, i
end
return ssub(s, a, e), (e :: number) + 1
end
local ESC = { n = "\n", t = "\t", r = "\r", ["\\"] = "\\", ['"'] = '"', ["'"] = "'", ["0"] = "\0", a = "\a", b = "\b", f = "\f", v = "\v" }
local function unescape(str: string): string
if not sfind(str, "\\", 1, true) then
return str
end
return (string.gsub(str, "\\(x?)(.)", function(x: string, c: string): string
if x == "x" then
return "\\x" .. c
end
return ESC[c] or c
end))
end
local function str(i: number): (string, number)
local q = ssub(s, i, i)
if ssub(s, i, i + 2) == q .. q .. q then
local e = sfind(s, q .. q .. q, i + 3, true)
if not e then
fail("unterminated string", i)
end
return unescape(ssub(s, i + 3, (e :: number) - 1)), (e :: number) + 3
end
local j = i + 1
while true do
local a = sfind(s, "[\\\n" .. q .. "]", j)
if not a then
fail("unterminated string", i)
end
local c = sbyte(s, a :: number)
if c == 92 then
j = (a :: number) + 2
elseif c == 10 then
fail("newline in string", a :: number)
else
return unescape(ssub(s, i + 1, (a :: number) - 1)), (a :: number) + 1
end
end
end
local function number(i: number): (number?, number)
local a, e = sfind(s, "^[-+]?%d*%.?%d*[eE][-+]?%d+", i)
if not a then
a, e = sfind(s, "^[-+]?%d*%.?%d*", i)
end
if a and (e :: number) >= (a :: number) then
local v = tonumber(ssub(s, a, e))
if v then
return v, (e :: number) + 1
end
end
local w, e2 = sfind(s, "^[-+]?%a+", i)
if w then
local word = string.lower(ssub(s, w, e2))
if word == "inf" or word == "+inf" then
return math.huge, (e2 :: number) + 1
elseif word == "-inf" then
return -math.huge, (e2 :: number) + 1
elseif word == "nan" or word == "-nan" or word == "+nan" then
return 0 / 0, (e2 :: number) + 1
end
end
return nil, i
end
local function skipBalanced(i: number): number
local open = sbyte(s, i)
local level = 0
while i <= n do
i = ws(i)
local c = sbyte(s, i)
if c == nil then
break
end
if c == 40 or c == 91 or c == 123 then
level += 1
i += 1
elseif c == 41 or c == 93 or c == 125 then
level -= 1
i += 1
if level == 0 then
return i
end
elseif c == 34 or c == 39 then
local _, j = str(i)
i = j
elseif c == 64 then
local e = sfind(s, "@", i + 1, true)
i = if e then e + 1 else n + 1
elseif c == 60 then
local e = sfind(s, ">", i + 1, true)
i = if e then e + 1 else n + 1
else
local _, e = sfind(s, "^[^%(%)%[%]{}\"'@<#/ \t\r\n]+", i)
i = if e then e + 1 else i + 1
end
end
fail("unbalanced " .. string.char(open or 63), i)
end
local value: (i: number) -> (Value, number)
local metadata: (i: number) -> ({ [string]: Value }, number)
local function list(i: number): (Value, number)
local close = sfind(s, "]", i + 1, true)
if close then
local body = ssub(s, i + 1, close - 1)
if not sfind(body, "[^%d%s%.,eE%-%+%(%)]") then
local first = smatch(body, "^%s*%(([^%)]*)%)")
local w = 1
if first then
w = 0
for _ in gmatch(first, "[^%s,]+") do
w += 1
end
elseif sfind(body, "[%(%)]") then
w = -1
end
if w > 0 then
local out: { number } = {}
local k = 0
local ok = true
for tok in gmatch(body, "[^%s,%(%)]+") do
local v = tonumber(tok)
if not v then
ok = false
break
end
k += 1
out[k] = v
end
if ok and k % w == 0 then
if k * 8 > maxBytes then
fail("array over the size limit", i)
end
return { t = "arr", w = w, v = out } :: Arr, close + 1
end
end
end
end
local items = {}
i += 1
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == "]" then
i += 1
break
elseif c == "" then
fail("unterminated list", i)
end
local v
v, i = value(i)
table.insert(items, v)
i = ws(i)
if ssub(s, i, i) == "(" then
local _
_, i = metadata(i)
i = ws(i)
end
c = ssub(s, i, i)
if c == "," then
i += 1
elseif c ~= "]" then
fail("expected ',' or ']' in a list", i)
end
end
local w: number? = nil
local flat: { number } = {}
for _, it in items do
if type(it) == "number" then
if w and w ~= 1 then
return { t = "list", v = items }, i
end
w = 1
table.insert(flat, it)
elseif type(it) == "table" and it.t == "tuple" then
local tw = #it.v
if (w and w ~= tw) or tw == 0 then
return { t = "list", v = items }, i
end
w = tw
for _, x in it.v do
if type(x) ~= "number" then
return { t = "list", v = items }, i
end
table.insert(flat, x)
end
else
return { t = "list", v = items }, i
end
end
if w == nil then
return { t = "list", v = items }, i
end
return { t = "arr", w = w, v = flat } :: Arr, i
end
local function tuple(i: number): (Value, number)
local items = {}
i += 1
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == ")" then
i += 1
break
elseif c == "" then
fail("unterminated tuple", i)
end
local v
v, i = value(i)
table.insert(items, v)
i = ws(i)
c = ssub(s, i, i)
if c == "," then
i += 1
elseif c ~= ")" then
fail("expected ',' or ')' in a tuple", i)
end
end
return { t = "tuple", v = items }, i
end
local function dict(i: number): (Value, number)
local out: { [string]: Value } = {}
i += 1
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == "}" then
i += 1
break
elseif c == "" then
fail("unterminated dictionary", i)
elseif c == ";" or c == "," then
i += 1
continue
end
local ty
ty, i = ident(i)
if not ty then
fail("expected a type in a dictionary", i)
end
i = ws(i)
if ssub(s, i, i + 1) == "[]" then
i += 2
end
i = ws(i)
local key: string?
c = ssub(s, i, i)
if c == '"' or c == "'" then
key, i = str(i)
else
key, i = ident(i)
end
if not key then
fail("expected a key in a dictionary", i)
end
i = expect(i, "=")
local v
v, i = value(i)
out[key :: string] = v
end
return { t = "dict", v = out }, i
end
function value(i: number): (Value, number)
depth += 1
if depth > MAX_DEPTH then
fail("nesting too deep", i)
end
i = ws(i)
local c = ssub(s, i, i)
local v: Value
if c == "[" then
v, i = list(i)
elseif c == "(" then
v, i = tuple(i)
elseif c == "{" then
v, i = dict(i)
elseif c == '"' or c == "'" then
v, i = str(i)
elseif c == "@" then
local path
if ssub(s, i, i + 2) == "@@@" then
local e = sfind(s, "@@@", i + 3, true)
if not e then
fail("unterminated asset path", i)
end
path, i = ssub(s, i + 3, (e :: number) - 1), (e :: number) + 3
else
local e = sfind(s, "@", i + 1, true)
if not e then
fail("unterminated asset path", i)
end
path, i = ssub(s, i + 1, (e :: number) - 1), (e :: number) + 1
end
local a: { [string]: any } = { t = "asset", v = path }
local j = ws(i)
if ssub(s, j, j) == "<" then
local e = sfind(s, ">", j + 1, true)
if not e then
fail("unterminated path", j)
end
a.path = ssub(s, j + 1, (e :: number) - 1)
i = (e :: number) + 1
end
v = a
elseif c == "<" then
local e = sfind(s, ">", i + 1, true)
if not e then
fail("unterminated path", i)
end
v, i = { t = "path", v = ssub(s, i + 1, (e :: number) - 1) }, (e :: number) + 1
else
local num, j = number(i)
if num ~= nil then
v, i = num, j
else
local id
id, j = ident(i)
if not id then
fail("expected a value", i)
end
i = j
if id == "None" then
v = NONE
elseif id == "true" then
v = true
elseif id == "false" then
v = false
else
v = { t = "id", v = id }
end
end
end
depth -= 1
return v, i
end
function metadata(i: number): ({ [string]: Value }, number)
local out: { [string]: Value } = {}
i = expect(i, "(")
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == ")" then
return out, i + 1
elseif c == "" then
fail("unterminated metadata", i)
elseif c == ";" or c == "," then
i += 1
continue
elseif c == '"' or c == "'" then
out.doc, i = str(i)
continue
end
local key
key, i = ident(i)
if not key then
fail("expected a metadata key", i)
end
local op: string? = nil
if LISTOPS[key] then
op = key
i = ws(i)
key, i = ident(i)
if not key then
fail("expected a metadata key", i)
end
end
i = ws(i)
if ssub(s, i, i) == "=" then
local v
v, i = value(i + 1)
if op == "delete" then
elseif op and op ~= "reorder" then
local prev = out[key :: string]
if type(prev) == "table" and prev.t == "list" and type(v) == "table" and v.t == "list" then
for _, x in v.v do
table.insert(prev.v, x)
end
else
out[key :: string] = v
end
else
out[key :: string] = v
end
end
end
end
local function samples(i: number): ({ times: { number }, values: { Value } }, number)
local times: { number }, values: { Value } = {}, {}
i = expect(i, "{")
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == "}" then
i += 1
break
elseif c == "" then
fail("unterminated time samples", i)
elseif c == "," then
i += 1
continue
end
local t
t, i = number(i)
if t == nil then
fail("expected a time code", i)
end
i = expect(i, ":")
local v
v, i = value(i)
table.insert(times, t :: number)
table.insert(values, v)
end
return { times = times, values = values }, i
end
local function targets(v: Value): { string }
local out = {}
if type(v) == "table" then
if v.t == "path" then
table.insert(out, v.v)
elseif v.t == "list" then
for _, x in v.v do
if type(x) == "table" and x.t == "path" then
table.insert(out, x.v)
end
end
end
end
return out
end
local primBody: (i: number, prim: Prim) -> number
local function newPrim(specifier: string, typeName: string?, name: string): Prim
return { specifier = specifier, typeName = typeName, name = name, meta = {}, props = {}, order = {}, children = {} }
end
-- def Type "name" ( meta ) { body }
local function prim(i: number, specifier: string): (Prim, number)
i = ws(i)
local typeName: string? = nil
local c = ssub(s, i, i)
if c ~= '"' and c ~= "'" then
typeName, i = ident(i)
if not typeName then
fail("expected a prim type or name", i)
end
i = ws(i)
while ssub(s, i, i) == "." do
local more
more, i = ident(i + 1)
typeName = (typeName :: string) .. "." .. (more or "")
end
i = ws(i)
end
c = ssub(s, i, i)
if c ~= '"' and c ~= "'" then
fail("expected a prim name", i)
end
local name
name, i = str(i)
local p = newPrim(specifier, typeName, name)
i = ws(i)
if ssub(s, i, i) == "(" then
p.meta, i = metadata(i)
end
i = expect(i, "{")
i = primBody(i, p)
return p, i
end
-- variantSet "name" = { "variant" ( meta ) { body } ... }
local function variantSet(i: number, p: Prim): number
i = ws(i)
local setName
setName, i = str(i)
i = expect(i, "=")
i = expect(i, "{")
local sets = p.variantSets or {}
p.variantSets = sets
local set = sets[setName] or {}
sets[setName] = set
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == "}" then
return i + 1
elseif c ~= '"' and c ~= "'" then
fail("expected a variant name", i)
end
local vname
vname, i = str(i)
local body = newPrim("def", nil, vname)
i = ws(i)
if ssub(s, i, i) == "(" then
body.meta, i = metadata(i)
end
i = expect(i, "{")
i = primBody(i, body)
set[vname] = body
end
end
-- [listop] [custom] [uniform|varying|config] (rel name | type[] name)[.connect|.timeSamples|...]
local function property(i: number, first: string, p: Prim): number
local word: string? = first
local op: string? = nil
if LISTOPS[word :: string] then
op = word
i = ws(i)
word, i = ident(i)
end
local custom, uniform = false, false
if word == "custom" then
custom = true
i = ws(i)
word, i = ident(i)
end
if word and VARIABILITY[word] then
uniform = word == "uniform"
i = ws(i)
word, i = ident(i)
end
if not word then
fail("expected a property", i)
end
local isRel = word == "rel"
local typeName: string? = nil
local array = false
if not isRel then
typeName = word
i = ws(i)
if ssub(s, i, i + 1) == "[]" then
array = true
i += 2
end
end
i = ws(i)
local name
name, i = ident(i)
if not name then
fail("expected a property name", i)
end
local suffix: string? = nil
if ssub(s, i, i) == "." then
suffix, i = ident(i + 1)
end
local prop = p.props[name :: string]
if not prop then
prop = { name = name :: string, rel = isRel } :: Prop
p.props[name :: string] = prop
table.insert(p.order, name :: string)
end
local pr = prop :: Prop
if typeName then
pr.typeName, pr.array = typeName, array
end
pr.uniform = pr.uniform or uniform or nil
pr.custom = pr.custom or custom or nil
i = ws(i)
if ssub(s, i, i) == "=" then
i = ws(i + 1)
if suffix == "timeSamples" then
pr.samples, i = samples(i)
elseif suffix == "spline" or (suffix ~= nil and suffix ~= "connect" and suffix ~= "default" and ssub(s, i, i) == "{") then
i = skipBalanced(i)
else
local v
v, i = value(i)
if op == "delete" then
elseif suffix == "connect" then
pr.connect = targets(v)
elseif isRel then
pr.value = targets(v)
pr.hasValue = true
else
pr.value = v
pr.hasValue = true
end
end
end
i = ws(i)
if ssub(s, i, i) == "(" then
local m
m, i = metadata(i)
if pr.meta then
for k, v in m do
(pr.meta :: any)[k] = v
end
else
pr.meta = m
end
end
return i
end
function primBody(i: number, p: Prim): number
depth += 1
if depth > MAX_DEPTH then
fail("nesting too deep", i)
end
while true do
i = ws(i)
local c = ssub(s, i, i)
if c == "}" then
depth -= 1
return i + 1
elseif c == "" then
fail("unterminated prim", i)
elseif c == ";" then
i += 1
continue
end
local word, j = ident(i)
if not word then
fail("unexpected character in a prim", i)
end
if word == "def" or word == "over" or word == "class" then
local child
child, i = prim(j, word)
table.insert(p.children, child)
elseif word == "variantSet" then
i = variantSet(j, p)
elseif word == "reorder" then
local k = ws(j)
local w2, k2 = ident(k)
if w2 == "nameChildren" or w2 == "properties" or w2 == "rootPrims" then
k2 = expect(k2, "=")
local _
_, i = value(k2)
else
i = property(j, word, p)
end
else
i = property(j, word, p)
end
end
end
local function layer(): Layer
local i = 1
if ssub(s, 1, 3) == "\239\187\191" then
i = 4
end
if ssub(s, i, i + 4) ~= "#usda" then
fail("not a USDA file (no #usda header)", i)
end
local nl = sfind(s, "\n", i, true)
i = if nl then nl + 1 else n + 1
local out: Layer = { meta = {}, prims = {} }
i = ws(i)
if ssub(s, i, i) == "(" then
out.meta, i = metadata(i)
end
while true do
i = ws(i)
if i > n then
break
end
local word, j = ident(i)
if word == "def" or word == "over" or word == "class" then
local p
p, i = prim(j, word)
table.insert(out.prims, p)
elseif word == "reorder" then
j = ws(j)
local _
_, j = ident(j)
j = expect(j, "=")
_, i = value(j)
elseif ssub(s, i, i) == ";" then
i += 1
else
fail("expected def / over / class", i)
end
end
return out
end
return layer
end
function Parse.layer(text: string, maxBytes: number?): (Layer?, string?, number?)
local run = parser(text, maxBytes or 2 ^ 30)
local ok, res = pcall(run)
if ok then
return res, nil, nil
end
if type(res) == "table" and (res :: any).usda then
return nil, (res :: any).usda, math.max(((res :: any).at or 1) - 1, 0)
end
return nil, "parse error: " .. tostring(res), nil
end
function Parse.version(text: string): string?
return smatch(text, "^\239?\187?\191?#usda%s+([%d%.]+)")
end
return Parse