Files
Lyrebird/Sources/LyrebirdGraphDSL/DSLLexer.swift
T

99 lines
3.8 KiB
Swift

// DSLLexer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Turns DSL source into a flat token stream. Whitespace is skipped, `#` runs to
// end of line as a comment, and runs of blank lines collapse to one `newline`
// separator. Spans are character offsets into the source.
/// Lexes DSL source into ``DSLToken``s.
public enum DSLLexer {
/// Tokenize `source`, ending with a single `.eof` token.
/// - Throws: ``DSLParseError`` on a character that starts no valid token.
public static func tokenize(_ source: String) throws -> [DSLToken] {
let chars: [Character] = Array(source)
let count: Int = chars.count
var i: Int = 0
var tokens: [DSLToken] = []
func punct(_ kind: DSLToken.Kind) {
tokens.append(DSLToken(kind: kind, text: "", span: DSLSpan(start: i, end: i + 1)))
i += 1
}
while i < count {
let c: Character = chars[i]
// Horizontal whitespace.
if c == " " || c == "\t" || c == "\r" {
i += 1
continue
}
// Comment to end of line.
if c == "#" {
while i < count, chars[i] != "\n" { i += 1 }
continue
}
// Newline(s) collapse to one separator.
if c == "\n" {
let start: Int = i
while i < count, chars[i] == "\n" || chars[i] == " " || chars[i] == "\t" || chars[i] == "\r" {
i += 1
}
tokens.append(DSLToken(kind: .newline, text: "", span: DSLSpan(start: start, end: i)))
continue
}
// Number: ASCII digits with optional fraction / exponent. (ASCII so
// `½`/`²`/other Unicode numerics don't lex as a number then fail.)
if isASCIIDigit(c) {
let start: Int = i
while i < count, isASCIIDigit(chars[i]) || chars[i] == "_" { i += 1 }
if i < count, chars[i] == ".", i + 1 < count, isASCIIDigit(chars[i + 1]) {
i += 1
while i < count, isASCIIDigit(chars[i]) || chars[i] == "_" { i += 1 }
}
if i < count, chars[i] == "e" || chars[i] == "E" {
i += 1
if i < count, chars[i] == "+" || chars[i] == "-" { i += 1 }
while i < count, isASCIIDigit(chars[i]) { i += 1 }
}
let text: String = String(chars[start..<i])
tokens.append(DSLToken(kind: .number, text: text, span: DSLSpan(start: start, end: i)))
continue
}
// Identifier.
if c.isLetter || c == "_" {
let start: Int = i
while i < count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" { i += 1 }
let text: String = String(chars[start..<i])
tokens.append(DSLToken(kind: .identifier, text: text, span: DSLSpan(start: start, end: i)))
continue
}
// Punctuation.
switch c {
case "(": punct(.leftParen)
case ")": punct(.rightParen)
case ",": punct(.comma)
case ":": punct(.colon)
case ".": punct(.dot)
case "=": punct(.equals)
case "+": punct(.plus)
case "-": punct(.minus)
case "*": punct(.star)
case "/": punct(.slash)
default:
throw DSLParseError(kind: .unexpectedCharacter(c), span: DSLSpan(start: i, end: i + 1))
}
}
tokens.append(DSLToken(kind: .eof, text: "", span: DSLSpan.point(count)))
return tokens
}
private static func isASCIIDigit(_ c: Character) -> Bool {
c >= "0" && c <= "9"
}
}