SPB Git

Repository Public License

Expression.swift 9.9 KB 256 lines swift

1import Foundation2import PrismCore34/// The typed expression language of ADR 0003, rung 1: pure, total, budgeted. No loops, no I/O.5public indirect enum Expr: Sendable, Hashable {6    case literal(JSONValue)7    case identifier(String)8    case member(Expr, String)9    case index(Expr, Expr)10    case call(String, [Expr])11    case unary(String, Expr)12    case binary(String, Expr, Expr)13    case conditional(Expr, Expr, Expr)14}1516public struct ExpressionError: Error, LocalizedError, Sendable, Equatable {17    public let message: String18    public init(_ message: String) { self.message = message }19    public var errorDescription: String? { message }20}2122public struct Expression: Sendable, Hashable {23    public let source: String24    public let root: Expr2526    public init(_ source: String) throws {27        self.source = source28        var parser = Parser(source)29        self.root = try parser.parseAll()30        guard Expression.depth(of: root, limit: Expression.maxDepth) <= Expression.maxDepth else {31            throw ExpressionError("The expression is too long or nested too deeply.")32        }33    }3435    /// Evaluation recurses once per level, so depth is capped to keep the stack small.36    public static let maxDepth = 1203738    static func depth(of e: Expr, limit: Int) -> Int {39        // Iterative so that measuring a hostile tree cannot itself overflow the stack.40        var stack: [(Expr, Int)] = [(e, 1)]41        var deepest = 042        while let (node, d) = stack.popLast() {43            deepest = max(deepest, d)44            if deepest > limit { return deepest }45            switch node {46            case .literal, .identifier: break47            case .member(let b, _), .unary(_, let b): stack.append((b, d + 1))48            case .index(let a, let b), .binary(_, let a, let b): stack.append((a, d + 1)); stack.append((b, d + 1))49            case .call(_, let args): for a in args { stack.append((a, d + 1)) }50            case .conditional(let a, let b, let c): stack.append((a, d + 1)); stack.append((b, d + 1)); stack.append((c, d + 1))51            }52        }53        return deepest54    }5556    /// Every `root.member` path read by the expression, e.g. `state.filter`, `queries.totals`, `row.amount`.57    public var references: Set<String> {58        var out = Set<String>()59        func walk(_ e: Expr) {60            switch e {61            case .literal: break62            case .identifier(let n): out.insert(n)63            case .member(.identifier(let r), let m): out.insert("\(r).\(m)")64            case .member(let b, _): walk(b)65            case .index(let a, let b): walk(a); walk(b)66            case .call(_, let args): args.forEach(walk)67            case .unary(_, let a): walk(a)68            case .binary(_, let a, let b): walk(a); walk(b)69            case .conditional(let a, let b, let c): walk(a); walk(b); walk(c)70            }71        }72        walk(root)73        return out74    }7576    /// Names of functions called, for validation against the library.77    public var calledFunctions: Set<String> {78        var out = Set<String>()79        func walk(_ e: Expr) {80            switch e {81            case .literal, .identifier: break82            case .member(let b, _): walk(b)83            case .index(let a, let b): walk(a); walk(b)84            case .call(let n, let args): out.insert(n); args.forEach(walk)85            case .unary(_, let a): walk(a)86            case .binary(_, let a, let b): walk(a); walk(b)87            case .conditional(let a, let b, let c): walk(a); walk(b); walk(c)88            }89        }90        walk(root)91        return out92    }93}9495// MARK: - Lexer and parser9697enum Token: Equatable {98    case number(JSONValue), string(String), ident(String), op(String), end99}100101struct Parser {102    private var tokens: [Token] = []103    private var pos = 0104    private let lexError: ExpressionError?105106    init(_ source: String) {107        do { tokens = try Parser.lex(source); lexError = nil } catch { tokens = [.end]; lexError = error as? ExpressionError }108    }109110    static func lex(_ source: String) throws -> [Token] {111        guard source.utf8.count <= 4000 else { throw ExpressionError("The expression is too long.") }112        let chars = Array(source)113        var i = 0114        var out: [Token] = []115        while i < chars.count {116            let c = chars[i]117            if c.isWhitespace { i += 1; continue }118            if c.isNumber && c.isASCII {119                var j = i, isDouble = false120                while j < chars.count, (chars[j].isNumber && chars[j].isASCII) || chars[j] == "." {121                    if chars[j] == "." {122                        guard j + 1 < chars.count, chars[j + 1].isNumber, !isDouble else { break }123                        isDouble = true124                    }125                    j += 1126                }127                let text = String(chars[i..<j])128                if isDouble, let d = Double(text) { out.append(.number(.double(d))) }129                else if let n = Int(text) { out.append(.number(.int(n))) }130                else { throw ExpressionError("`\(text)` is not a number.") }131                i = j132                continue133            }134            if c.isLetter || c == "_" {135                var j = i136                while j < chars.count, chars[j].isLetter || chars[j].isNumber || chars[j] == "_" { j += 1 }137                out.append(.ident(String(chars[i..<j])))138                i = j139                continue140            }141            if c == "'" || c == "\"" {142                var j = i + 1, text = ""143                while j < chars.count, chars[j] != c {144                    if chars[j] == "\\", j + 1 < chars.count {145                        let n = chars[j + 1]146                        text.append(n == "n" ? "\n" : n == "t" ? "\t" : n)147                        j += 2148                    } else { text.append(chars[j]); j += 1 }149                }150                guard j < chars.count else { throw ExpressionError("A text value is missing its closing quote.") }151                out.append(.string(text))152                i = j + 1153                continue154            }155            let two = i + 1 < chars.count ? String(chars[i...i + 1]) : ""156            if ["==", "!=", "<=", ">=", "&&", "||"].contains(two) { out.append(.op(two)); i += 2; continue }157            if "+-*/%<>!?:(),.[]".contains(c) { out.append(.op(String(c))); i += 1; continue }158            throw ExpressionError("Unexpected character `\(c)`.")159        }160        out.append(.end)161        return out162    }163164    private var peek: Token { tokens[pos] }165    private mutating func advance() -> Token { defer { if pos < tokens.count - 1 { pos += 1 } }; return tokens[pos] }166    private mutating func eat(_ op: String) -> Bool { if peek == .op(op) { _ = advance(); return true }; return false }167    private mutating func expect(_ op: String) throws {168        guard eat(op) else { throw ExpressionError("Expected `\(op)`.") }169    }170171    mutating func parseAll() throws -> Expr {172        if let lexError { throw lexError }173        guard peek != .end else { throw ExpressionError("The expression is empty.") }174        let e = try ternary(depth: 0)175        guard peek == .end else { throw ExpressionError("Unexpected text after the expression.") }176        return e177    }178179    private func guardDepth(_ depth: Int) throws {180        guard depth < 64 else { throw ExpressionError("The expression is nested too deeply.") }181    }182183    private mutating func ternary(depth: Int) throws -> Expr {184        try guardDepth(depth)185        let cond = try binary(0, depth: depth)186        guard eat("?") else { return cond }187        let a = try ternary(depth: depth + 1)188        try expect(":")189        let b = try ternary(depth: depth + 1)190        return .conditional(cond, a, b)191    }192193    private static let levels: [[String]] = [["||"], ["&&"], ["==", "!="], ["<", "<=", ">", ">="], ["+", "-"], ["*", "/", "%"]]194195    private mutating func binary(_ level: Int, depth: Int) throws -> Expr {196        try guardDepth(depth)197        guard level < Parser.levels.count else { return try unary(depth: depth) }198        var left = try binary(level + 1, depth: depth)199        while case .op(let o) = peek, Parser.levels[level].contains(o) {200            _ = advance()201            left = .binary(o, left, try binary(level + 1, depth: depth))202        }203        return left204    }205206    private mutating func unary(depth: Int) throws -> Expr {207        try guardDepth(depth)208        if eat("!") { return .unary("!", try unary(depth: depth + 1)) }209        if eat("-") { return .unary("-", try unary(depth: depth + 1)) }210        return try postfix(depth: depth)211    }212213    private mutating func postfix(depth: Int) throws -> Expr {214        var e = try primary(depth: depth)215        while true {216            if eat(".") {217                guard case .ident(let name) = advance() else { throw ExpressionError("Expected a name after `.`.") }218                e = .member(e, name)219            } else if eat("[") {220                let i = try ternary(depth: depth + 1)221                try expect("]")222                e = .index(e, i)223            } else { return e }224        }225    }226227    private mutating func primary(depth: Int) throws -> Expr {228        switch advance() {229        case .number(let n): return .literal(n)230        case .string(let s): return .literal(.string(s))231        case .ident(let name):232            switch name {233            case "true": return .literal(.bool(true))234            case "false": return .literal(.bool(false))235            case "null": return .literal(.null)236            default: break237            }238            if eat("(") {239                var args: [Expr] = []240                if !eat(")") {241                    repeat { args.append(try ternary(depth: depth + 1)) } while eat(",")242                    try expect(")")243                }244                return .call(name, args)245            }246            return .identifier(name)247        case .op("("):248            let e = try ternary(depth: depth + 1)249            try expect(")")250            return e251        case .end: throw ExpressionError("The expression ends too early.")252        case .op(let o): throw ExpressionError("Unexpected `\(o)`.")253        }254    }255}256
Files main
Menu

Theme