237 lines
9.3 KiB
Swift
237 lines
9.3 KiB
Swift
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 `<?` reads as HTML with PHP islands.
|
|
public init(language: Language?, text: String = "") {
|
|
grammar = Grammar(language, text: text)
|
|
}
|
|
|
|
/// True when a construct is still open, such as a block comment or a heredoc.
|
|
public var isInsideConstruct: Bool {
|
|
state.mode != .code || state.child != nil || !state.resumes.isEmpty
|
|
}
|
|
}
|
|
|
|
public enum SyntaxHighlighter {
|
|
/// Tokenises a whole buffer; unmarked stretches are `.plain`.
|
|
///
|
|
/// Runs on every keystroke in the editable view, so it must stay linear in the text
|
|
/// length. Multi-line constructs (block comments, heredocs, template strings) carry
|
|
/// state across lines. PHP class-name tokens found in `knownSymbols` become `.symbol`.
|
|
/// The tokens cover the text end to end, in order, adjacent runs of one role merged.
|
|
public static func tokens(for text: String, language: Language?, knownSymbols: Set<String> = []) -> [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<String> = []) -> [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<String> = []) -> [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 `<?php … ?>` 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("<?") ? .phpTemplate : .php
|
|
case .javascript: self = .javascript(typescript: false, jsx: false)
|
|
case .jsx: self = .javascript(typescript: false, jsx: true)
|
|
case .typescript: self = .javascript(typescript: true, jsx: false)
|
|
case .tsx: self = .javascript(typescript: true, jsx: true)
|
|
case .markup: self = .markup
|
|
case .css: self = .css
|
|
case .json: self = .json
|
|
case .markdown: self = .markdown
|
|
case .bash: self = .bash
|
|
case .python: self = .python
|
|
case .yaml: self = .yaml
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The construct a grammar is inside at a line break.
|
|
enum Mode: Hashable, Sendable {
|
|
case code
|
|
case blockComment
|
|
/// A string that may run over lines: PHP and shell quotes.
|
|
case quoted(UInt16)
|
|
/// A JavaScript template literal.
|
|
case template
|
|
/// A Python triple-quoted string.
|
|
case triple(UInt16)
|
|
/// PHP `<<<ID` or shell `<<ID`; `interpolates` is false for nowdoc and quoted shell markers.
|
|
case heredoc(id: String, interpolates: Bool)
|
|
case markupComment
|
|
case cdata
|
|
/// Inside `<name …` before its `>`; 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 `<script>` body, a fenced block.
|
|
indirect enum Embedded: Hashable, Sendable {
|
|
case grammar(Grammar, GrammarState, until: Terminator)
|
|
}
|
|
|
|
enum Grammars {
|
|
/// Scans the rest of the line, handing over to and back from embedded grammars.
|
|
static func scan(_ grammar: Grammar, _ lx: inout Lexer, _ st: inout GrammarState) {
|
|
while true {
|
|
if case let .grammar(inner, innerState, terminator)? = st.child, terminator != .fence {
|
|
var state = innerState
|
|
let outerStop = lx.stop
|
|
lx.stop = terminator
|
|
scan(inner, &lx, &state)
|
|
lx.stop = outerStop
|
|
guard lx.i < lx.end else {
|
|
st.child = .grammar(inner, state, until: terminator)
|
|
return
|
|
}
|
|
if terminator == .phpClose {
|
|
lx.emit(lx.i, lx.i + 2, .keyword)
|
|
lx.i += 2
|
|
}
|
|
st.child = nil
|
|
}
|
|
guard lx.i < lx.end else { return }
|
|
scanOwn(grammar, &lx, &st)
|
|
guard case let .grammar(_, _, terminator)? = st.child, terminator != .fence, lx.i <= lx.end else { return }
|
|
}
|
|
}
|
|
|
|
private static func scanOwn(_ grammar: Grammar, _ lx: inout Lexer, _ st: inout GrammarState) {
|
|
switch grammar {
|
|
case let .javascript(typescript, jsx): JavaScriptGrammar.scan(&lx, &st, typescript: typescript, jsx: jsx)
|
|
case .php: PHPGrammar.scan(&lx, &st)
|
|
case .phpTemplate: MarkupGrammar.scan(&lx, &st, phpIslands: true)
|
|
case .markup: MarkupGrammar.scan(&lx, &st, phpIslands: false)
|
|
case .css: CSSGrammar.scan(&lx, &st)
|
|
case .json: JSONGrammar.scan(&lx, &st)
|
|
case .markdown: MarkdownGrammar.scan(&lx, &st)
|
|
case .bash: ShellGrammar.scan(&lx, &st)
|
|
case .python: PythonGrammar.scan(&lx, &st)
|
|
case .yaml: YAMLGrammar.scan(&lx, &st)
|
|
}
|
|
}
|
|
}
|