SPB Git

Repository Public License

Evaluator.swift 15.4 KB 310 lines swift

1import Foundation2import PrismCore34/// Where an expression's names come from. `queries.<id>` is resolved lazily so unused queries never run.5public struct ExpressionScope: Sendable {6    public var roots: [String: JSONValue]7    public var queryResolver: (@Sendable (String) -> JSONValue)?8    /// Calls a function of the app's scripts (`js('name', …)`); nil where scripts are not available.9    public var scriptCaller: (@Sendable (String, [JSONValue]) throws -> JSONValue)?10    public var locale: Locale11    public var currencyCode: String12    public var now: Date1314    public init(15        roots: [String: JSONValue] = [:], queryResolver: (@Sendable (String) -> JSONValue)? = nil,16        locale: Locale = .current, currencyCode: String = "USD", now: Date = Date()17    ) {18        self.roots = roots; self.queryResolver = queryResolver; self.locale = locale19        self.currencyCode = currencyCode; self.now = now20    }2122    public static let knownRoots: Set<String> = ["state", "row", "item", "queries", "value", "event", "params"]23}2425extension JSONValue {26    public var isTruthy: Bool {27        switch self {28        case .null: false29        case .bool(let b): b30        case .int(let i): i != 031        case .double(let d): d != 032        case .string(let s): !s.isEmpty33        case .array(let a): !a.isEmpty34        case .object: true35        }36    }3738    /// Text shown to a person. Numbers lose a trailing `.0`.39    public var displayString: String {40        switch self {41        case .null: ""42        case .bool(let b): b ? "true" : "false"43        case .int(let i): String(i)44        case .double(let d): d.rounded() == d && abs(d) < 1e15 ? String(Int(d)) : String(d)45        case .string(let s): s46        case .array(let a): a.map(\.displayString).joined(separator: ", ")47        case .object: canonicalString()48        }49    }5051    /// Numbers, and strings that are entirely a number.52    public var numericValue: Double? {53        if let d = doubleValue { return d }54        if let s = stringValue { return Double(s.trimmingCharacters(in: .whitespaces)) }55        return nil56    }57}5859public struct Evaluator {60    public static let functionNames: Set<String> = [61        "sum", "avg", "min", "max", "count", "first", "last", "round", "abs", "floor", "ceil", "lower", "upper", "trim",62        "contains", "startsWith", "concat", "length", "formatCurrency", "formatNumber", "formatPercent", "formatDate",63        "month", "year", "today", "coalesce", "if", "number", "text", "isEmpty", "pluck", "unique", "js",64    ]6566    public let scope: ExpressionScope67    private var budget: Int6869    public init(scope: ExpressionScope, budget: Int = 20_000) {70        self.scope = scope; self.budget = budget71    }7273    public static func evaluate(_ expression: Expression, scope: ExpressionScope) throws -> JSONValue {74        var e = Evaluator(scope: scope)75        return try e.eval(expression.root)76    }7778    public static func evaluate(_ source: String, scope: ExpressionScope) throws -> JSONValue {79        try evaluate(try Expression(source), scope: scope)80    }8182    mutating func eval(_ e: Expr) throws -> JSONValue {83        budget -= 184        guard budget > 0 else { throw ExpressionError("The expression is too expensive to evaluate.") }85        switch e {86        case .literal(let v): return v87        case .identifier(let name):88            if let v = scope.roots[name] { return v }89            if name == "queries" { return .emptyObject }90            throw ExpressionError("Unknown name `\(name)`.")91        case .member(.identifier("queries"), let id):92            guard let resolver = scope.queryResolver else { throw ExpressionError("Queries are not available here.") }93            return resolver(id)94        case .member(let base, let name):95            let b = try eval(base)96            if case .array(let a) = b, name == "length" { return .int(a.count) }97            return b[name] ?? .null98        case .index(let base, let index):99            let b = try eval(base), i = try eval(index)100            if let n = i.intValue { return b[n] ?? .null }101            if let k = i.stringValue { return b[k] ?? .null }102            return .null103        case .unary("!", let a): return .bool(!(try eval(a)).isTruthy)104        case .unary(_, let a):105            let v = try eval(a)106            if case .int(let i) = v { return .int(-i) }107            guard let d = v.numericValue else { throw ExpressionError("`-` needs a number.") }108            return d.rounded() == d && abs(d) < 9e15 ? .int(Int(-d)) : .double(-d)109        case .binary("&&", let a, let b):110            let l = try eval(a)111            return l.isTruthy ? .bool((try eval(b)).isTruthy) : .bool(false)112        case .binary("||", let a, let b):113            let l = try eval(a)114            return l.isTruthy ? .bool(true) : .bool((try eval(b)).isTruthy)115        case .binary(let op, let a, let b): return try binary(op, try eval(a), try eval(b))116        case .conditional(let c, let a, let b): return (try eval(c)).isTruthy ? try eval(a) : try eval(b)117        case .call(let name, let args):118            if name == "if" {119                guard args.count == 3 else { throw ExpressionError("`if` takes 3 arguments.") }120                return (try eval(args[0])).isTruthy ? try eval(args[1]) : try eval(args[2])121            }122            if name == "coalesce" {123                for a in args { let v = try eval(a); if !v.isNull && v != .string("") { return v } }124                return .null125            }126            var values: [JSONValue] = []127            for a in args { values.append(try eval(a)) }128            return try call(name, values)129        }130    }131132    private func binary(_ op: String, _ l: JSONValue, _ r: JSONValue) throws -> JSONValue {133        let v = try rawBinary(op, l, r)134        // Whole-number results are integers, so `2.5 * 2 == 5` and canonical output stay predictable.135        if case .double(let d) = v, d.rounded() == d, abs(d) < 9e15 { return .int(Int(d)) }136        return v137    }138139    private func rawBinary(_ op: String, _ l: JSONValue, _ r: JSONValue) throws -> JSONValue {140        switch op {141        case "==": return .bool(Evaluator.equal(l, r))142        case "!=": return .bool(!Evaluator.equal(l, r))143        case "<", "<=", ">", ">=":144            let order: Int145            if let a = l.numericValue, let b = r.numericValue { order = a < b ? -1 : a > b ? 1 : 0 }146            else if l.isNull || r.isNull { return .bool(false) }147            else { let a = l.displayString, b = r.displayString; order = a < b ? -1 : a > b ? 1 : 0 }148            return .bool(op == "<" ? order < 0 : op == "<=" ? order <= 0 : op == ">" ? order > 0 : order >= 0)149        case "+":150            if case .int(let a) = l, case .int(let b) = r {151                let (s, overflow) = a.addingReportingOverflow(b)152                return overflow ? .double(Double(a) + Double(b)) : .int(s)153            }154            if l.stringValue != nil || r.stringValue != nil, l.doubleValue == nil || r.doubleValue == nil {155                return .string(l.displayString + r.displayString)156            }157            return .double((l.doubleValue ?? 0) + (r.doubleValue ?? 0))158        case "-", "*", "/", "%":159            guard let a = l.isNull ? 0 : l.numericValue, let b = r.isNull ? 0 : r.numericValue else {160                throw ExpressionError("`\(op)` needs numbers.")161            }162            if case .int(let x) = l, case .int(let y) = r {163                switch op {164                case "-": let (v, o) = x.subtractingReportingOverflow(y); if !o { return .int(v) }165                case "*": let (v, o) = x.multipliedReportingOverflow(by: y); if !o { return .int(v) }166                case "%": return y == 0 ? .null : .int(x % y)167                default: break168                }169            }170            switch op {171            case "-": return .double(a - b)172            case "*": return .double(a * b)173            case "/": return b == 0 ? .null : .double(a / b)174            default: return b == 0 ? .null : .double(a.truncatingRemainder(dividingBy: b))175            }176        default: throw ExpressionError("Unknown operator `\(op)`.")177        }178    }179180    static func equal(_ l: JSONValue, _ r: JSONValue) -> Bool {181        if let a = l.doubleValue, let b = r.doubleValue { return a == b }182        return l == r183    }184185    /// Numbers out of a list of numbers, or out of a list of records plus a column name.186    private func numbers(_ args: [JSONValue], _ fn: String) throws -> [Double] {187        guard let first = args.first else { throw ExpressionError("`\(fn)` needs a list.") }188        guard let list = first.arrayValue else {189            return args.compactMap(\.numericValue)190        }191        if args.count > 1, let column = args[1].stringValue { return list.compactMap { $0[column]?.numericValue } }192        return list.compactMap(\.numericValue)193    }194195    private func call(_ name: String, _ a: [JSONValue]) throws -> JSONValue {196        func arg(_ i: Int) throws -> JSONValue {197            guard i < a.count else { throw ExpressionError("`\(name)` is missing an argument.") }198            return a[i]199        }200        func number(_ v: Double) -> JSONValue { v.rounded() == v && abs(v) < 9e15 ? .int(Int(v)) : .double(v) }201        switch name {202        case "js":203            guard let fn = try arg(0).stringValue else { throw ExpressionError("`js` needs the function name as its first argument.") }204            guard let caller = scope.scriptCaller else { throw ExpressionError("Scripts are not available here.") }205            return try caller(fn, Array(a.dropFirst()))206        case "sum": return number(try numbers(a, name).reduce(0, +))207        case "avg": let n = try numbers(a, name); return n.isEmpty ? .null : .double(n.reduce(0, +) / Double(n.count))208        case "min": return try numbers(a, name).min().map(number) ?? .null209        case "max": return try numbers(a, name).max().map(number) ?? .null210        case "count": return .int(try arg(0).arrayValue?.count ?? 0)211        case "first": return try arg(0).arrayValue?.first ?? .null212        case "last": return try arg(0).arrayValue?.last ?? .null213        case "length":214            let v = try arg(0)215            return .int(v.arrayValue?.count ?? v.displayString.count)216        case "isEmpty": return .bool(!(try arg(0)).isTruthy)217        case "pluck":218            guard let column = try arg(1).stringValue else { throw ExpressionError("`pluck` needs a column name.") }219            return .array((try arg(0).arrayValue ?? []).map { $0[column] ?? .null })220        case "unique":221            var seen = Set<JSONValue>(), out: [JSONValue] = []222            for v in try arg(0).arrayValue ?? [] where seen.insert(v).inserted { out.append(v) }223            return .array(out)224        case "round":225            guard let v = try arg(0).numericValue else { return .null }226            let places = a.count > 1 ? max(0, min(a[1].intValue ?? 0, 10)) : 0227            let f = pow(10, Double(places))228            return number((v * f).rounded() / f)229        case "abs": return try arg(0).numericValue.map { number(abs($0)) } ?? .null230        case "floor": return try arg(0).numericValue.map { number($0.rounded(.down)) } ?? .null231        case "ceil": return try arg(0).numericValue.map { number($0.rounded(.up)) } ?? .null232        case "number": return try arg(0).numericValue.map(number) ?? .null233        case "text": return .string(try arg(0).displayString)234        case "lower": return .string(try arg(0).displayString.lowercased())235        case "upper": return .string(try arg(0).displayString.uppercased())236        case "trim": return .string(try arg(0).displayString.trimmingCharacters(in: .whitespacesAndNewlines))237        case "concat": return .string(a.map(\.displayString).joined())238        case "contains":239            let hay = try arg(0), needle = try arg(1)240            if let list = hay.arrayValue { return .bool(list.contains { Evaluator.equal($0, needle) }) }241            return .bool(hay.displayString.localizedCaseInsensitiveContains(needle.displayString))242        case "startsWith":243            return .bool(try arg(0).displayString.lowercased().hasPrefix(try arg(1).displayString.lowercased()))244        case "formatCurrency":245            guard let v = try arg(0).numericValue else { return .string("") }246            let code = a.count > 1 ? a[1].stringValue ?? scope.currencyCode : scope.currencyCode247            return .string(v.formatted(.currency(code: code).locale(scope.locale)))248        case "formatNumber":249            guard let v = try arg(0).numericValue else { return .string("") }250            let places = a.count > 1 ? max(0, min(a[1].intValue ?? 0, 10)) : 0251            return .string(v.formatted(.number.precision(.fractionLength(places)).locale(scope.locale)))252        case "formatPercent":253            guard let v = try arg(0).numericValue else { return .string("") }254            return .string(v.formatted(.percent.precision(.fractionLength(0...1)).locale(scope.locale)))255        case "today": return .string(DateCoding.string(from: scope.now))256        case "month":257            let s = try arg(0).displayString258            return DateCoding.date(from: s) == nil ? .null : .string(String(s.prefix(7)))259        case "year":260            let s = try arg(0).displayString261            return DateCoding.date(from: s) == nil ? .null : .int(Int(s.prefix(4)) ?? 0)262        case "formatDate":263            guard let d = DateCoding.date(from: try arg(0).displayString) else { return .string("") }264            let style = a.count > 1 ? a[1].stringValue ?? "medium" : "medium"265            var cal = Calendar(identifier: .gregorian)266            cal.timeZone = TimeZone(identifier: "UTC")!267            var f = Date.FormatStyle(date: style == "long" ? .long : style == "short" ? .numeric : .abbreviated, time: .omitted)268            f.timeZone = TimeZone(identifier: "UTC")!269            f.locale = scope.locale270            f.calendar = cal271            return .string(d.formatted(f))272        default: throw ExpressionError("Unknown function `\(name)`.")273        }274    }275}276277/// Dates are stored as ISO `YYYY-MM-DD` text, interpreted in UTC so they never shift with the time zone.278public enum DateCoding {279    public static func date(from text: String) -> Date? {280        let parts = text.prefix(10).split(separator: "-")281        guard parts.count == 3, parts[0].count == 4, let y = Int(parts[0]), let m = Int(parts[1]), let d = Int(parts[2]),282              (1...12).contains(m), (1...31).contains(d) else { return nil }283        var cal = Calendar(identifier: .gregorian)284        cal.timeZone = TimeZone(identifier: "UTC")!285        guard let date = cal.date(from: DateComponents(year: y, month: m, day: d)),286              cal.component(.day, from: date) == d else { return nil }287        return date288    }289290    public static func string(from date: Date, timeZone: TimeZone = .current) -> String {291        var cal = Calendar(identifier: .gregorian)292        cal.timeZone = timeZone293        let c = cal.dateComponents([.year, .month, .day], from: date)294        return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0)295    }296297    /// Accepts ISO dates plus the common `M/D/YYYY` and `D.M.YYYY`-free forms found in bank exports.298    public static func normalize(_ text: String) -> String? {299        let t = text.trimmingCharacters(in: .whitespaces)300        if date(from: t) != nil, t.count >= 10 { return String(t.prefix(10)) }301        let parts = t.split(whereSeparator: { $0 == "/" })302        if parts.count == 3, let m = Int(parts[0]), let d = Int(parts[1]), var y = Int(parts[2]) {303            if y < 100 { y += 2000 }304            let iso = String(format: "%04d-%02d-%02d", y, m, d)305            return date(from: iso) == nil ? nil : iso306        }307        return nil308    }309}310
Files main
Menu

Theme