Files
Lyrebird/Sources/LyrebirdGraphDSL/DSLParser.swift
T

254 lines
9.6 KiB
Swift

// DSLParser.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Recursive-descent parser producing a `DSLProgram` from a token stream.
//
// Grammar (v1):
// program = { line }
// line = [ statement ] newline
// statement = ( ident "=" expr ) | expr
// expr = term { ("+"|"-") term }
// term = factor { ("*"|"/") factor }
// factor = "-" factor | number | call | "(" expr ")"
// call = ident "(" [ args ] ")"
// args = arg { "," arg }
// arg = [ ident ":" ] expr
/// Parses DSL tokens into a ``DSLProgram``.
public struct DSLParser {
private let tokens: [DSLToken]
private var pos: Int = 0
/// Recursion-depth ceiling — pathological or generated input (deeply nested
/// parens / calls) throws instead of overflowing the stack and crashing the
/// host process.
private static let maxDepth: Int = 128
public init(tokens: [DSLToken]) {
self.tokens = tokens
}
/// Lex + parse `source` in one step.
public static func parse(_ source: String) throws -> DSLProgram {
var parser: DSLParser = DSLParser(tokens: try DSLLexer.tokenize(source))
return try parser.parseProgram()
}
// MARK: - Cursor
private var current: DSLToken { tokens[pos] }
@discardableResult
private mutating func advance() -> DSLToken {
let t: DSLToken = tokens[pos]
if pos < tokens.count - 1 { pos += 1 }
return t
}
private func check(_ kind: DSLToken.Kind) -> Bool { current.kind == kind }
@discardableResult
private mutating func match(_ kind: DSLToken.Kind) -> Bool {
if check(kind) { advance(); return true }
return false
}
private mutating func expect(_ kind: DSLToken.Kind, _ label: String) throws -> DSLToken {
guard check(kind) else {
throw DSLParseError(kind: .expected(label, found: describe(current)),
span: current.span)
}
return advance()
}
private func describe(_ token: DSLToken) -> String {
switch token.kind {
case .eof: return "end of input"
case .newline: return "end of line"
case .identifier, .number: return "'\(token.text)'"
default: return "'\(punctText(token.kind))'"
}
}
private func punctText(_ kind: DSLToken.Kind) -> String {
switch kind {
case .leftParen: return "("
case .rightParen: return ")"
case .comma: return ","
case .colon: return ":"
case .dot: return "."
case .equals: return "="
case .plus: return "+"
case .minus: return "-"
case .star: return "*"
case .slash: return "/"
default: return "?"
}
}
// MARK: - Grammar
private mutating func parseProgram() throws -> DSLProgram {
var statements: [DSLProgram.Statement] = []
while !check(.eof) {
// Skip blank separators.
if match(.newline) { continue }
statements.append(try parseStatement())
// Statement must end at a newline or eof.
if !check(.eof) {
_ = try expect(.newline, "end of line")
}
}
return DSLProgram(statements: statements)
}
private mutating func parseStatement() throws -> DSLProgram.Statement {
// `ident =` → assignment; else an expression.
if check(.identifier), tokens[pos + 1].kind == .equals {
let name: DSLToken = advance()
advance() // '='
let value: DSLExpr = try parseExpr(depth: 0)
return .assignment(name: name.text, value: value,
DSLSpan(start: name.span.start, end: value.span.end))
}
return .expression(try parseExpr(depth: 0))
}
private mutating func parseExpr(depth: Int) throws -> DSLExpr {
guard depth <= DSLParser.maxDepth else {
throw DSLParseError(kind: .tooDeeplyNested, span: current.span)
}
var lhs: DSLExpr = try parseTerm(depth: depth)
while check(.plus) || check(.minus) {
let op: DSLExpr.BinaryOp = check(.plus) ? .add : .subtract
advance()
let rhs: DSLExpr = try parseTerm(depth: depth)
lhs = Self.fold(op, lhs, rhs)
}
return lhs
}
private mutating func parseTerm(depth: Int) throws -> DSLExpr {
var lhs: DSLExpr = try parseFactor(depth: depth)
while check(.star) || check(.slash) {
let op: DSLExpr.BinaryOp = check(.star) ? .multiply : .divide
advance()
let rhs: DSLExpr = try parseFactor(depth: depth)
lhs = Self.fold(op, lhs, rhs)
}
return lhs
}
private mutating func parseFactor(depth: Int) throws -> DSLExpr {
guard depth <= DSLParser.maxDepth else {
throw DSLParseError(kind: .tooDeeplyNested, span: current.span)
}
// Unary minus — folded into a negative literal when the operand is a
// number, so numeric-literal-only parameters accept `-0.5`.
if check(.minus) {
let minus: DSLToken = advance()
let operand: DSLExpr = try parseFactor(depth: depth + 1)
let span: DSLSpan = DSLSpan(start: minus.span.start, end: operand.span.end)
if case .number(let n, _) = operand {
return .number(-n, span)
}
let zero: DSLExpr = .number(0, DSLSpan.point(minus.span.start))
return .binary(op: .subtract, lhs: zero, rhs: operand, span)
}
if check(.number) {
let t: DSLToken = advance()
guard let value: Double = Double(t.text.replacingOccurrences(of: "_", with: "")) else {
throw DSLParseError(kind: .invalidNumber(t.text), span: t.span)
}
return .number(value, t.span)
}
if check(.leftParen) {
let open: DSLToken = advance()
let inner: DSLExpr = try parseExpr(depth: depth + 1)
guard check(.rightParen) else {
throw DSLParseError(kind: .unclosedParen, span: open.span)
}
advance()
return inner
}
if check(.identifier) {
// `Name(` or `Name.` → a call; a bare identifier → a resource reference.
let next: DSLToken.Kind = tokens[pos + 1].kind
if next == .leftParen || next == .dot {
return try parseCall(depth: depth)
}
let ident: DSLToken = advance()
return .reference(name: ident.text, ident.span)
}
throw DSLParseError(kind: .expected("a number, name, or '('", found: describe(current)),
span: current.span)
}
private mutating func parseCall(depth: Int) throws -> DSLExpr {
let name: DSLToken = advance()
// Optional rate suffix — the *exact* Swift nested-class names so a DSL
// graph expression is paste-compatible with a Lyrebird project:
// `OscSin.Control(freq: 4)` reads and constructs identically in both.
var rate: DSLRate? = nil
if match(.dot) {
let rateToken: DSLToken = try expect(.identifier, "'Audio' or 'Control'")
switch rateToken.text {
case "Audio": rate = .audio
case "Control": rate = .control
default:
throw DSLParseError(kind: .invalidRate(rateToken.text), span: rateToken.span)
}
}
let open: DSLToken = try expect(.leftParen, "(")
var arguments: [DSLExpr.Argument] = []
if !check(.rightParen) {
repeat {
arguments.append(try parseArgument(depth: depth + 1))
} while match(.comma)
}
guard check(.rightParen) else {
throw DSLParseError(kind: .unclosedParen, span: open.span)
}
let close: DSLToken = advance()
return .call(name: name.text, rate: rate, arguments: arguments,
DSLSpan(start: name.span.start, end: close.span.end))
}
private mutating func parseArgument(depth: Int) throws -> DSLExpr.Argument {
guard depth <= DSLParser.maxDepth else {
throw DSLParseError(kind: .tooDeeplyNested, span: current.span)
}
// `ident :` → labelled argument.
if check(.identifier), tokens[pos + 1].kind == .colon {
let label: DSLToken = advance()
advance() // ':'
let value: DSLExpr = try parseExpr(depth: depth)
return DSLExpr.Argument(label: label.text, value: value,
span: DSLSpan(start: label.span.start, end: value.span.end))
}
let value: DSLExpr = try parseExpr(depth: depth)
return DSLExpr.Argument(label: nil, value: value, span: value.span)
}
/// Constant-fold a binary op over two number literals so computed constants
/// (`220 * 2`, `-0.5`) stay usable where a numeric literal is required.
/// Division by zero is left un-folded (built as a generator node).
private static func fold(_ op: DSLExpr.BinaryOp, _ lhs: DSLExpr, _ rhs: DSLExpr) -> DSLExpr {
let span: DSLSpan = DSLSpan(start: lhs.span.start, end: rhs.span.end)
if case .number(let a, _) = lhs, case .number(let b, _) = rhs {
switch op {
case .add: return .number(a + b, span)
case .subtract: return .number(a - b, span)
case .multiply: return .number(a * b, span)
case .divide where b != 0: return .number(a / b, span)
case .divide: break
}
}
return .binary(op: op, lhs: lhs, rhs: rhs, span)
}
}