import Foundation /// The six syntax roles of the design, plus the ⌘-clickable class name. public enum TokenRole: String, Sendable, Equatable { /// Plain text and function names. case plain /// Variables and properties. case variable case comment /// Keywords, operators, pseudo-classes. case keyword /// Strings, values, type paths. case string /// Numbers, tags, hex literals. case number /// A class name the project declares, underlined while ⌘ is held (PHP only). case symbol } /// A run of one role, as a UTF-16 range into the highlighted text (NSAttributedString-friendly). public struct Token: Sendable, Equatable { public var location: Int public var length: Int public var role: TokenRole public init(location: Int, length: Int, role: TokenRole) { self.location = location self.length = length self.role = role } } /// What the tokenizer carries from the end of one line to the start of the next. /// /// An editor keeps the state after every line; after an edit it re-tokenizes from the /// edited line until the state it computes equals the one it stored. public struct HighlightState: Sendable, Hashable { let grammar: Grammar? var state = GrammarState() /// The state before the first line. A PHP buffer containing ` = []) -> [Token] { let units = Array(text.utf16) var state = HighlightState(language: language, text: text) var lexer = Lexer(units: units, symbols: knownSymbols) if state.grammar != nil { var lineStart = 0 while lineStart <= units.count { var lineEnd = lineStart while lineEnd < units.count && units[lineEnd] != 10 { lineEnd += 1 } lexer.i = lineStart lexer.end = lineEnd scanLine(&lexer, &state) lineStart = lineEnd + 1 } } return filled(lexer.tokens, length: units.count) } /// Tokenises one line on its own, for the diff panes where every line stands alone. public static func lineTokens(for line: String, language: Language?, knownSymbols: Set = []) -> [Token] { var state = HighlightState(language: language, text: line) return lineTokens(for: line, state: &state, knownSymbols: knownSymbols) } /// Tokenises one line (without its newline) starting from `state`, and advances `state` past it. public static func lineTokens(for line: String, state: inout HighlightState, knownSymbols: Set = []) -> [Token] { let units = Array(line.utf16) var lexer = Lexer(units: units, symbols: knownSymbols) scanLine(&lexer, &state) return filled(lexer.tokens, length: units.count) } private static func scanLine(_ lexer: inout Lexer, _ state: inout HighlightState) { guard let grammar = state.grammar else { return } Grammars.scan(grammar, &lexer, &state.state) } /// Fills the gaps between role tokens with `.plain`, so the tokens tile the text. private static func filled(_ tokens: [Token], length: Int) -> [Token] { var out: [Token] = [] out.reserveCapacity(tokens.count * 2 + 1) var position = 0 for token in tokens { let start = max(token.location, position) let end = min(token.location + token.length, length) guard end > start else { continue } if start > position { out.append(Token(location: position, length: start - position, role: .plain)) } out.append(Token(location: start, length: end - start, role: token.role)) position = end } if position < length { out.append(Token(location: position, length: length - position, role: .plain)) } return out } } /// One tokenizer; several `Language`s share one (the JavaScript family), and PHP has two. enum Grammar: Hashable, Sendable { case javascript(typescript: Bool, jsx: Bool) case php /// HTML with `` islands. case phpTemplate case markup case css case json case markdown case bash case python case yaml init?(_ language: Language?, text: String) { switch language { case nil: return nil case .php: self = text.contains("`; closing tags keep their leading slash. case markupTag(String) case markupValue(quote: UInt16, tag: String) /// Inside a JSX tag; `level` counts the elements open around it, a closing tag included. case jsxTag(level: Int, closing: Bool) /// JSX children text inside `level` open elements. case jsxText(level: Int) /// A CSS declaration value that did not end on its line. case cssValue /// A YAML `|` or `>` block, holding the indent of its key. case yamlBlock(indent: Int) /// A Markdown fence, closed by `count` or more `marker` characters. case fence(marker: UInt16, count: Int) } struct GrammarState: Hashable, Sendable { var mode: Mode = .code /// Brace depth: CSS nesting, or the braces inside a `${…}` or JSX `{…}` expression. var depth = 0 /// For each open `${` or JSX `{`, where its closing `}` returns to. var resumes: [Resume] = [] var child: Embedded? } /// The brace depth at which a `}` ends an embedded expression, and the mode it returns to. struct Resume: Hashable, Sendable { var depth: Int var mode: Mode } /// A grammar running inside another: PHP in HTML, a `