wgsl-reflect/src/parser/literal.js
2025-04-17 12:06:54 -05:00

144 lines
2 KiB
JavaScript

import { any, anyOf, digit, many, maybe, seq, str } from 'kuebiko'
const iu = anyOf('iu')
const decimal = char('.')
const sign = anyOf('+-')
const e = anyOf('eE')
const p = anyOf('pP')
const fh = anyOf('fh')
export const zero = char('0')
export const digits = many(digit)
export const booleanLiteral = any(str('true'), str('false'))
export const decimalIntLiteral = any(
zero,
seq(
not(zero),
digits,
maybe(iu)
)
)
const hexDigit = any(digit, anyOf('abcdef'), anyOf('ABCDEF'))
const hexPrefix = seq(zero, anyOf('xX'))
const hexIntLiteral = seq(
hexPrefix,
hexDigit,
maybe(iu)
)
export const integerLiteral = any(
decimalIntLiteral,
hexIntLiteral
)
const nonzeroDigit = anyOf('123456789')
const many1 = parser => seq(parser, many(parser))
const exponent = seq(
e,
sign,
many1(digit)
)
const fhDecimalFloatLiteral = seq(
any(
zero,
seq(
nonzeroDigit,
digits
)
),
fh
)
const eDecimalFloatLiteral = seq(
digits,
exponent,
fh
)
const cDecimalFloatLiteral = seq(
any(
seq(
digits,
decimal,
many1(digit)
),
seq(
many1(digit),
decimal,
digits
)
),
maybe(seq(exponent, fh)),
)
const decimalFloatLiteral = any(
fhDecimalFloatLiteral,
eDecimalFloatLiteral,
cDecimalFloatLiteral
)
const sHexFloatLiteral = seq(
hexPrefix,
any(
seq(
many(hexDigit),
decimal,
many1(hexDigit)
),
seq(
many1(hexDigit),
decimal,
many(hexDigit)
)
),
maybe(
seq(
p,
maybe(sign),
many1(digit),
fh
)
)
)
const zHexFloatLiteral = seq(
hexPrefix,
many1(hexDigit),
p,
maybe(sign),
many1(digit),
maybe(fh)
)
const hexFloatLiteral = any(
sHexFloatLiteral,
zHexFloatLiteral
)
export const floatingPointLiteral = any(
decimalFloatLiteral,
hexFloatLiteral
)
export const numericLiteral = any(
integerLiteral,
floatingPointLiteral
)
export const literal = any(
numericLiteral,
booleanLiteral
)