/
Matching.swift
277 lines (233 loc) · 10.5 KB
/
Matching.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
//
// Matching.swift
//
//
// Created by Steven Obua on 08/08/2021.
//
import Foundation
public struct Matching {
private struct Task : CustomStringConvertible {
let level : Int
let pattern : Tm
let instance : Tm
func apply(_ subst : TmSubstitution) -> Task? {
guard let s = subst.apply(level: level, pattern) else { return nil }
return Task(level: level, pattern: s, instance: instance)
}
var description: String {
return "[\(level)] \(pattern) => \(instance)"
}
}
private struct Job {
var result : TmSubstitution
var tasks : [Task]
mutating func substitute(_ v : Var, _ tmWithHoles : TmWithHoles) -> Bool {
let subst = TmSubstitution(free: [v : tmWithHoles])
//print("substitute \(v) ==> \(tmWithHoles)")
let newTasks = tasks.compactMap { task in task.apply(subst) }
guard newTasks.count == tasks.count else { return false }
guard result.compose(subst) else { return false }
result[v] = tmWithHoles
tasks = newTasks
return true
}
mutating func addTask(_ task : Task) {
//print("adding task: \(task)")
tasks.append(task)
}
mutating func nextTask() -> Task? {
if tasks.isEmpty { return nil }
return tasks.removeLast()
}
}
public let kc : KernelContext
public func match(patterns : [TmWithHoles], instances : [TmWithHoles], max_matches : Int, frees : inout FreeVars) -> [TmSubstitution] {
guard patterns.count == instances.count else { fatalError() }
var _patternFreeVars = FreeVars()
for p in patterns {
guard frees.add(p.tm) else { return [] }
_patternFreeVars.add(p.tm)
}
let patternFreeVars = _patternFreeVars.vars
guard let (instances, renaming) = frees.addFresh(instances) else { return [] }
let constantFreeVars = renaming.codomain
var nextJobs : [Job] = []
var results : [TmSubstitution] = []
var job = Job(result: TmSubstitution(), tasks: [])
for (i, p) in patterns.enumerated() {
let q = instances[i]
guard q.holes == p.holes else { return [] }
job.addTask(Task(level: q.holes, pattern: p.tm, instance: q.tm))
//print("*** \(p) ==> \(instances[i])")
}
func trySubstitutions( _ v : Var, substs : [TmWithHoles]) -> Bool {
var newJobs : [Job] = []
for s in substs {
var newJob = job
guard newJob.substitute(v, s) else { continue }
newJobs.append(newJob)
}
if newJobs.isEmpty { return false }
job = newJobs.first!
nextJobs.append(contentsOf: newJobs.dropFirst())
return true
}
func solve(level : Int, params1 : [Tm], params2 : [Tm]) -> Bool {
guard params1.count == params2.count else { return false }
for (i, param) in params1.enumerated() {
job.addTask(Task(level: level, pattern: param, instance: params2[i]))
}
return true
}
func couldMatch(pattern : Tm, constVar : Var) -> Bool {
switch pattern {
case let .free(v, params: _):
if constantFreeVars.contains(v) {
return v == constVar
} else {
return true
}
case .bound, .const: return false
}
}
func couldMatch(pattern : Tm, const : Const) -> Bool {
switch pattern {
case let .free(v, params: _): return !constantFreeVars.contains(v)
case .bound: return false
case let .const(c, binders: _, params: _): return c == const
}
}
func couldMatch(pattern : Tm, constBound index : Int) -> Bool {
switch pattern {
case .free: return true
case let .bound(i): return i == index
case .const: return false
}
}
func couldMatch(pattern : Tm, bound index : Int) -> Bool {
return pattern == .bound(index)
}
func solveTask(_ task : Task) -> Bool {
switch (task.pattern, task.instance) {
case (.const, .free): return false
case (.const, .bound): return false
case let (.const(const1, binders1, params1), .const(const2, binders: binders2, params: params2)):
guard const1 == const2, binders1.count == binders2.count else { return false }
let sublevel = binders1.count + task.level
return solve(level: sublevel, params1: params1, params2: params2)
case (.bound, .const): return false
case let (.bound(index1), .bound(index2)): return index1 == index2
case (.bound, .free): return false
case let (.free(v, params1), _) where constantFreeVars.contains(v):
switch task.instance {
case let .free(w, params: params2) where v == w && params2.count == params1.count:
return solve(level: task.level, params1: params1, params2: params2)
default: return false
}
case let (.free(v, params: params1), .bound(index)) where index < task.level:
job.addTask(task)
var twhs : [TmWithHoles] = []
for (i, p) in params1.enumerated() {
if couldMatch(pattern: p, bound: index) {
twhs.append(TmWithHoles.projection(holes: params1.count, i))
}
}
return trySubstitutions(v, substs: twhs)
case let (.free(v, params: params1), .bound(index)): // index >= task.level
job.addTask(task)
var twhs : [TmWithHoles] = []
twhs.append(TmWithHoles.constant(holes: params1.count, index - task.level))
for (i, p) in params1.enumerated() {
if couldMatch(pattern: p, constBound: index) {
twhs.append(TmWithHoles.projection(holes: params1.count, i))
}
}
return trySubstitutions(v, substs: twhs)
case let (.free(v, params: params1), .const(c, _, params: _)):
guard let head = kc.constants[c]?.head else { return false }
job.addTask(task)
var twhs : [TmWithHoles] = []
let twh = TmWithHoles.constant(holes: params1.count, head: head) { v, a in frees.addFresh(v, arity: a) }
twhs.append(twh)
for (i, p) in params1.enumerated() {
if couldMatch(pattern: p, const: c) {
twhs.append(TmWithHoles.projection(holes: params1.count, i))
}
}
return trySubstitutions(v, substs: twhs)
case let (.free(v1, params: params1), .free(v2, params: params2)):
job.addTask(task)
var twhs : [TmWithHoles] = []
let twh = TmWithHoles.variable(holes: params1.count, var: v2, numargs: params2.count) { v, a in frees.addFresh(v, arity: a) }
twhs.append(twh)
for (i, p) in params1.enumerated() {
if couldMatch(pattern: p, constVar: v2) {
twhs.append(TmWithHoles.projection(holes: params1.count, i))
}
}
return trySubstitutions(v1, substs: twhs)
}
}
let renamingReversed = renaming.reversed()
jobLoop:
repeat {
while let task = job.nextTask() {
guard solveTask(task) else {
guard !nextJobs.isEmpty else { return results }
job = nextJobs.removeLast()
continue jobLoop
}
}
job.result.restrict(patternFreeVars)
job.result.compose(renamingReversed)
results.append(job.result)
guard !nextJobs.isEmpty, results.count < max_matches else {
return results
}
job = nextJobs.removeLast()
} while true
}
public func match(patterns : [Tm], instances : [Tm], max_matches : Int = Int.max) -> [TmSubstitution] {
var frees = FreeVars()
let patterns = patterns.map { p in TmWithHoles(holes: 0, p) }
let instances = instances.map { i in TmWithHoles(holes: 0, i) }
return match(patterns: patterns, instances: instances, max_matches: max_matches, frees: &frees)
}
public func match(pattern : Tm, instance : Tm, max_matches : Int = Int.max) -> [TmSubstitution] {
return match(patterns: [pattern], instances: [instance], max_matches: max_matches)
}
public func match1(pattern : Tm, instance : Tm) -> TmSubstitution? {
return match(pattern: pattern, instance: instance, max_matches: 1).first
}
}
extension Matching {
public func proveByAxiom(term : Term) -> (axiom : Int, thm : Theorem)? {
guard let tm = kc.tmOf(term) else { return nil }
for (i, ax) in kc.axioms.enumerated() {
let ax = kc.tmOf(ax)!
guard let subst = match1(pattern: ax, instance: tm) else { continue }
let th = kc.axiom(i)
guard let sth = kc.substitute(subst, in: th) else { continue }
return (axiom: i, thm: sth)
}
return nil
}
// Finds a substitution delta such that subsumed <= delta ∘ subsumed
public func subsumption(subsuming : TmSubstitution, subsumed : TmSubstitution) -> TmSubstitution? {
var patterns : [TmWithHoles] = []
var instances : [TmWithHoles] = []
for (v, i) in subsumed.freeMappings {
if let p = subsuming[v] {
patterns.append(p)
instances.append(i)
} else {
let p = TmWithHoles.variable(v, arity: 0)
patterns.append(p)
instances.append(i)
}
}
var frees = FreeVars()
let solutions = match(patterns: patterns, instances: instances, max_matches: 1, frees: &frees)
return solutions.first
}
}