200 lines
7.9 KiB
Swift
200 lines
7.9 KiB
Swift
// ScratchSwiftTokenizer.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// LyrebirdUI/LiveCompile
|
|
//
|
|
// A small, dependency-free lexer that classifies the colorable spans of Swift
|
|
// source — comments, string literals, numbers, keywords, and Capitalized type
|
|
// names — for the scratch editor's syntax highlighting. It is intentionally
|
|
// approximate (a highlighter, not a parser): good enough to read code at a
|
|
// glance, and re-run whole on every keystroke — a full grapheme walk of the
|
|
// buffer, fine for typical snippet sizes (not tuned or validated for very large
|
|
// documents). Pure (no AppKit) so it is unit-testable. Ranges are `NSRange`
|
|
// (UTF-16), matching `NSTextView`.
|
|
//
|
|
// macOS only — consumed by the macOS-only scratch editor.
|
|
|
|
#if os(macOS)
|
|
import Foundation
|
|
|
|
/// Classifies Swift source into colorable token spans for syntax highlighting.
|
|
enum ScratchSwiftTokenizer {
|
|
|
|
/// A colorable category. Uncategorized text (identifiers, punctuation,
|
|
/// whitespace) produces no token and renders in the default text color.
|
|
enum Kind: Equatable {
|
|
case keyword
|
|
case type
|
|
case string
|
|
case number
|
|
case comment
|
|
}
|
|
|
|
/// One colorable span. `range` is a UTF-16 `NSRange` into the source.
|
|
struct Token: Equatable {
|
|
let range: NSRange
|
|
let kind: Kind
|
|
}
|
|
|
|
/// Swift keywords (plus a few common contextual ones) colored as keywords.
|
|
private static let keywords: Set<String> = [
|
|
"associatedtype", "class", "deinit", "enum", "extension", "fileprivate",
|
|
"func", "import", "init", "inout", "internal", "let", "open", "operator",
|
|
"private", "precedencegroup", "protocol", "public", "rethrows", "static",
|
|
"struct", "subscript", "typealias", "var",
|
|
"break", "case", "continue", "default", "defer", "do", "else",
|
|
"fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch",
|
|
"where", "while",
|
|
"as", "await", "catch", "false", "is", "nil", "self", "Self", "super",
|
|
"throw", "throws", "true", "try", "Any",
|
|
"async", "some", "any", "mutating", "nonmutating", "weak", "unowned",
|
|
"final", "lazy", "indirect", "convenience", "required", "optional",
|
|
"override", "dynamic", "willSet", "didSet", "get", "set",
|
|
"actor", "nonisolated", "isolated", "distributed", "consuming",
|
|
"borrowing", "sending", "each",
|
|
]
|
|
|
|
/// UTF-16 length of the `"""` multiline-string delimiter.
|
|
private static let tripleQuoteDelimiterLength: Int = 3
|
|
|
|
/// Classify `text` into colorable token spans, left to right.
|
|
static func tokens(in text: String) -> [Token] {
|
|
let chars: [Character] = Array(text)
|
|
let count: Int = chars.count
|
|
// Prefix table of UTF-16 offsets so `[a, b)` maps to an exact NSRange
|
|
// even with multi-unit characters (emoji in a comment, etc.).
|
|
var utf16Starts: [Int] = [Int](repeating: 0, count: count + 1)
|
|
var acc: Int = 0
|
|
for k: Int in 0..<count {
|
|
utf16Starts[k] = acc
|
|
acc += chars[k].utf16.count
|
|
}
|
|
utf16Starts[count] = acc
|
|
|
|
func makeRange(_ start: Int, _ end: Int) -> NSRange {
|
|
NSRange(location: utf16Starts[start], length: utf16Starts[end] - utf16Starts[start])
|
|
}
|
|
|
|
var tokens: [Token] = []
|
|
var i: Int = 0
|
|
while i < count {
|
|
let c: Character = chars[i]
|
|
|
|
// Line comment: // … end of line
|
|
if c == "/", i + 1 < count, chars[i + 1] == "/" {
|
|
let start: Int = i
|
|
i += 2
|
|
while i < count, chars[i] != "\n" { i += 1 }
|
|
tokens.append(Token(range: makeRange(start, i), kind: .comment))
|
|
continue
|
|
}
|
|
|
|
// Block comment: /* … */ with Swift's nesting.
|
|
if c == "/", i + 1 < count, chars[i + 1] == "*" {
|
|
let start: Int = i
|
|
i += 2
|
|
var depth: Int = 1
|
|
while i < count, depth > 0 {
|
|
if chars[i] == "/", i + 1 < count, chars[i + 1] == "*" {
|
|
depth += 1
|
|
i += 2
|
|
} else if chars[i] == "*", i + 1 < count, chars[i + 1] == "/" {
|
|
depth -= 1
|
|
i += 2
|
|
} else {
|
|
i += 1
|
|
}
|
|
}
|
|
tokens.append(Token(range: makeRange(start, i), kind: .comment))
|
|
continue
|
|
}
|
|
|
|
// String literal: triple-quoted (multiline) or single-line.
|
|
if c == "\"" {
|
|
let start: Int = i
|
|
if i + 2 < count, chars[i + 1] == "\"", chars[i + 2] == "\"" {
|
|
i += tripleQuoteDelimiterLength
|
|
while i < count {
|
|
if chars[i] == "\\" { i = min(i + 2, count); continue }
|
|
if chars[i] == "\"", i + 2 < count,
|
|
chars[i + 1] == "\"", chars[i + 2] == "\"" {
|
|
i += tripleQuoteDelimiterLength
|
|
break
|
|
}
|
|
i += 1
|
|
}
|
|
} else {
|
|
i += 1
|
|
while i < count {
|
|
if chars[i] == "\\" { i = min(i + 2, count); continue } // escape
|
|
if chars[i] == "\"" { i += 1; break }
|
|
if chars[i] == "\n" { break } // unterminated
|
|
i += 1
|
|
}
|
|
}
|
|
tokens.append(Token(range: makeRange(start, i), kind: .string))
|
|
continue
|
|
}
|
|
|
|
// Number literal (must start with a digit here).
|
|
if c.isNumber {
|
|
let start: Int = i
|
|
i += 1
|
|
while i < count {
|
|
let d: Character = chars[i]
|
|
if (d == "e" || d == "E" || d == "p" || d == "P"),
|
|
i + 1 < count, chars[i + 1] == "+" || chars[i + 1] == "-" {
|
|
i += 2 // signed exponent, e.g. 1e-10
|
|
} else if d.isHexDigit || d == "_"
|
|
|| d == "x" || d == "X" || d == "o" || d == "O"
|
|
|| d == "b" || d == "B" || d == "e" || d == "E"
|
|
|| d == "p" || d == "P" {
|
|
i += 1
|
|
} else if d == ".", i + 1 < count, chars[i + 1].isNumber {
|
|
i += 1 // decimal point (not a range/member `.`)
|
|
} else {
|
|
break
|
|
}
|
|
}
|
|
tokens.append(Token(range: makeRange(start, i), kind: .number))
|
|
continue
|
|
}
|
|
|
|
// Attribute: @escaping, @MainActor, …
|
|
if c == "@" {
|
|
let start: Int = i
|
|
i += 1
|
|
while i < count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
|
|
i += 1
|
|
}
|
|
tokens.append(Token(range: makeRange(start, i), kind: .keyword))
|
|
continue
|
|
}
|
|
|
|
// Identifier: keyword, Capitalized type, or plain (no token).
|
|
if c.isLetter || c == "_" {
|
|
let start: Int = i
|
|
i += 1
|
|
while i < count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
|
|
i += 1
|
|
}
|
|
let word: String = String(chars[start..<i])
|
|
if keywords.contains(word) {
|
|
tokens.append(Token(range: makeRange(start, i), kind: .keyword))
|
|
} else if let first: Character = word.first, first.isUppercase {
|
|
tokens.append(Token(range: makeRange(start, i), kind: .type))
|
|
}
|
|
continue
|
|
}
|
|
|
|
i += 1
|
|
}
|
|
return tokens
|
|
}
|
|
}
|
|
|
|
#endif
|