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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
use itertools::Itertools;
use std::collections::{HashMap, HashSet};
use std::iter;
pub type Place = Vec<usize>;
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Variable {
pub(crate) id: usize,
}
impl Variable {
pub fn name<'sig>(&self, sig: &'sig Signature) -> Option<&'sig str> {
let opt = &sig.variables[self.id];
opt.as_ref().map(|s| s.as_str())
}
pub fn display(&self, sig: &Signature) -> String {
if let Some(ref name) = sig.variables[self.id] {
name.clone()
} else {
format!("<var {}>", self.id)
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct Operator {
pub(crate) id: usize,
}
impl Operator {
pub fn arity(&self, sig: &Signature) -> u32 {
sig.operators[self.id].0
}
pub fn name<'sig>(&self, sig: &'sig Signature) -> Option<&'sig str> {
let opt = &sig.operators[self.id].1;
opt.as_ref().map(|s| s.as_str())
}
pub fn display(&self, sig: &Signature) -> String {
if let (_, Some(ref name)) = sig.operators[self.id] {
name.clone()
} else {
format!("<op {}>", self.id)
}
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Atom {
Variable(Variable),
Operator(Operator),
}
impl From<Variable> for Atom {
fn from(var: Variable) -> Atom {
Atom::Variable(var)
}
}
impl From<Operator> for Atom {
fn from(op: Operator) -> Atom {
Atom::Operator(op)
}
}
#[derive(Clone, Debug)]
pub struct Signature {
pub(crate) operators: Vec<(u32, Option<String>)>,
pub(crate) variables: Vec<Option<String>>,
}
impl Signature {
pub fn new(operator_spec: Vec<(u32, Option<String>)>) -> (Signature, Vec<Operator>) {
let variables = Vec::new();
let sig = Signature {
operators: operator_spec,
variables,
};
let ops = sig.operators();
(sig, ops)
}
pub fn operators(&self) -> Vec<Operator> {
(0..self.operators.len())
.map(|id| Operator { id })
.collect()
}
pub fn variables(&self) -> Vec<Variable> {
(0..self.variables.len())
.map(|id| Variable { id })
.collect()
}
pub fn new_op(&mut self, arity: u32, name: Option<String>) -> Operator {
let id = self.operators.len();
self.operators.push((arity, name));
Operator { id }
}
pub fn new_var(&mut self, name: Option<String>) -> Variable {
let id = self.variables.len();
self.variables.push(name);
Variable { id }
}
pub fn merge(&mut self, mut other: Signature, strategy: MergeStrategy) -> SignatureChange {
let delta_op = match strategy {
MergeStrategy::SameOperators => 0,
MergeStrategy::OperatorsByArityAndName => {
let old_len = self.operators.len();
for op_spec in other.operators {
if !self.operators.contains(&op_spec) {
self.operators.push(op_spec)
}
}
old_len
}
MergeStrategy::DistinctOperators => {
let old_len = self.operators.len();
self.operators.append(&mut other.operators);
old_len
}
};
let delta_var = self.variables.len();
self.variables.append(&mut other.variables);
SignatureChange {
delta_op,
delta_var,
}
}
}
impl Default for Signature {
fn default() -> Signature {
Signature {
operators: Vec::new(),
variables: Vec::new(),
}
}
}
impl PartialEq for Signature {
fn eq(&self, other: &Signature) -> bool {
self.variables.len() == other.variables.len()
&& self.operators.len() == other.operators.len()
&& self.operators
.iter()
.zip(&other.operators)
.all(|(&(arity1, _), &(arity2, _))| arity1 == arity2)
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum MergeStrategy {
SameOperators,
OperatorsByArityAndName,
DistinctOperators,
}
pub struct SignatureChange {
delta_op: usize,
delta_var: usize,
}
impl SignatureChange {
pub fn reify_term(&self, term: Term) -> Term {
match term {
Term::Variable(Variable { id }) => {
let id = id + self.delta_var;
Term::Variable(Variable { id })
}
Term::Application {
op: Operator { id },
args,
} => {
let id = id + self.delta_op;
Term::Application {
op: Operator { id },
args: args.into_iter().map(|t| self.reify_term(t)).collect(),
}
}
}
}
pub fn reify_context(&self, context: Context) -> Context {
match context {
Context::Hole => Context::Hole,
Context::Variable(Variable { id }) => {
let id = id + self.delta_var;
Context::Variable(Variable { id })
}
Context::Application {
op: Operator { id },
args,
} => {
let id = id + self.delta_op;
Context::Application {
op: Operator { id },
args: args.into_iter().map(|t| self.reify_context(t)).collect(),
}
}
}
}
pub fn reify_rule(&self, rule: Rule) -> Rule {
let Rule { lhs, rhs } = rule;
let lhs = self.reify_term(lhs);
let rhs = rhs.into_iter().map(|t| self.reify_term(t)).collect();
Rule { lhs, rhs }
}
pub fn reify_trs(&self, trs: TRS) -> TRS {
let rules = trs.rules.into_iter().map(|r| self.reify_rule(r)).collect();
TRS { rules }
}
}
#[derive(PartialEq, Eq)]
enum Unification {
Match,
Unify,
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum Context {
Hole,
Variable(Variable),
Application { op: Operator, args: Vec<Context> },
}
impl Context {
}
impl From<Term> for Context {
fn from(t: Term) -> Context {
match t {
Term::Variable(v) => Context::Variable(v),
Term::Application { op, args } => {
let args = args.into_iter().map(Context::from).collect();
Context::Application { op, args }
}
}
}
}
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub enum Term {
Variable(Variable),
Application { op: Operator, args: Vec<Term> },
}
impl Term {
pub fn variables(&self) -> Vec<Variable> {
match *self {
Term::Variable(v) => vec![v],
Term::Application { ref args, .. } => {
args.iter().flat_map(Term::variables).unique().collect()
}
}
}
pub fn operators(&self) -> Vec<Operator> {
match *self {
Term::Variable(_) => vec![],
Term::Application { op, ref args } => args.iter()
.flat_map(Term::operators)
.chain(iter::once(op))
.unique()
.collect(),
}
}
pub fn subterms(&self) -> Vec<(&Term, Place)> {
match *self {
Term::Variable(_) => vec![(self, vec![])],
Term::Application { ref args, .. } => {
let here = iter::once((self, vec![]));
let subterms = args.iter().enumerate().flat_map(|(i, arg)| {
arg.subterms()
.into_iter()
.zip(iter::repeat(i))
.map(|((t, p), i)| {
let mut a = vec![i];
a.extend(p);
(t, a)
})
});
here.chain(subterms).collect()
}
}
}
#[cfg_attr(feature = "cargo-clippy", allow(ptr_arg))]
pub fn at(&self, place: &Place) -> Option<&Term> {
self.at_helper(&*place)
}
fn at_helper(&self, place: &[usize]) -> Option<&Term> {
if place.is_empty() {
Some(self)
} else {
match *self {
Term::Variable(_) => None,
Term::Application { ref args, .. } => if place[0] <= args.len() {
args[place[0]].at_helper(&place[1..].to_vec())
} else {
None
},
}
}
}
#[cfg_attr(feature = "cargo-clippy", allow(ptr_arg))]
pub fn replace(&self, place: &Place, subterm: Term) -> Option<Term> {
self.replace_helper(&*place, subterm)
}
fn replace_helper(&self, place: &[usize], subterm: Term) -> Option<Term> {
if place.is_empty() {
Some(subterm)
} else {
match *self {
Term::Application { op, ref args } if place[0] <= args.len() => {
if let Some(term) = args[place[0]].replace_helper(&place[1..].to_vec(), subterm)
{
let mut new_args = args.clone();
new_args.remove(place[0]);
new_args.insert(place[0], term);
Some(Term::Application { op, args: new_args })
} else {
None
}
}
_ => None,
}
}
}
pub fn substitute(&self, sub: &HashMap<Variable, Term>) -> Term {
match *self {
Term::Variable(ref v) => sub.get(v).unwrap_or(self).clone(),
Term::Application { op, ref args } => Term::Application {
op,
args: args.iter().map(|t| t.substitute(sub)).collect(),
},
}
}
fn constraint_substitute(
cs: &[(Term, Term)],
sub: &HashMap<Variable, Term>,
) -> Vec<(Term, Term)> {
cs.iter()
.map(|&(ref s, ref t)| (s.substitute(sub), t.substitute(sub)))
.collect()
}
fn compose(
sub1: Option<HashMap<Variable, Term>>,
sub2: Option<HashMap<Variable, Term>>,
) -> Option<HashMap<Variable, Term>> {
match (sub1, sub2) {
(Some(mut s1), Some(s2)) => {
for (k, v) in s2 {
let v = v.substitute(&s1);
s1.insert(k, v);
}
Some(s1)
}
_ => None,
}
}
pub fn alpha_equivalent(t1: &Term, t2: &Term) -> bool {
Term::pmatch(vec![(t1.clone(), t2.clone())]).is_some()
&& Term::pmatch(vec![(t2.clone(), t1.clone())]).is_some()
}
pub fn shape_equivalent(t1: &Term, t2: &Term) -> bool {
let mut vmap = HashMap::new();
let mut omap = HashMap::new();
Term::se_helper(t1, t2, &mut vmap, &mut omap)
}
fn se_helper(
t1: &Term,
t2: &Term,
vmap: &mut HashMap<Variable, Variable>,
omap: &mut HashMap<Operator, Operator>,
) -> bool {
match (t1, t2) {
(&Term::Variable(v1), &Term::Variable(v2)) => v2 == *vmap.entry(v1).or_insert(v2),
(
&Term::Application {
op: op1,
args: ref args1,
},
&Term::Application {
op: op2,
args: ref args2,
},
) => {
op2 == *omap.entry(op1).or_insert(op2)
&& args1
.into_iter()
.zip(args2)
.all(|(a1, a2)| Term::se_helper(a1, a2, vmap, omap))
}
_ => false,
}
}
pub fn pmatch(cs: Vec<(Term, Term)>) -> Option<HashMap<Variable, Term>> {
Term::unify_internal(cs, Unification::Match)
}
pub fn unify(cs: Vec<(Term, Term)>) -> Option<HashMap<Variable, Term>> {
Term::unify_internal(cs, Unification::Unify)
}
fn unify_internal(
mut cs: Vec<(Term, Term)>,
utype: Unification,
) -> Option<HashMap<Variable, Term>> {
let c = cs.pop();
match c {
None => Some(HashMap::new()),
Some((ref s, ref t)) if s == t => Term::unify_internal(cs, utype),
Some((
Term::Application {
op: h1,
args: ref a1,
},
Term::Application {
op: h2,
args: ref a2,
},
)) if h1 == h2 =>
{
cs.append(&mut a1.clone().into_iter().zip(a2.clone().into_iter()).collect());
Term::unify_internal(cs, utype)
}
Some((Term::Variable(var), ref t)) if !t.variables().contains(&&var) => {
let mut st = HashMap::new();
st.insert(var, t.clone());
let mut cs = Term::constraint_substitute(&cs, &st);
Term::compose(Term::unify_internal(cs, utype), Some(st))
}
Some((ref s, Term::Variable(var)))
if !s.variables().contains(&&var) && utype != Unification::Match =>
{
let mut ts = HashMap::new();
ts.insert(var, s.clone());
let mut cs = Term::constraint_substitute(&cs, &ts);
Term::compose(Term::unify_internal(cs, utype), Some(ts))
}
_ => None,
}
}
}
#[derive(Debug, PartialEq)]
pub struct Rule {
lhs: Term,
rhs: Vec<Term>,
}
impl Rule {
fn is_valid(lhs: &Term, rhs: &[Term]) -> bool {
if let Term::Application { .. } = *lhs {
let lhs_vars: HashSet<_> = lhs.variables().into_iter().collect();
let rhs_vars: HashSet<_> = rhs.iter().flat_map(Term::variables).collect();
rhs_vars.is_subset(&lhs_vars)
} else {
false
}
}
pub fn new(lhs: Term, rhs: Vec<Term>) -> Option<Rule> {
if Rule::is_valid(&lhs, &rhs) {
Some(Rule { lhs, rhs })
} else {
None
}
}
}
#[derive(Debug, PartialEq)]
pub struct TRS {
rules: Vec<Rule>,
}
impl TRS {
pub fn new(rules: Vec<Rule>) -> TRS {
TRS { rules }
}
fn rewrite_head(&self, term: &Term) -> Option<Vec<Term>> {
for rule in &self.rules {
if let Some(ref sub) = Term::pmatch(vec![(rule.lhs.clone(), term.clone())]) {
return Some(rule.rhs.iter().map(|x| x.substitute(sub)).collect());
}
}
None
}
fn rewrite_args(&self, term: &Term) -> Option<Vec<Term>> {
if let Term::Application { op, ref args } = *term {
for (i, arg) in args.iter().enumerate() {
if let Some(v) = self.rewrite(arg) {
let res = v.iter()
.map(|x| {
let mut args = args.clone();
args[i] = x.clone();
Term::Application { op, args }
})
.collect();
return Some(res);
}
}
None
} else {
None
}
}
pub fn rewrite(&self, term: &Term) -> Option<Vec<Term>> {
match *term {
Term::Variable(_) => None,
ref app => self.rewrite_head(app).or_else(|| self.rewrite_args(app)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn variable_show() {
let mut sig = Signature::default();
let v1 = sig.new_var(None);
let v2 = sig.new_var(Some("blah".to_string()));
assert_eq!(v1.display(&sig), "<var 0>".to_string());
assert_eq!(v1.name(&sig), None);
assert_eq!(v2.display(&sig), "blah".to_string());
assert_eq!(v2.name(&sig), Some("blah"));
}
#[test]
fn variable_eq() {
let mut sig = Signature::default();
let v1 = sig.new_var(Some("blah".to_string()));
let v2 = sig.new_var(None);
let v3 = Variable { id: 0 };
assert_eq!(v1, v1);
assert_ne!(v1, v2);
assert_eq!(v1, v3);
}
#[test]
fn rule_is_valid_yes() {
let mut sig = Signature::default();
let lhs: Term = Term::Application {
op: sig.new_op(0, None),
args: vec![],
};
let rhs: Vec<Term> = vec![Term::Application {
op: sig.new_op(0, None),
args: vec![],
}];
assert!(Rule::is_valid(&lhs, &rhs));
}
#[test]
fn rule_is_valid_lhs_var() {
let mut sig = Signature::default();
let lhs = Term::Variable(sig.new_var(None));
let rhs = vec![Term::Application {
op: sig.new_op(0, None),
args: vec![],
}];
assert!(!Rule::is_valid(&lhs, &rhs));
}
#[test]
fn rule_is_valid_rhs_var() {
let mut sig = Signature::default();
let lhs = Term::Application {
op: sig.new_op(0, None),
args: vec![],
};
let rhs = vec![Term::Variable(sig.new_var(None))];
assert!(!Rule::is_valid(&lhs, &rhs));
}
#[test]
fn rule_new_some() {
let mut sig = Signature::default();
let lhs = Term::Application {
op: sig.new_op(0, None),
args: vec![],
};
let rhs = vec![Term::Application {
op: sig.new_op(0, None),
args: vec![],
}];
let rule = Rule {
lhs: lhs.clone(),
rhs: rhs.clone(),
};
assert_eq!(Rule::new(lhs, rhs), Some(rule));
}
#[test]
fn rule_is_valid_none() {
let mut sig = Signature::default();
let lhs = Term::Application {
op: sig.new_op(0, None),
args: vec![],
};
let rhs = vec![Term::Variable(sig.new_var(None))];
assert_eq!(Rule::new(lhs, rhs), None);
}
#[test]
fn trs_new() {
let trs1: TRS = TRS::new(vec![]);
let trs2 = TRS { rules: vec![] };
assert_eq!(trs1, trs2);
}
#[test]
fn trs_debug() {
let trs: TRS = TRS::new(vec![]);
assert_eq!(format!("{:?}", trs), "TRS { rules: [] }");
}
}