-
Notifications
You must be signed in to change notification settings - Fork 0
/
PredicateKeyPathProviding.swift
88 lines (69 loc) · 2.64 KB
/
PredicateKeyPathProviding.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// The Swift Programming Language
// https://docs.swift.org/swift-book
//
// Swift Argument Parser
// https://swiftpackageindex.com/apple/swift-argument-parser/documentation
import ArgumentParser
import Foundation
struct PredicateKeyPath<ObjectType> {
let rootKeyPath: PartialKeyPath<ObjectType>
let leafKeyPath: AnyKeyPath?
}
protocol PredicateKeyPathProviding {
static var keyPaths: [PredicateKeyPath<Self>] { get }
}
struct Root: PredicateKeyPathProviding {
static var keyPaths: [PredicateKeyPath<Self>] {
[
.init(rootKeyPath: \Self.value, leafKeyPath: nil),
.init(rootKeyPath: \Self.optionalLeaf, leafKeyPath: \Leaf.optionalValue),
]
}
struct Leaf {
let optionalValue: Int?
}
let value: Int
let optionalLeaf: Leaf?
}
@main
struct PredicateKeyPathProvidingCommand: ParsableCommand {
mutating func run() throws {
let factory = PredicateFactory<Root>()
let predicate1 = factory.createPredicate1()
print("predicate1=\(predicate1)")
let predicate2 = factory.createPredicate2(ofType: Root.Leaf.self)
print("predicate2=\(predicate2)")
}
}
struct PredicateFactory<RootType: PredicateKeyPathProviding> {
func createPredicate1() -> any PredicateExpression {
let rootVariable = PredicateExpressions.Variable<RootType>()
let rootKeyPath = RootType.keyPaths[0].rootKeyPath
guard let keyPath = rootKeyPath as? KeyPath<RootType, Int> else {
fatalError()
}
return PredicateExpressions.Equal(
lhs: PredicateExpressions.KeyPath(root: rootVariable, keyPath: keyPath),
rhs: PredicateExpressions.Value(1)
)
}
func createPredicate2<LeafType>(ofType: LeafType) -> any PredicateExpression {
let rootVariable = PredicateExpressions.Variable<RootType>()
// this cast fails
guard let rootKeyPath = RootType.keyPaths[1].rootKeyPath as? KeyPath<RootType, LeafType?> else {
fatalError()
}
guard let leafKeyPath = RootType.keyPaths[1].leafKeyPath as? KeyPath<LeafType, Int> else {
fatalError()
}
let rootExpression = PredicateExpressions.KeyPath(root: rootVariable, keyPath: rootKeyPath)
return PredicateExpressions.NilCoalesce(
lhs: PredicateExpressions.OptionalFlatMap(rootExpression, { leafVariable in
PredicateExpressions.Equal(
lhs: PredicateExpressions.KeyPath(root: leafVariable, keyPath: leafKeyPath),
rhs: PredicateExpressions.Value(1))
}),
rhs: PredicateExpressions.Value(false)
)
}
}