import Foundation enum PythonGrammar { static let keywords: Set = [ "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 = [ "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 } }