123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- import Foundation
- internal func memoizedClosure<T>(_ closure: @escaping () throws -> T) -> (Bool) throws -> T {
- var cache: T?
- return { withoutCaching in
- if withoutCaching || cache == nil {
- cache = try closure()
- }
- return cache!
- }
- }
- public struct Expression<T> {
-
- internal let _expression: (Bool) throws -> T?
- internal let _withoutCaching: Bool
-
- public let location: SourceLocation
- public let isClosure: Bool
-
-
-
-
-
-
-
-
-
-
-
- public init(expression: @escaping () throws -> T?, location: SourceLocation, isClosure: Bool = true) {
- self._expression = memoizedClosure(expression)
- self.location = location
- self._withoutCaching = false
- self.isClosure = isClosure
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- public init(memoizedExpression: @escaping (Bool) throws -> T?, location: SourceLocation, withoutCaching: Bool, isClosure: Bool = true) {
- self._expression = memoizedExpression
- self.location = location
- self._withoutCaching = withoutCaching
- self.isClosure = isClosure
- }
-
-
-
-
-
-
-
-
- public func cast<U>(_ block: @escaping (T?) throws -> U?) -> Expression<U> {
- return Expression<U>(
- expression: ({ try block(self.evaluate()) }),
- location: self.location,
- isClosure: self.isClosure
- )
- }
- public func evaluate() throws -> T? {
- return try self._expression(_withoutCaching)
- }
- public func withoutCaching() -> Expression<T> {
- return Expression(
- memoizedExpression: self._expression,
- location: location,
- withoutCaching: true,
- isClosure: isClosure
- )
- }
- }
|