Files
2026-10-17 17:33:13 +02:00

115 lines
3.2 KiB
Swift

/// The kinds of code that get their own colour.
public enum CodeTokenKind: Sendable, Equatable {
case keyword
case string
case number
case comment
case variable
case tag
/// An attribute name in XML, a key in JSON.
case attribute
}
/// A highlighted piece of code; the range counts UTF-16 units, as NSRange does.
public struct CodeToken: Sendable, Equatable {
public let kind: CodeTokenKind
public let range: Range<Int>
public init(_ kind: CodeTokenKind, _ range: Range<Int>) {
self.kind = kind
self.range = range
}
}
/// The highlighted pieces of a code body; text between them is plain code.
public enum CodeHighlighter {
public static func tokens(_ body: String, kind: FenceKind) -> [CodeToken] {
switch kind {
case .php: PHPTokenizer.tokens(body)
case .json: JSONTokenizer.tokens(body)
case .xml: XMLTokenizer.tokens(body)
case .csv: []
}
}
}
/// Walks the UTF-16 units of a code body; all syntax that matters is ASCII.
struct CodeScanner {
let units: [UInt16]
var index = 0
private(set) var tokens: [CodeToken] = []
init(_ text: String) {
units = Array(text.utf16)
}
var atEnd: Bool {
index >= units.count
}
func peek(_ offset: Int = 0) -> UInt16? {
index + offset < units.count ? units[index + offset] : nil
}
func peekIs(_ character: Character, _ offset: Int = 0) -> Bool {
peek(offset) == character.utf16.first
}
func starts(with text: String) -> Bool {
var offset = 0
for unit in text.utf16 {
guard peek(offset) == unit else { return false }
offset += 1
}
return true
}
func text(from start: Int) -> String {
String(decoding: units[start..<index], as: UTF16.self)
}
mutating func add(_ kind: CodeTokenKind, from start: Int) {
if index > start { tokens.append(CodeToken(kind, start..<index)) }
}
mutating func skip(while condition: (UInt16) -> Bool) {
while let unit = peek(), condition(unit) { index += 1 }
}
/// Moves past `end`, or to the end when it never comes.
mutating func skip(past end: String) {
while !atEnd, !starts(with: end) { index += 1 }
index = min(units.count, index + end.utf16.count)
}
/// From an opening quote to past its closing quote.
mutating func skipQuoted(escapes: Bool) {
let quote = units[index]
index += 1
while let unit = peek() {
index += 1
if escapes, unit == 0x5C {
index = min(units.count, index + 1)
} else if unit == quote {
return
}
}
}
static func isLetter(_ unit: UInt16) -> Bool {
(unit >= 0x41 && unit <= 0x5A) || (unit >= 0x61 && unit <= 0x7A) || unit == 0x5F || unit >= 0x80
}
static func isDigit(_ unit: UInt16) -> Bool {
unit >= 0x30 && unit <= 0x39
}
static func isWord(_ unit: UInt16) -> Bool {
isLetter(unit) || isDigit(unit)
}
static func isSpace(_ unit: UInt16) -> Bool {
unit == 0x20 || unit == 0x09 || unit == 0x0A || unit == 0x0D
}
}