restores Helder in all its glory

This commit is contained in:
2026-09-28 11:34:49 +02:00
parent c2b38b853c
commit 1d29d0952d
280 changed files with 29205 additions and 7 deletions
@@ -0,0 +1,155 @@
import Foundation
/// CSS, and SCSS too: nesting, `$vars` and `//` comments.
enum CSSGrammar {
private enum Context {
case selector, property, value
}
private static let important = Unit.literal("important")
private static let url = Unit.literal("url(")
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
let lineStart = lx.i
var context: Context = st.mode == .cssValue ? .value : statementContext(lx, depth: st.depth)
if st.mode == .cssValue { st.mode = .code }
while lx.i < lx.end {
if st.mode == .blockComment {
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
}
if lx.stop != nil && lx.atStop() { return }
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.slash where lx.peek(1) == Unit.slash && (start == lineStart || Unit.isSpace(lx.unit(at: start - 1))):
lx.lineComment()
case Unit.quote, Unit.apostrophe:
lx.i += 1
_ = lx.quoted(from: start, quote: c)
case Unit.lbrace:
lx.i += 1
st.depth += 1
context = statementContext(lx, depth: st.depth)
case Unit.rbrace:
lx.i += 1
st.depth = max(0, st.depth - 1)
context = statementContext(lx, depth: st.depth)
case Unit.semicolon:
lx.i += 1
context = statementContext(lx, depth: st.depth)
case Unit.at where Unit.isIdentStart(lx.peek(1)):
lx.i += 1
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .keyword)
context = .value
case Unit.dollar where Unit.isIdentStart(lx.peek(1)):
lx.i += 1
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .variable)
if lx.nextNonSpace() == Unit.colon { context = .value }
case Unit.bang where lx.startsIgnoringCase(with: important, at: start + 1):
lx.i += 1 + important.count
lx.emit(start, lx.i, .keyword)
default:
switch context {
case .selector: selectorPart(&lx)
case .property:
if Unit.isIdentStart(c) || c == Unit.minus {
lx.identifier { $0 == Unit.minus }
if lx.nextNonSpace() == Unit.colon {
lx.emit(start, lx.i, .variable)
lx.skipSpaces()
lx.i += 1
context = .value
} else {
lx.emit(start, lx.i, .number)
}
} else {
selectorPart(&lx)
}
case .value: valuePart(&lx)
}
}
}
if context == .value && st.depth > 0 && st.mode == .code { st.mode = .cssValue }
}
/// Whether what follows is a selector or a declaration: at the top level always a selector,
/// inside a block a selector only when a `{` comes before any `;` or `}` on the line.
private static func statementContext(_ lx: Lexer, depth: Int) -> Context {
if depth == 0 { return .selector }
var k = lx.i
while k < lx.end {
switch lx.u[k] {
case Unit.lbrace: return .selector
case Unit.semicolon, Unit.rbrace: return .property
default: k += 1
}
}
return .property
}
private static func selectorPart(_ lx: inout Lexer) {
let start = lx.i
let c = lx.u[start]
switch c {
case Unit.colon:
lx.i += 1
if lx.peek() == Unit.colon { lx.i += 1 }
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .keyword)
case Unit.amp, Unit.greater, Unit.plus, Unit.tilde:
lx.i += 1
lx.emit(start, lx.i, .keyword)
case Unit.lbracket:
while lx.i < lx.end && lx.u[lx.i] != Unit.rbracket { lx.i += 1 }
lx.i = min(lx.i + 1, lx.end)
lx.emit(start, lx.i, .number)
case Unit.dot, Unit.hash, Unit.star, Unit.percent:
lx.i += 1
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .number)
case _ where Unit.isIdentStart(c) || c == Unit.minus:
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .number)
default:
lx.i += 1
}
}
private static func valuePart(_ lx: inout Lexer) {
let start = lx.i
let c = lx.u[start]
if c == Unit.hash && Unit.isHexDigit(lx.peek(1)) {
lx.i += 1
lx.identifier()
lx.emit(start, lx.i, .number)
} else if Unit.isDigit(c) || ((c == Unit.dot || c == Unit.minus || c == Unit.plus) && (Unit.isDigit(lx.peek(1)) || (lx.peek(1) == Unit.dot && Unit.isDigit(lx.peek(2))))) {
lx.i += 1
while lx.i < lx.end && (Unit.isDigit(lx.u[lx.i]) || lx.u[lx.i] == Unit.dot) { lx.i += 1 }
if lx.peek() == Unit.percent { lx.i += 1 } else { lx.identifier() }
lx.emit(start, lx.i, .number)
} else if lx.startsIgnoringCase(with: url) {
lx.i += url.count
let body = lx.i
while lx.i < lx.end && lx.u[lx.i] != Unit.rparen { lx.i += 1 }
lx.emit(body, lx.i, .string)
} else if c == Unit.minus && lx.peek(1) == Unit.minus {
lx.identifier { $0 == Unit.minus }
lx.emit(start, lx.i, .variable)
} else if Unit.isIdentStart(c) || c == Unit.minus {
lx.identifier { $0 == Unit.minus }
if lx.peek() != Unit.lparen { lx.emit(start, lx.i, .string) }
} else {
lx.i += 1
}
}
}
@@ -0,0 +1,44 @@
import Foundation
/// JSON with comments allowed, since tsconfig-style files carry them.
enum JSONGrammar {
private static let literals: Set<String> = ["true", "false", "null"]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
while lx.i < lx.end {
if st.mode == .blockComment {
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
}
let start = lx.i
let c = lx.u[start]
switch c {
case Unit.slash where lx.peek(1) == Unit.slash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.quote:
lx.i += 1
var closed = false
while lx.i < lx.end && !closed {
if lx.u[lx.i] == Unit.backslash { lx.i += 1 } else if lx.u[lx.i] == Unit.quote { closed = true }
lx.i += 1
}
lx.i = min(lx.i, lx.end)
lx.emit(start, lx.i, lx.nextNonSpace() == Unit.colon ? .variable : .string)
case _ where Unit.isDigit(c) || (c == Unit.minus && Unit.isDigit(lx.peek(1))):
if c == Unit.minus {
lx.i += 1
lx.emit(start, lx.i, .number)
}
lx.number()
case _ where Unit.isAlpha(c):
lx.identifier()
if literals.contains(lx.text(start, lx.i)) { lx.emit(start, lx.i, .number) }
default:
lx.i += 1
}
}
}
}
@@ -0,0 +1,256 @@
import Foundation
enum JavaScriptGrammar {
static let keywords: Set<String> = [
"as", "async", "await", "break", "case", "catch", "class", "const", "continue", "debugger",
"default", "delete", "do", "else", "enum", "export", "extends", "finally", "for", "from",
"function", "get", "if", "implements", "import", "in", "instanceof", "interface", "let", "new",
"of", "package", "private", "protected", "public", "return", "set", "static", "super", "switch",
"this", "throw", "try", "typeof", "var", "void", "while", "with", "yield",
]
static let typeScriptKeywords: Set<String> = [
"abstract", "declare", "is", "keyof", "module", "namespace", "readonly", "type", "infer",
"satisfies", "override", "unique", "asserts", "accessor",
]
/// Painted as builtins, in the number colour.
static let typeScriptBuiltins: Set<String> = [
"string", "number", "boolean", "any", "void", "never", "unknown", "object", "symbol", "bigint",
]
static let constants: Set<String> = ["true", "false", "null", "undefined", "NaN", "Infinity"]
/// Keywords after which the next name is a class.
private static let classIntroducers: Set<String> = ["class", "extends", "implements", "new", "instanceof", "interface"]
/// Keywords after which a `/` starts a regex rather than a division.
private static let valueKeywords: Set<String> = ["this", "super"]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState, typescript: Bool, jsx: Bool) {
var expectsValue = true
var classNext = false
while lx.i < lx.end {
switch st.mode {
case .blockComment:
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
case .template:
template(&lx, &st)
expectsValue = false
continue
case let .jsxTag(level, closing):
jsxTag(&lx, &st, level: level, closing: closing)
expectsValue = true
continue
case let .jsxText(level):
jsxText(&lx, &st, level: level)
expectsValue = true
continue
default:
break
}
if lx.stop != nil && lx.atStop() { return }
let c = lx.u[lx.i]
let start = lx.i
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.slash where lx.peek(1) == Unit.slash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.slash where expectsValue && regex(&lx):
expectsValue = false
case Unit.quote, Unit.apostrophe:
lx.i += 1
_ = lx.quoted(from: start, quote: c)
expectsValue = false
case Unit.backtick:
lx.i += 1
lx.emit(start, lx.i, .string)
st.mode = .template
case _ where Unit.isDigit(c) || (c == Unit.dot && Unit.isDigit(lx.peek(1))):
lx.number()
expectsValue = false
case _ where Unit.isIdentStart(c) || c == Unit.dollar || (c == Unit.hash && Unit.isIdentStart(lx.peek(1))):
lx.i += 1
lx.identifier { $0 == Unit.dollar }
let word = lx.text(start, lx.i)
if keywords.contains(word) || (typescript && typeScriptKeywords.contains(word)) {
lx.emit(start, lx.i, .keyword)
classNext = classIntroducers.contains(word)
expectsValue = !valueKeywords.contains(word)
continue
}
if constants.contains(word) || (typescript && typeScriptBuiltins.contains(word)) {
lx.emit(start, lx.i, .number)
} else if classNext {
lx.emit(start, lx.i, .variable)
} else if isConstantName(lx, start, lx.i) {
lx.emit(start, lx.i, .number)
}
classNext = false
expectsValue = false
continue
case Unit.lbrace:
lx.i += 1
if !st.resumes.isEmpty { st.depth += 1 }
expectsValue = true
case Unit.rbrace:
lx.i += 1
if let resume = st.resumes.last, resume.depth == st.depth {
st.resumes.removeLast()
st.mode = resume.mode
} else if !st.resumes.isEmpty {
st.depth -= 1
}
expectsValue = true
case Unit.lparen, Unit.lbracket, Unit.comma, Unit.semicolon:
lx.i += 1
expectsValue = true
case Unit.rparen, Unit.rbracket:
lx.i += 1
expectsValue = false
case Unit.less where jsx && (expectsValue || lx.peek(1) == Unit.slash):
if !openJSX(&lx, &st, level: 0) { lx.operatorRun() }
case Unit.dot:
lx.i += 1
while lx.peek() == Unit.dot { lx.i += 1 }
if lx.i - start > 1 { lx.emit(start, lx.i, .keyword) }
expectsValue = lx.i - start > 1
case _ where Unit.isOperator(c):
lx.operatorRun()
expectsValue = true
default:
lx.i += 1
}
classNext = false
}
}
/// `FOO_BAR`: an all-caps name of two or more characters, painted as a constant.
static func isConstantName(_ lx: Lexer, _ from: Int, _ to: Int) -> Bool {
guard to - from >= 2, Unit.isUpper(lx.u[from]) else { return false }
for k in from..<to where Unit.isLower(lx.u[k]) { return false }
return true
}
/// A regex literal from the `/` at `lx.i`; false (nothing consumed) when the line ends before it closes.
private static func regex(_ lx: inout Lexer) -> Bool {
let start = lx.i
var k = start + 1
var inClass = false
while k < lx.end {
let c = lx.u[k]
if c == Unit.backslash {
k += 2
continue
}
if c == Unit.lbracket { inClass = true }
if c == Unit.rbracket { inClass = false }
if c == Unit.slash && !inClass { break }
k += 1
}
guard k < lx.end, k > start + 1 else { return false }
k += 1
while k < lx.end && Unit.isAlpha(lx.u[k]) { k += 1 }
lx.i = k
lx.emit(start, k, .string)
return true
}
/// Template-literal text up to the closing backtick, a `${`, or the end of the line.
private static func template(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.backslash {
lx.i = min(lx.i + 2, lx.end)
continue
}
if c == Unit.backtick {
lx.i += 1
lx.emit(start, lx.i, .string)
st.mode = .code
return
}
if c == Unit.dollar && lx.peek(1) == Unit.lbrace {
lx.emit(start, lx.i, .string)
lx.i += 2
st.resumes.append(Resume(depth: st.depth, mode: .template))
st.mode = .code
return
}
lx.i += 1
}
lx.emit(start, lx.i, .string)
}
/// `<Name`, `</Name`, `<>` or `</>`; false (nothing consumed) for anything else.
private static func openJSX(_ lx: inout Lexer, _ st: inout GrammarState, level: Int) -> Bool {
var k = lx.i + 1
let closing = lx.unit(at: k) == Unit.slash
if closing { k += 1 }
let first = lx.unit(at: k)
if first == Unit.greater {
lx.i = k + 1
st.mode = children(closing ? level - 1 : level + 1)
return true
}
guard Unit.isAlpha(first) else { return false }
let nameStart = k
while k < lx.end && (Unit.isIdentPart(lx.u[k]) || lx.u[k] == Unit.dot || lx.u[k] == Unit.minus || lx.u[k] == Unit.colon) { k += 1 }
lx.emit(nameStart, k, .number)
lx.i = k
st.mode = .jsxTag(level: level, closing: closing)
return true
}
private static func children(_ open: Int) -> Mode {
open > 0 ? .jsxText(level: open) : .code
}
/// Attributes inside a JSX tag, up to `>` or `/>`; a `{` hands over to code until its `}`.
private static func jsxTag(_ lx: inout Lexer, _ st: inout GrammarState, level: Int, closing: Bool) {
while lx.i < lx.end {
let c = lx.u[lx.i]
let start = lx.i
if c == Unit.greater {
lx.i += 1
st.mode = children(closing ? level - 1 : level + 1)
return
} else if c == Unit.slash && lx.peek(1) == Unit.greater {
lx.i += 2
st.mode = children(level)
return
} else if c == Unit.lbrace {
lx.i += 1
st.resumes.append(Resume(depth: st.depth, mode: .jsxTag(level: level, closing: closing)))
st.mode = .code
return
} else if c == Unit.quote || c == Unit.apostrophe {
lx.i += 1
_ = lx.quoted(from: start, quote: c, escapes: false)
} else if Unit.isIdentStart(c) {
lx.identifier { $0 == Unit.minus || $0 == Unit.colon }
lx.emit(start, lx.i, .variable)
} else {
lx.i += 1
}
}
}
/// Children text: plain up to the next tag or `{` expression.
private static func jsxText(_ lx: inout Lexer, _ st: inout GrammarState, level: Int) {
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.less && openJSX(&lx, &st, level: level) { return }
if c == Unit.lbrace {
lx.i += 1
st.resumes.append(Resume(depth: st.depth, mode: .jsxText(level: level)))
st.mode = .code
return
}
lx.i += 1
}
}
}
+206
View File
@@ -0,0 +1,206 @@
import Foundation
/// Where an embedded grammar hands control back to its host.
enum Terminator: Hashable, Sendable {
/// `?>` closes a PHP island inside markup.
case phpClose
/// `</name` closes a `<script>` or `<style>` body; the name is lowercase.
case closingTag(String)
/// A Markdown fence closes on a line of its own, which the Markdown grammar checks itself.
case fence
}
/// A cursor over UTF-16 units that collects non-plain tokens for one line at a time.
///
/// Grammars scan `i..<end` and must return when `i` reaches `end`, or when `atStop()`
/// is true at a code position, so the host grammar can take over.
struct Lexer {
let u: [UInt16]
var i: Int
var end: Int
var stop: Terminator?
let symbols: Set<String>
private(set) var tokens: [Token] = []
init(units: [UInt16], symbols: Set<String>) {
u = units
i = 0
end = units.count
self.symbols = symbols
}
/// The unit `k` places ahead, or 0 past the end of the line.
@inline(__always) func peek(_ k: Int = 0) -> UInt16 {
let j = i + k
return j < end ? u[j] : 0
}
func unit(at j: Int) -> UInt16 {
j >= 0 && j < end ? u[j] : 0
}
mutating func emit(_ from: Int, _ to: Int, _ role: TokenRole) {
guard to > from, role != .plain else { return }
if let last = tokens.last, last.role == role, last.location + last.length == from {
tokens[tokens.count - 1].length += to - from
} else {
tokens.append(Token(location: from, length: to - from, role: role))
}
}
func text(_ from: Int, _ to: Int) -> String {
String(decoding: u[from..<to], as: UTF16.self)
}
func starts(with literal: [UInt16], at j: Int? = nil) -> Bool {
let at = j ?? i
guard at + literal.count <= end else { return false }
for k in literal.indices where u[at + k] != literal[k] { return false }
return true
}
/// ASCII case-insensitive `starts(with:)`; `literal` must be lowercase.
func startsIgnoringCase(with literal: [UInt16], at j: Int? = nil) -> Bool {
let at = j ?? i
guard at + literal.count <= end else { return false }
for k in literal.indices where Unit.lower(u[at + k]) != literal[k] { return false }
return true
}
func atStop() -> Bool {
switch stop {
case .phpClose: return peek() == Unit.question && peek(1) == Unit.greater
case let .closingTag(name):
guard peek() == Unit.less, peek(1) == Unit.slash else { return false }
return startsIgnoringCase(with: Array(name.utf16), at: i + 2)
case .fence, nil: return false
}
}
mutating func skipSpaces() {
while i < end && Unit.isSpace(u[i]) { i += 1 }
}
/// The first non-space unit from `j` on, or 0.
func nextNonSpace(from j: Int? = nil) -> UInt16 {
var k = j ?? i
while k < end && Unit.isSpace(u[k]) { k += 1 }
return k < end ? u[k] : 0
}
mutating func identifier(extra: (UInt16) -> Bool = { _ in false }) {
while i < end && (Unit.isIdentPart(u[i]) || extra(u[i])) { i += 1 }
}
/// A comment to the end of the line, or to the stop marker a PHP `?>` or `</script` sets.
mutating func lineComment() {
let start = i
if stop == nil {
i = end
} else {
while i < end && !atStop() { i += 1 }
}
emit(start, i, .comment)
}
/// Consumes up to and including `close`; returns false when the line ends first.
mutating func blockComment(from start: Int, close: [UInt16]) -> Bool {
while i < end {
if starts(with: close) {
i += close.count
emit(start, i, .comment)
return true
}
i += 1
}
emit(start, i, .comment)
return false
}
/// A string body up to the closing `quote`, with backslash escapes; false when the line ends first.
mutating func quoted(from start: Int, quote: UInt16, escapes: Bool = true, role: TokenRole = .string) -> Bool {
while i < end {
let c = u[i]
if escapes && c == Unit.backslash {
i += 2
continue
}
i += 1
if c == quote {
emit(start, i, role)
return true
}
}
i = min(i, end)
emit(start, i, role)
return false
}
/// A numeric literal: hex/octal/binary prefixes, `_` separators, fraction, exponent and a letter suffix.
mutating func number() {
let start = i
if peek() == Unit.zero && Unit.isAlpha(peek(1)) && "xXoObB".utf16.contains(peek(1)) {
i += 2
while i < end && (Unit.isHexDigit(u[i]) || u[i] == Unit.underscore) { i += 1 }
} else {
while i < end && (Unit.isDigit(u[i]) || u[i] == Unit.underscore) { i += 1 }
if peek() == Unit.dot && Unit.isDigit(peek(1)) {
i += 1
while i < end && (Unit.isDigit(u[i]) || u[i] == Unit.underscore) { i += 1 }
}
if (peek() == Unit.lowerE || peek() == Unit.upperE)
&& (Unit.isDigit(peek(1)) || ((peek(1) == Unit.plus || peek(1) == Unit.minus) && Unit.isDigit(peek(2)))) {
i += 2
while i < end && Unit.isDigit(u[i]) { i += 1 }
}
}
while i < end && Unit.isAlpha(u[i]) { i += 1 }
emit(start, i, .number)
}
/// Consumes a run of operator characters and paints it as a keyword.
mutating func operatorRun(_ isOperator: (UInt16) -> Bool = Unit.isOperator) {
let start = i
while i < end && isOperator(u[i]) { i += 1 }
emit(start, i, .keyword)
}
}
enum Literals {
static let blockClose = Unit.literal("*/")
static let heredoc = Unit.literal("<<<")
}
/// UTF-16 character classes. Every unit at or above 0x80 counts as an identifier letter,
/// which keeps surrogate pairs and non-ASCII names in one token.
enum Unit {
static let tab: UInt16 = 9, space: UInt16 = 32, bang: UInt16 = 33, quote: UInt16 = 34
static let hash: UInt16 = 35, dollar: UInt16 = 36, percent: UInt16 = 37, amp: UInt16 = 38
static let apostrophe: UInt16 = 39, lparen: UInt16 = 40, rparen: UInt16 = 41, star: UInt16 = 42
static let plus: UInt16 = 43, comma: UInt16 = 44, minus: UInt16 = 45, dot: UInt16 = 46
static let slash: UInt16 = 47, zero: UInt16 = 48, colon: UInt16 = 58, semicolon: UInt16 = 59
static let less: UInt16 = 60, equals: UInt16 = 61, greater: UInt16 = 62, question: UInt16 = 63
static let at: UInt16 = 64, upperE: UInt16 = 69, lbracket: UInt16 = 91, backslash: UInt16 = 92
static let rbracket: UInt16 = 93, caret: UInt16 = 94, underscore: UInt16 = 95, backtick: UInt16 = 96
static let lowerE: UInt16 = 101, lbrace: UInt16 = 123, pipe: UInt16 = 124, rbrace: UInt16 = 125
static let tilde: UInt16 = 126
@inline(__always) static func isDigit(_ c: UInt16) -> Bool { c &- 48 < 10 }
@inline(__always) static func isUpper(_ c: UInt16) -> Bool { c &- 65 < 26 }
@inline(__always) static func isLower(_ c: UInt16) -> Bool { c &- 97 < 26 }
@inline(__always) static func isAlpha(_ c: UInt16) -> Bool { isUpper(c) || isLower(c) }
@inline(__always) static func isHexDigit(_ c: UInt16) -> Bool { isDigit(c) || (c | 0x20) &- 97 < 6 }
@inline(__always) static func isIdentStart(_ c: UInt16) -> Bool { isAlpha(c) || c == underscore || c >= 0x80 }
@inline(__always) static func isIdentPart(_ c: UInt16) -> Bool { isIdentStart(c) || isDigit(c) }
@inline(__always) static func isSpace(_ c: UInt16) -> Bool { c == space || c == tab || c == 13 || c == 12 || c == 11 }
@inline(__always) static func lower(_ c: UInt16) -> UInt16 { isUpper(c) ? c + 32 : c }
static func isOperator(_ c: UInt16) -> Bool {
switch c {
case plus, minus, star, slash, percent, equals, amp, pipe, caret, bang, tilde, less, greater, question, colon: true
default: false
}
}
static func literal(_ text: String) -> [UInt16] { Array(text.utf16) }
}
@@ -0,0 +1,156 @@
import Foundation
/// Markdown, with fenced code in a known language highlighted by that language.
enum MarkdownGrammar {
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
let lineStart = lx.i
if case let .fence(marker, count) = st.mode {
fencedLine(&lx, &st, marker: marker, count: count)
return
}
lx.skipSpaces()
let c = lx.peek()
if (c == Unit.backtick || c == Unit.tilde), let count = run(lx, of: c), count >= 3 {
let info = lx.text(lx.i + count, lx.end).trimmingCharacters(in: .whitespaces)
let word = String(info.prefix { !$0.isWhitespace })
lx.i = lx.end
lx.emit(lineStart, lx.end, .comment)
st.mode = .fence(marker: c, count: count)
if let grammar = Grammar(MarkdownParser.fenceLanguage(word), text: "") {
st.child = .grammar(grammar, GrammarState(), until: .fence)
}
return
}
if c == Unit.hash, let count = run(lx, of: c), count <= 6, lx.unit(at: lx.i + count) == 0 || Unit.isSpace(lx.unit(at: lx.i + count)) {
lx.i = lx.end
lx.emit(lineStart, lx.end, .keyword)
return
}
if isRule(lx) {
lx.i = lx.end
lx.emit(lineStart, lx.end, .comment)
return
}
while lx.peek() == Unit.greater {
lx.emit(lx.i, lx.i + 1, .comment)
lx.i += 1
lx.skipSpaces()
}
listMarker(&lx)
inline(&lx)
}
private static func fencedLine(_ lx: inout Lexer, _ st: inout GrammarState, marker: UInt16, count: Int) {
let lineStart = lx.i
var k = lineStart
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
var closing = k
while closing < lx.end && lx.u[closing] == marker { closing += 1 }
var rest = closing
while rest < lx.end && Unit.isSpace(lx.u[rest]) { rest += 1 }
if closing - k >= count && rest == lx.end {
lx.i = lx.end
lx.emit(lineStart, lx.end, .comment)
st.mode = .code
st.child = nil
return
}
if case let .grammar(grammar, inner, _)? = st.child {
var state = inner
Grammars.scan(grammar, &lx, &state)
st.child = .grammar(grammar, state, until: .fence)
}
lx.i = lx.end
}
/// How many `c` in a row start at the cursor.
private static func run(_ lx: Lexer, of c: UInt16) -> Int? {
var k = lx.i
while k < lx.end && lx.u[k] == c { k += 1 }
return k - lx.i
}
/// Three or more of one of `-`, `*`, `_`, spaces allowed between them.
private static func isRule(_ lx: Lexer) -> Bool {
let first = lx.peek()
guard first == Unit.minus || first == Unit.star || first == Unit.underscore else { return false }
var marks = 0
for k in lx.i..<lx.end {
if lx.u[k] == first {
marks += 1
} else if !Unit.isSpace(lx.u[k]) {
return false
}
}
return marks >= 3
}
/// `-`, `*`, `+` or `1.`/`1)` followed by a space.
private static func listMarker(_ lx: inout Lexer) {
var k = lx.i
let c = lx.peek()
if c == Unit.minus || c == Unit.star || c == Unit.plus {
k += 1
} else {
while k < lx.end && Unit.isDigit(lx.u[k]) { k += 1 }
guard k > lx.i, lx.unit(at: k) == Unit.dot || lx.unit(at: k) == Unit.rparen else { return }
k += 1
}
guard Unit.isSpace(lx.unit(at: k)) else { return }
lx.emit(lx.i, k, .comment)
lx.i = k
}
/// Code spans, link targets and autolinks in running text.
private static func inline(_ lx: inout Lexer) {
while lx.i < lx.end {
let start = lx.i
let c = lx.u[start]
if c == Unit.backslash {
lx.i = min(lx.i + 2, lx.end)
} else if c == Unit.backtick {
let ticks = run(lx, of: c) ?? 1
if let close = findRun(lx, of: c, count: ticks, from: start + ticks) {
lx.i = close + ticks
lx.emit(start, lx.i, .keyword)
} else {
lx.i += ticks
}
} else if c == Unit.rbracket && lx.peek(1) == Unit.lparen {
lx.i += 1
let open = lx.i
while lx.i < lx.end && lx.u[lx.i] != Unit.rparen { lx.i += 1 }
lx.i = min(lx.i + 1, lx.end)
lx.emit(open, lx.i, .variable)
} else if c == Unit.less && Unit.isAlpha(lx.peek(1)) {
var k = start + 1
while k < lx.end && lx.u[k] != Unit.greater && !Unit.isSpace(lx.u[k]) { k += 1 }
if lx.unit(at: k) == Unit.greater && lx.text(start + 1, k).contains(":") {
lx.i = k + 1
lx.emit(start, lx.i, .variable)
} else {
lx.i += 1
}
} else {
lx.i += 1
}
}
}
/// The start of the next run of exactly `count` × `c` from `from`, or nil.
private static func findRun(_ lx: Lexer, of c: UInt16, count: Int, from: Int) -> Int? {
var k = from
while k < lx.end {
if lx.u[k] == c {
var e = k
while e < lx.end && lx.u[e] == c { e += 1 }
if e - k == count { return k }
k = e
} else {
k += 1
}
}
return nil
}
}
@@ -0,0 +1,155 @@
import Foundation
/// HTML, XML, SVG and Vue, plus the markup around `<?php` blocks in PHP files.
enum MarkupGrammar {
private static let commentOpen = Unit.literal("<!--")
private static let commentClose = Unit.literal("-->")
private static let cdataOpen = Unit.literal("<![cdata[")
private static let cdataClose = Unit.literal("]]>")
private static let phpOpenTags = [Unit.literal("<?php"), Unit.literal("<?="), Unit.literal("<?")]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState, phpIslands: Bool) {
while lx.i < lx.end {
switch st.mode {
case .markupComment:
if lx.blockComment(from: lx.i, close: commentClose) { st.mode = .code }
continue
case .cdata:
if lx.blockComment(from: lx.i, close: cdataClose) { st.mode = .code }
continue
case let .markupTag(name):
tag(&lx, &st, name: name, phpIslands: phpIslands)
if st.child != nil { return }
continue
case let .markupValue(quote, name):
value(&lx, &st, quote: quote, tag: name, from: lx.i, phpIslands: phpIslands)
if st.child != nil { return }
continue
default:
break
}
if lx.stop != nil && lx.atStop() { return }
if phpIslands && openIsland(&lx, &st) { return }
let start = lx.i
let c = lx.u[start]
if c == Unit.less {
openTag(&lx, &st)
} else if c == Unit.amp {
lx.i += 1
while lx.i < lx.end && (Unit.isIdentPart(lx.u[lx.i]) || lx.u[lx.i] == Unit.hash) { lx.i += 1 }
if lx.peek() == Unit.semicolon && lx.i > start + 1 {
lx.i += 1
lx.emit(start, lx.i, .variable)
}
} else {
lx.i += 1
while lx.i < lx.end && lx.u[lx.i] != Unit.less && lx.u[lx.i] != Unit.amp { lx.i += 1 }
}
}
}
/// Everything that starts with `<` in text: comments, CDATA, doctype, prolog and tags.
private static func openTag(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
if lx.starts(with: commentOpen) {
lx.i += commentOpen.count
if !lx.blockComment(from: start, close: commentClose) { st.mode = .markupComment }
return
}
if lx.startsIgnoringCase(with: cdataOpen) {
lx.i += cdataOpen.count
if !lx.blockComment(from: start, close: cdataClose) { st.mode = .cdata }
return
}
let next = lx.peek(1)
if next == Unit.bang || next == Unit.question {
let close = next == Unit.bang ? [Unit.greater] : [Unit.question, Unit.greater]
lx.i += 2
_ = lx.blockComment(from: start, close: close)
return
}
var k = start + 1
let closing = lx.unit(at: k) == Unit.slash
if closing { k += 1 }
guard Unit.isAlpha(lx.unit(at: k)) else {
lx.i += 1
return
}
let nameStart = k
while k < lx.end && (Unit.isIdentPart(lx.u[k]) || lx.u[k] == Unit.minus || lx.u[k] == Unit.colon || lx.u[k] == Unit.dot) { k += 1 }
lx.emit(nameStart, k, .number)
let name = lx.text(nameStart, k).lowercased()
lx.i = k
st.mode = .markupTag(closing ? "/" + name : name)
}
/// Attributes up to `>`; a `>` that closes `<script>` or `<style>` hands the body to JavaScript or CSS.
private static func tag(_ lx: inout Lexer, _ st: inout GrammarState, name: String, phpIslands: Bool) {
while lx.i < lx.end {
if phpIslands && openIsland(&lx, &st) { return }
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) || c == Unit.equals {
lx.i += 1
} else if c == Unit.greater {
lx.i += 1
st.mode = .code
switch name {
case "script": st.child = .grammar(.javascript(typescript: false, jsx: false), GrammarState(), until: .closingTag("script"))
case "style": st.child = .grammar(.css, GrammarState(), until: .closingTag("style"))
default: break
}
return
} else if c == Unit.slash && lx.peek(1) == Unit.greater {
lx.i += 2
st.mode = .code
return
} else if c == Unit.quote || c == Unit.apostrophe {
lx.i += 1
value(&lx, &st, quote: c, tag: name, from: start, phpIslands: phpIslands)
if st.child != nil || st.mode != .markupTag(name) { return }
} else if c == Unit.slash {
lx.i += 1
} else {
while lx.i < lx.end && !isAttributeEnd(lx.u[lx.i]) { lx.i += 1 }
lx.emit(start, lx.i, lx.unit(at: start - 1) == Unit.equals ? .string : .variable)
}
}
}
private static func isAttributeEnd(_ c: UInt16) -> Bool {
Unit.isSpace(c) || c == Unit.equals || c == Unit.greater || c == Unit.slash || c == Unit.quote || c == Unit.apostrophe
}
/// A quoted attribute value; it may run over lines and may hold a PHP island.
private static func value(_ lx: inout Lexer, _ st: inout GrammarState, quote: UInt16, tag: String, from start: Int, phpIslands: Bool) {
while lx.i < lx.end {
if phpIslands && lx.peek() == Unit.less && lx.peek(1) == Unit.question {
lx.emit(start, lx.i, .string)
st.mode = .markupValue(quote: quote, tag: tag)
_ = openIsland(&lx, &st)
return
}
if lx.u[lx.i] == quote {
lx.i += 1
lx.emit(start, lx.i, .string)
st.mode = .markupTag(tag)
return
}
lx.i += 1
}
lx.emit(start, lx.i, .string)
st.mode = .markupValue(quote: quote, tag: tag)
}
/// `<?php`, `<?=` or `<?` starts a PHP island that runs until `?>`.
private static func openIsland(_ lx: inout Lexer, _ st: inout GrammarState) -> Bool {
guard lx.peek() == Unit.less, lx.peek(1) == Unit.question else { return false }
let start = lx.i
let open = phpOpenTags.first { lx.startsIgnoringCase(with: $0) } ?? phpOpenTags[2]
lx.i += open.count
lx.emit(start, lx.i, .keyword)
st.child = .grammar(.php, GrammarState(), until: .phpClose)
return true
}
}
@@ -0,0 +1,265 @@
import Foundation
enum PHPGrammar {
/// Matched lowercase: PHP keywords are case-insensitive.
static let keywords: Set<String> = [
"abstract", "and", "array", "as", "break", "callable", "case", "catch", "class", "clone", "const",
"continue", "declare", "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare",
"endfor", "endforeach", "endif", "endswitch", "endwhile", "enum", "eval", "exit", "extends",
"final", "finally", "fn", "for", "foreach", "from", "function", "global", "goto", "if",
"implements", "include", "include_once", "instanceof", "insteadof", "interface", "isset", "list",
"match", "namespace", "new", "or", "parent", "print", "private", "protected", "public", "readonly",
"require", "require_once", "return", "self", "static", "switch", "throw", "trait", "try", "unset",
"use", "var", "while", "xor", "yield",
"int", "float", "string", "bool", "void", "mixed", "never", "iterable", "object",
]
static let constants: Set<String> = ["true", "false", "null"]
/// Keywords after which the next name is a class.
private static let classIntroducers: Set<String> = [
"class", "interface", "trait", "enum", "extends", "implements", "instanceof", "insteadof", "new",
]
private static let scopeKeywords: Set<String> = ["self", "static", "parent"]
private static let openTags = [Unit.literal("<?php"), Unit.literal("<?="), Unit.literal("<?")]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
var classNext = false
var namespaceNext = false
var afterArrow = false
var afterDoubleColon = false
while lx.i < lx.end {
switch st.mode {
case .blockComment:
if lx.blockComment(from: lx.i, close: Literals.blockClose) { st.mode = .code }
continue
case let .quoted(quote):
if interpolated(&lx, from: lx.i, close: quote, interpolates: quote != Unit.apostrophe) { st.mode = .code }
continue
case let .heredoc(id, interpolates):
heredocLine(&lx, &st, id: id, interpolates: interpolates)
continue
default:
break
}
if lx.stop != nil && lx.atStop() { return }
let c = lx.u[lx.i]
let start = lx.i
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.hash where lx.peek(1) == Unit.lbracket:
lx.i += 2
classNext = true
continue
case Unit.hash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.slash:
lx.lineComment()
case Unit.slash where lx.peek(1) == Unit.star:
lx.i += 2
if !lx.blockComment(from: start, close: Literals.blockClose) { st.mode = .blockComment }
case Unit.apostrophe, Unit.quote, Unit.backtick:
lx.i += 1
if !interpolated(&lx, from: start, close: c, interpolates: c != Unit.apostrophe) { st.mode = .quoted(c) }
case Unit.less where lx.starts(with: Literals.heredoc):
heredocStart(&lx, &st)
case Unit.less where lx.peek(1) == Unit.question:
let tag = openTags.first { lx.startsIgnoringCase(with: $0) } ?? openTags[2]
lx.i += tag.count
lx.emit(start, lx.i, .keyword)
case Unit.question where lx.peek(1) == Unit.greater:
lx.i += 2
lx.emit(start, lx.i, .keyword)
case Unit.dollar where Unit.isIdentStart(lx.peek(1)) || lx.peek(1) == Unit.dollar:
while lx.peek() == Unit.dollar { lx.i += 1 }
lx.identifier()
lx.emit(start, lx.i, .variable)
case _ where Unit.isDigit(c) || (c == Unit.dot && Unit.isDigit(lx.peek(1))):
lx.number()
case Unit.minus where lx.peek(1) == Unit.greater, Unit.question where lx.peek(1) == Unit.minus && lx.peek(2) == Unit.greater:
lx.i += c == Unit.question ? 3 : 2
lx.emit(start, lx.i, .keyword)
afterArrow = true
continue
case Unit.colon where lx.peek(1) == Unit.colon:
lx.i += 2
lx.emit(start, lx.i, .keyword)
afterDoubleColon = true
continue
case _ where Unit.isIdentStart(c) || (c == Unit.backslash && Unit.isIdentStart(lx.peek(1))):
name(&lx, classNext: &classNext, namespaceNext: &namespaceNext, afterArrow: afterArrow, afterDoubleColon: afterDoubleColon)
case _ where Unit.isOperator(c) || c == Unit.dot || c == Unit.at:
lx.operatorRun { Unit.isOperator($0) || $0 == Unit.dot || $0 == Unit.at }
default:
lx.i += 1
}
afterArrow = false
afterDoubleColon = false
}
}
/// A name, possibly qualified (`\App\Models\Agent`): the namespace path reads as a string,
/// the last segment as a keyword, class, constant or function.
private static func name(_ lx: inout Lexer, classNext: inout Bool, namespaceNext: inout Bool, afterArrow: Bool, afterDoubleColon: Bool) {
let start = lx.i
var lastSegment = start
while lx.i < lx.end {
if lx.u[lx.i] == Unit.backslash && Unit.isIdentStart(lx.peek(1)) {
lx.i += 1
lastSegment = lx.i
} else if Unit.isIdentPart(lx.u[lx.i]) {
lx.i += 1
} else {
break
}
}
if lx.peek() == Unit.backslash {
// A group import, `use App\Models\{A, B}`: the whole prefix is a path.
lx.i += 1
lx.emit(start, lx.i, .string)
return
}
let end = lx.i
let qualified = lastSegment > start
if namespaceNext {
namespaceNext = false
lx.emit(start, end, .string)
return
}
lx.emit(start, lastSegment, .string)
let word = lx.text(lastSegment, end)
let next = lx.nextNonSpace()
let callsNext = next == Unit.lparen
if afterArrow {
lx.emit(lastSegment, end, callsNext ? .plain : .variable)
return
}
if afterDoubleColon {
let lower = word.lowercased()
if lower == "class" {
lx.emit(lastSegment, end, .keyword)
} else if !callsNext && JavaScriptGrammar.isConstantName(lx, lastSegment, end) {
lx.emit(lastSegment, end, .number)
}
return
}
if !qualified {
let lower = word.lowercased()
if constants.contains(lower) {
lx.emit(lastSegment, end, .number)
return
}
if scopeKeywords.contains(lower) {
lx.emit(lastSegment, end, .keyword)
return
}
if keywords.contains(lower) && !(lx.peek() == Unit.colon && lx.peek(1) == Unit.colon) {
lx.emit(lastSegment, end, .keyword)
classNext = classIntroducers.contains(lower)
namespaceNext = lower == "namespace"
return
}
}
let followedByScope = lx.peek() == Unit.colon && lx.peek(1) == Unit.colon
let isConstant = JavaScriptGrammar.isConstantName(lx, lastSegment, end)
let looksLikeClass = Unit.isUpper(lx.u[lastSegment]) && !isConstant && !callsNext
if classNext || followedByScope || looksLikeClass {
lx.emit(lastSegment, end, lx.symbols.contains(word) ? .symbol : .variable)
} else if isConstant && !callsNext {
lx.emit(lastSegment, end, .number)
}
classNext = false
}
/// A string body with `$var`, `$var->prop` and `{$…}` interpolation; false when the line ends first.
/// With `close` 0 it runs to the end of the line, for heredoc bodies.
static func interpolated(_ lx: inout Lexer, from start: Int, close: UInt16, interpolates: Bool) -> Bool {
var runStart = start
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.backslash && close != 0 {
lx.i = min(lx.i + 2, lx.end)
continue
}
if c == close {
lx.i += 1
lx.emit(runStart, lx.i, .string)
return true
}
if interpolates && c == Unit.dollar && Unit.isIdentStart(lx.peek(1)) {
lx.emit(runStart, lx.i, .string)
let varStart = lx.i
lx.i += 1
lx.identifier()
if lx.peek() == Unit.minus && lx.peek(1) == Unit.greater && Unit.isIdentStart(lx.peek(2)) {
lx.i += 2
lx.identifier()
}
lx.emit(varStart, lx.i, .variable)
runStart = lx.i
continue
}
if interpolates && c == Unit.lbrace && lx.peek(1) == Unit.dollar {
lx.emit(runStart, lx.i, .string)
let varStart = lx.i
var depth = 0
while lx.i < lx.end {
if lx.u[lx.i] == Unit.lbrace { depth += 1 }
if lx.u[lx.i] == Unit.rbrace {
depth -= 1
if depth == 0 {
lx.i += 1
break
}
}
lx.i += 1
}
lx.emit(varStart, lx.i, .variable)
runStart = lx.i
continue
}
lx.i += 1
}
lx.emit(runStart, lx.i, .string)
return false
}
/// `<<<ID`, `<<<"ID"` or `<<<'ID'` (nowdoc): the rest of the line and every line up to the marker.
private static func heredocStart(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
var k = start + 3
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let quote = lx.unit(at: k)
let quoted = quote == Unit.apostrophe || quote == Unit.quote
if quoted { k += 1 }
let idStart = k
while k < lx.end && Unit.isIdentPart(lx.u[k]) { k += 1 }
guard k > idStart else {
lx.i = start + 3
lx.emit(start, lx.i, .keyword)
return
}
let id = lx.text(idStart, k)
if quoted && lx.unit(at: k) == quote { k += 1 }
lx.i = k
lx.emit(start, k, .string)
st.mode = .heredoc(id: id, interpolates: quote != Unit.apostrophe)
}
/// One heredoc body line; the closing marker may be indented and followed by code.
private static func heredocLine(_ lx: inout Lexer, _ st: inout GrammarState, id: String, interpolates: Bool) {
let start = lx.i
var k = start
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let marker = Array(id.utf16)
if lx.starts(with: marker, at: k) && !Unit.isIdentPart(lx.unit(at: k + marker.count)) {
lx.i = k + marker.count
lx.emit(start, lx.i, .string)
st.mode = .code
return
}
_ = interpolated(&lx, from: start, close: 0, interpolates: interpolates)
}
}
@@ -0,0 +1,109 @@
import Foundation
enum PythonGrammar {
static let keywords: Set<String> = [
"and", "as", "assert", "async", "await", "break", "case", "class", "continue", "def", "del",
"elif", "else", "except", "exec", "finally", "for", "from", "global", "if", "import", "in", "is",
"lambda", "match", "nonlocal", "not", "or", "pass", "print", "raise", "return", "try", "while",
"with", "yield",
]
/// Builtins and the three constants, painted in the number colour.
static let builtins: Set<String> = [
"True", "False", "None", "abs", "all", "any", "ascii", "bin", "bool", "bytearray", "bytes",
"callable", "chr", "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
"enumerate", "eval", "filter", "float", "format", "frozenset", "getattr", "globals", "hasattr",
"hash", "help", "hex", "id", "input", "int", "isinstance", "issubclass", "iter", "len", "list",
"locals", "map", "max", "memoryview", "min", "next", "object", "oct", "open", "ord", "pow",
"property", "range", "repr", "reversed", "round", "set", "setattr", "slice", "sorted",
"staticmethod", "str", "sum", "super", "tuple", "type", "vars", "zip", "__import__",
]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
var classNext = false
while lx.i < lx.end {
if case let .triple(quote) = st.mode {
if triple(&lx, from: lx.i, quote: quote) { st.mode = .code }
continue
}
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) {
lx.i += 1
continue
}
if let quote = stringQuote(lx) {
lx.i = quote.bodyStart
if quote.isTriple {
if !triple(&lx, from: start, quote: quote.unit) { st.mode = .triple(quote.unit) }
} else {
_ = lx.quoted(from: start, quote: quote.unit)
}
classNext = false
continue
}
switch c {
case Unit.hash:
lx.lineComment()
case Unit.at where Unit.isIdentStart(lx.peek(1)) && isLineStart(lx, start):
lx.i += 1
lx.identifier { $0 == Unit.dot }
lx.emit(start, lx.i, .keyword)
case _ where Unit.isDigit(c) || (c == Unit.dot && Unit.isDigit(lx.peek(1))):
lx.number()
case _ where Unit.isIdentStart(c):
lx.identifier()
let word = lx.text(start, lx.i)
if keywords.contains(word) {
lx.emit(start, lx.i, .keyword)
classNext = word == "class"
continue
}
if classNext {
lx.emit(start, lx.i, .variable)
} else if builtins.contains(word) {
lx.emit(start, lx.i, .number)
}
case _ where Unit.isOperator(c) && c != Unit.colon:
lx.operatorRun { Unit.isOperator($0) && $0 != Unit.colon }
default:
lx.i += 1
}
classNext = false
}
}
private static func isLineStart(_ lx: Lexer, _ j: Int) -> Bool {
var k = j - 1
while k >= 0 && Unit.isSpace(lx.u[k]) { k -= 1 }
return k < 0 || lx.u[k] == 10
}
/// A string opener at the cursor, with its `r`/`b`/`f`/`u` prefix.
private static func stringQuote(_ lx: Lexer) -> (unit: UInt16, isTriple: Bool, bodyStart: Int)? {
var k = lx.i
while k - lx.i < 2 && k < lx.end && "rRbBuUfF".utf16.contains(lx.u[k]) { k += 1 }
if k > lx.i && Unit.isIdentPart(lx.unit(at: lx.i - 1)) { return nil }
let q = lx.unit(at: k)
guard q == Unit.quote || q == Unit.apostrophe else { return nil }
if lx.unit(at: k + 1) == q && lx.unit(at: k + 2) == q { return (q, true, k + 3) }
return (q, false, k + 1)
}
/// A triple-quoted body up to its closing three quotes; false when the line ends first.
private static func triple(_ lx: inout Lexer, from start: Int, quote: UInt16) -> Bool {
while lx.i < lx.end {
if lx.u[lx.i] == Unit.backslash {
lx.i = min(lx.i + 2, lx.end)
continue
}
if lx.u[lx.i] == quote && lx.peek(1) == quote && lx.peek(2) == quote {
lx.i += 3
lx.emit(start, lx.i, .string)
return true
}
lx.i += 1
}
lx.emit(start, lx.i, .string)
return false
}
}
@@ -0,0 +1,187 @@
import Foundation
/// Shell scripts, and `.env` files.
enum ShellGrammar {
static let keywords: Set<String> = [
"if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case", "esac", "in",
"function", "select", "time", "return", "local", "export", "readonly", "declare", "unset", "shift",
"break", "continue", "exit", "source", "alias", "typeset", "let", "eval",
]
/// Painted in the number colour.
static let builtins: Set<String> = [
"echo", "cd", "pwd", "printf", "read", "test", "set", "trap", "wait", "kill", "exec", "true",
"false", "type", "hash", "getopts", "umask", "ulimit", "command", "builtin", "jobs", "fg", "bg",
"pushd", "popd", "dirs", "history", "shopt", "mapfile",
]
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
let lineStart = lx.i
while lx.i < lx.end {
switch st.mode {
case let .quoted(quote):
if string(&lx, from: lx.i, quote: quote) { st.mode = .code }
continue
case let .heredoc(id, interpolates):
heredocLine(&lx, &st, id: id, interpolates: interpolates)
continue
default:
break
}
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.hash where start == lineStart || isWordBreak(lx.unit(at: start - 1)):
lx.lineComment()
case Unit.apostrophe, Unit.quote:
lx.i += 1
if !string(&lx, from: start, quote: c) { st.mode = .quoted(c) }
case Unit.dollar:
variable(&lx)
case Unit.less where lx.peek(1) == Unit.less && lx.peek(2) != Unit.less:
heredocStart(&lx, &st)
case _ where isOperator(c):
lx.operatorRun(isOperator)
case _ where isWordBreak(c):
lx.i += 1
default:
word(&lx, atCommandStart: start == lineStart || isWordBreak(lx.unit(at: start - 1)))
}
}
}
private static func isOperator(_ c: UInt16) -> Bool {
c == Unit.less || c == Unit.greater || c == Unit.equals || c == Unit.bang || c == Unit.amp || c == Unit.pipe
}
private static func isWordBreak(_ c: UInt16) -> Bool {
switch c {
case Unit.space, Unit.tab, Unit.pipe, Unit.amp, Unit.semicolon, Unit.lparen, Unit.rparen,
Unit.less, Unit.greater, Unit.lbrace, Unit.rbrace, Unit.backtick, 13: true
default: false
}
}
/// One shell word: `NAME=` assigns, a bare keyword or builtin is coloured, digits are a number.
private static func word(_ lx: inout Lexer, atCommandStart: Bool) {
let start = lx.i
while lx.i < lx.end && Unit.isIdentPart(lx.u[lx.i]) { lx.i += 1 }
let identEnd = lx.i
if identEnd > start && atCommandStart && lx.peek() == Unit.equals && !Unit.isDigit(lx.u[start]) {
lx.emit(start, identEnd, .variable)
return
}
while lx.i < lx.end && !isWordBreak(lx.u[lx.i]) && !isQuoteOrDollar(lx.u[lx.i]) { lx.i += 1 }
guard lx.i == identEnd, identEnd > start else {
if lx.i == start { lx.i += 1 }
return
}
let text = lx.text(start, identEnd)
if keywords.contains(text) {
lx.emit(start, identEnd, .keyword)
} else if builtins.contains(text) || text.utf16.allSatisfy(Unit.isDigit) {
lx.emit(start, identEnd, .number)
}
}
private static func isQuoteOrDollar(_ c: UInt16) -> Bool {
c == Unit.quote || c == Unit.apostrophe || c == Unit.dollar
}
/// `$name`, `$1`, `$@`, `${…}`; `$(` is left plain for the command inside it.
private static func variable(_ lx: inout Lexer) {
let start = lx.i
lx.i += 1
let next = lx.peek()
if next == Unit.lbrace {
while lx.i < lx.end && lx.u[lx.i] != Unit.rbrace { lx.i += 1 }
lx.i = min(lx.i + 1, lx.end)
} else if Unit.isIdentStart(next) {
lx.identifier()
} else if Unit.isDigit(next) || "@*#?$!-".utf16.contains(next) {
lx.i += 1
} else {
return
}
lx.emit(start, lx.i, .variable)
}
/// A quoted body; double quotes interpolate `$…`. False when the line ends first.
private static func string(_ lx: inout Lexer, from start: Int, quote: UInt16) -> Bool {
var runStart = start
while lx.i < lx.end {
let c = lx.u[lx.i]
if quote == Unit.quote && c == Unit.backslash {
lx.i = min(lx.i + 2, lx.end)
continue
}
if c == quote {
lx.i += 1
lx.emit(runStart, lx.i, .string)
return true
}
if quote == Unit.quote && c == Unit.dollar && (Unit.isIdentStart(lx.peek(1)) || lx.peek(1) == Unit.lbrace) {
lx.emit(runStart, lx.i, .string)
variable(&lx)
runStart = lx.i
continue
}
lx.i += 1
}
lx.emit(runStart, lx.i, .string)
return false
}
/// `<<ID`, `<<-ID`, `<<'ID'` or `<<"ID"`; a quoted marker turns interpolation off.
private static func heredocStart(_ lx: inout Lexer, _ st: inout GrammarState) {
let start = lx.i
var k = start + 2
if lx.unit(at: k) == Unit.minus { k += 1 }
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let quote = lx.unit(at: k)
let quoted = quote == Unit.apostrophe || quote == Unit.quote
if quoted { k += 1 }
let idStart = k
while k < lx.end && Unit.isIdentPart(lx.u[k]) { k += 1 }
guard k > idStart else {
lx.i = start + 2
lx.emit(start, lx.i, .keyword)
return
}
let id = lx.text(idStart, k)
if quoted && lx.unit(at: k) == quote { k += 1 }
lx.emit(start, idStart - (quoted ? 1 : 0), .keyword)
lx.emit(idStart - (quoted ? 1 : 0), k, .string)
lx.i = k
st.mode = .heredoc(id: id, interpolates: !quoted)
}
private static func heredocLine(_ lx: inout Lexer, _ st: inout GrammarState, id: String, interpolates: Bool) {
let start = lx.i
var k = start
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let marker = Array(id.utf16)
if lx.starts(with: marker, at: k) && k + marker.count == lx.end {
lx.i = lx.end
lx.emit(start, lx.i, .string)
st.mode = .code
return
}
var runStart = start
while lx.i < lx.end {
if interpolates && lx.u[lx.i] == Unit.dollar {
lx.emit(runStart, lx.i, .string)
let before = lx.i
variable(&lx)
if lx.i == before { lx.i += 1 }
runStart = lx.i
continue
}
lx.i += 1
}
lx.emit(runStart, lx.i, .string)
}
}
@@ -0,0 +1,236 @@
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)
}
}
}
@@ -0,0 +1,113 @@
import Foundation
enum YAMLGrammar {
static func scan(_ lx: inout Lexer, _ st: inout GrammarState) {
let lineStart = lx.i
var k = lineStart
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
let indent = k - lineStart
if case let .yamlBlock(parent) = st.mode {
if k == lx.end { return }
if indent > parent {
lx.i = lx.end
lx.emit(k, lx.end, .string)
return
}
st.mode = .code
}
var flow = 0
while lx.i < lx.end {
let start = lx.i
let c = lx.u[start]
if Unit.isSpace(c) {
lx.i += 1
continue
}
switch c {
case Unit.hash where start == lineStart || Unit.isSpace(lx.unit(at: start - 1)):
lx.lineComment()
case Unit.minus where isIndicator(lx, start + 1):
lx.i += 1
case Unit.quote, Unit.apostrophe:
var k = start + 1
while k < lx.end && lx.u[k] != c {
k += c == Unit.quote && lx.u[k] == Unit.backslash ? 2 : 1
}
lx.i = min(k + 1, lx.end)
lx.emit(start, lx.i, isKeyColon(lx, lx.i) ? .keyword : .string)
case Unit.amp, Unit.star:
lx.i += 1
while lx.i < lx.end && !Unit.isSpace(lx.u[lx.i]) && !isFlowPunctuation(lx.u[lx.i]) { lx.i += 1 }
lx.emit(start, lx.i, .keyword)
case Unit.bang:
while lx.i < lx.end && !Unit.isSpace(lx.u[lx.i]) { lx.i += 1 }
lx.emit(start, lx.i, .number)
case Unit.lbracket, Unit.lbrace:
flow += 1
lx.i += 1
case Unit.rbracket, Unit.rbrace:
flow = max(0, flow - 1)
lx.i += 1
case Unit.comma where flow > 0:
lx.i += 1
case Unit.pipe where isBlockIndicator(lx, start), Unit.greater where isBlockIndicator(lx, start):
lx.i = lx.end
st.mode = .yamlBlock(indent: indent)
default:
scalar(&lx, inFlow: flow > 0)
}
}
}
/// A `-` or `?` followed by a space or the line end.
private static func isIndicator(_ lx: Lexer, _ next: Int) -> Bool {
next >= lx.end || Unit.isSpace(lx.u[next])
}
private static func isFlowPunctuation(_ c: UInt16) -> Bool {
c == Unit.comma || c == Unit.rbracket || c == Unit.rbrace
}
/// A `:` right at `j` that ends a key.
private static func isKeyColon(_ lx: Lexer, _ j: Int) -> Bool {
lx.unit(at: j) == Unit.colon && isIndicator(lx, j + 1)
}
/// `|` or `>` with optional chomping/indent flags, then only a comment or nothing.
private static func isBlockIndicator(_ lx: Lexer, _ j: Int) -> Bool {
var k = j + 1
while k < lx.end && (lx.u[k] == Unit.minus || lx.u[k] == Unit.plus || Unit.isDigit(lx.u[k])) { k += 1 }
while k < lx.end && Unit.isSpace(lx.u[k]) { k += 1 }
return k == lx.end || lx.u[k] == Unit.hash
}
/// A plain scalar: a key when a `: ` follows, else a boolean, null, number or plain text.
private static func scalar(_ lx: inout Lexer, inFlow: Bool) {
let start = lx.i
var lastSolid = start
while lx.i < lx.end {
let c = lx.u[lx.i]
if c == Unit.colon && isIndicator(lx, lx.i + 1) { break }
if c == Unit.hash && lx.i > start && Unit.isSpace(lx.u[lx.i - 1]) { break }
if inFlow && isFlowPunctuation(c) { break }
if !Unit.isSpace(c) { lastSolid = lx.i + 1 }
lx.i += 1
}
if lx.i == start {
lx.i += 1
return
}
if isKeyColon(lx, lx.i) {
lx.emit(start, lastSolid, .keyword)
lx.i += 1
return
}
let value = lx.text(start, lastSolid).lowercased()
if value == "true" || value == "false" || value == "null" || value == "~" {
lx.emit(start, lastSolid, .keyword)
} else if value.wholeMatch(of: /[+-]?(?:0x[0-9a-f]+|0o[0-7]+|(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?|\.inf|\.nan)/) != nil {
lx.emit(start, lastSolid, .number)
}
}
}