-
Notifications
You must be signed in to change notification settings - Fork 1
/
lib.rs
2020 lines (1775 loc) · 70 KB
/
lib.rs
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![doc = include_str!("../README.md")]
use std::sync::Arc;
use std::sync::mpsc::Sender;
use rustc_hash::FxHashSet as HashSet;
use rustc_hash::FxHashMap as HashMap;
use std::fmt;
use std::path::Path;
use piston_meta::Range;
use lazy_static::lazy_static;
use meta_cache::MetaCache;
pub mod parsing;
pub mod meta_cache;
pub mod cycle_detector;
/// Used to keep track of how much it costs to prove something.
pub struct Search {
pub n: u64,
pub debug: bool,
}
impl Search {
/// Creates a new search.
pub fn new() -> Search {Search {n: 0, debug: false}}
/// Increase the counter that shows cost.
pub fn inc(&mut self) {self.n += 1}
/// Asserts that length is less or equal than some limit.
pub fn le(&self, n: u64) {
assert!(self.n <= n, "{} <= {}", self.n, n);
}
/// Beat length.
pub fn beat(&self, n: u64) {
if self.n >= n {panic!("record attempt failed {} >= {}", self.n, n)}
else {panic!("new record {} < {}", self.n, n)}
}
}
#[derive(Clone)]
pub struct Context {
/// Stores symbols.
pub symbols: Vec<Arc<String>>,
/// Stores the terms.
pub terms: Vec<Term>,
/// Stores the term names.
pub term_names: Vec<Arc<String>>,
/// Stores the proofs.
pub proofs: Vec<Type>,
/// Stores proof cache.
pub proof_cache: HashSet<Type>,
}
impl Context {
pub fn new() -> Context {
Context {
symbols: vec![],
terms: vec![],
term_names: vec![],
proofs: vec![],
proof_cache: HashSet::default(),
}
}
pub fn is_symbol_declared(&self, symbol: &str) -> bool {
for s in &self.symbols {
if &**s == symbol {return true}
}
false
}
pub fn is_type_declared(&self, ty: &Type, sym_blocks: &mut Vec<Arc<String>>) -> bool {
use Type::*;
match ty {
Sym(s) => {
self.is_symbol_declared(s) ||
sym_blocks.iter().any(|n| n == s)
}
True | False | Ty(_) | AllTy(_) => true,
LocSym(a) => {
sym_blocks.push(a.clone());
true
}
Pow(ab) => {
let n = sym_blocks.len();
let res = self.is_type_declared(&ab.1, sym_blocks) &&
self.is_type_declared(&ab.0, sym_blocks);
sym_blocks.truncate(n);
res
}
Fun(ab) => {
let n = sym_blocks.len();
let res = self.is_type_declared(&ab.0, sym_blocks) &&
self.is_type_declared(&ab.1, sym_blocks);
sym_blocks.truncate(n);
res
}
And(ab) | Or(ab) | Imply(ab) |
App(ab) | Sd(ab) | Jud(ab) | Comp(ab) | Q(ab) | Pair(ab) =>
self.is_type_declared(&ab.0, sym_blocks) &&
self.is_type_declared(&ab.1, sym_blocks),
All(a) | Nec(a) | Pos(a) | Qu(a) => self.is_type_declared(a, sym_blocks),
SymBlock(ab) => {
let n = sym_blocks.len();
sym_blocks.push(ab.0.clone());
let res = self.is_type_declared(&ab.1, sym_blocks);
sym_blocks.truncate(n);
res
}
}
}
pub fn has_term_ty(&self, name: &str, ty: &Type) -> bool {
for (term_name, term) in self.term_names.iter().zip(self.terms.iter()) {
if &**term_name == name {return term.get_type().has_bound(ty).is_ok()}
}
false
}
pub fn has_term(&self, name: &str) -> bool {
self.term_names.iter().any(|n| &**n == name)
}
pub fn run_str(
&mut self,
file: &str,
script: &str,
search: &mut Search,
loader: &mut Loader,
meta_cache: &MetaCache,
) -> Result<Option<(bool, Arc<String>)>, String> {
parsing::run_str(file, self, script, search, loader, meta_cache)
}
pub fn run(
&mut self,
file: &str,
search: &mut Search,
loader: &mut Loader,
meta_cache: &MetaCache,
) -> Result<Option<(bool, Arc<String>)>, String> {
use std::fs::File;
use std::io::Read;
let mut data_file =
File::open(file).map_err(|err| format!("Could not open `{}`, {}", file, err))?;
let mut data = String::new();
data_file.read_to_string(&mut data)
.map_err(|err| format!("Could not open `{}`, {}", file, err))?;
self.run_str(file, &data, search, loader, meta_cache)
}
pub fn new_term(
&mut self,
(name, t): (Arc<String>, Term),
is_use: bool,
search: &mut Search
) -> Result<(), String> {
let ty = t.get_type();
if !is_use && !self.is_type_declared(&ty, &mut vec![]) {
return Err("Some symbols where not declared".into())
}
match t.has_type(&ty, self, search) {
Ok(()) => {
self.terms.push(t);
self.term_names.push(name.clone());
self.proof_cache.insert(ty);
Ok(())
}
Err(err) => Err(format!("{}\nType mismatch `{}`", err, name)),
}
}
#[must_use]
pub fn fun<F: FnOnce(&mut Context, &mut Search) -> Result<bool, (Range, String)>>(
&mut self,
range: Range,
name: Arc<String>,
ty: Type,
search: &mut Search,
f: F
) -> Result<(), (Range, String)> {
if let Type::Pow(_) | Type::Fun(_) = &ty {
let mut ctx = Context::new();
ctx.symbols = self.symbols.clone();
let unsafe_flag = f(&mut ctx, search)?;
if ctx.prove(ty.clone(), search) && ctx.safe(&ty) {
if !unsafe_flag && !ty.is_safe_to_prove() {
return Err((range, format!("Not safe to prove `{}`\nUse `unsafe return`", ty.to_str(true, None))));
}
// Force the proof since it is safe.
let ty = ty.lift();
self.add_proof(ty.clone());
let is_use = false;
self.new_term((name, Term::FunDecl(ty)), is_use, search)
.map_err(|err| (range, err))?;
Ok(())
} else {Err((range, format!("Could not prove `{}`", ty.to_str(true, None))))}
} else {Err((range, "Expected `->`".into()))}
}
#[must_use]
pub fn lam<F: FnOnce(&mut Context, &mut Search) -> Result<bool, (Range, String)>>(
&mut self,
range: Range,
name: Arc<String>,
ty: Type,
search: &mut Search,
f: F
) -> Result<(), (Range, String)> {
if let Type::Imply(_) = ty {
let mut ctx = self.clone();
let unsafe_flag = f(&mut ctx, search)?;
if ctx.prove(ty.clone(), search) {
if !unsafe_flag && !ty.is_safe_to_prove() {
return Err((range, format!("Not safe to prove `{}`", ty.to_str(true, None))));
}
// Force the proof since it is safe.
self.add_proof(ty.clone());
let is_use = false;
self.new_term((name, Term::LamDecl(ty)), is_use, search)
.map_err(|err| (range, err))?;
Ok(())
} else {Err((range, format!("Could not prove `{}`", ty.to_str(true, None))))}
} else {Err((range, "Expected `=>`".into()))}
}
// Returns `true` if type is safe to add to list of proofs.
//
// There are only some exponential propositions (power) that are unsafe.
// If every initial term is covered in the assumption, then it is safe.
fn safe(&self, ty: &Type) -> bool {
if self.terms.len() == 0 {true}
else if let Type::Imply(_) = ty {true}
else if let Some(ab) = ty.fun_norm() {
let mut cover = true;
for term in &self.terms {
if term.is_safe() {continue};
let ty = term.get_type();
if !ty.is_covered(&ab.0) {
cover = false;
break;
}
}
cover
}
else {true}
}
fn fast_proof(&mut self, proof: &Type) -> bool {
use Type::*;
match proof {
True => true,
Sd(_) if proof.symbolic_distinct() => true,
_ => false,
}
}
pub fn has_proof(&mut self, proof: &Type) -> bool {
if self.proof_cache.contains(proof) {return true};
if self.proofs.iter().any(|n| n.has_bound(proof).is_ok()) {
self.proof_cache.insert(proof.clone());
true
} else if self.terms.iter().any(|n| n.get_type().has_bound(proof).is_ok()) {
self.proof_cache.insert(proof.clone());
true
} else if self.fast_proof(proof) {
self.proof_cache.insert(proof.clone());
true
} else {
false
}
}
pub fn proof_has(&self, proof: &Type) -> bool {
self.proofs.iter().any(|n| proof.has_bound(n).is_ok())
}
/// Adds a proof by first checking redundance.
pub fn add_proof(&mut self, proof: Type) {
if !self.has_proof(&proof) {
self.proofs.push(proof.clone());
self.proof_cache.insert(proof);
}
}
#[must_use]
pub fn prove_depth(&mut self, ty: Type, depth: u32, _search: &mut Search) -> bool {
if depth == 0 {return false}
if self.has_proof(&ty) {return true}
false
}
#[must_use]
pub fn prove(&mut self, ty: Type, search: &mut Search) -> bool {self.prove_depth(ty, 3, search)}
}
/// Represents a term.
#[derive(Clone, Debug)]
pub enum Term {
/// Proof `()` of some statement that can be proved.
Check(Type),
/// An axiom.
Axiom(Type),
/// A variable must be covered by context to be lifted.
Var(Type),
/// Function declaration.
FunDecl(Type),
/// Lambda declaration.
LamDecl(Type),
/// Function application.
App(Arc<String>, Vec<Arc<String>>, Type),
/// Match statement.
Match(Vec<Arc<String>>, Type),
}
lazy_static! {
static ref MATCH_TYPE: Type = {
// `(a | b) & ((a => c) & (b => c)) -> c`.
pow(ty("c"), and(or(ty("a"), ty("b")), and(imply(ty("a"), ty("c")), imply(ty("b"), ty("c")))))
};
}
impl Term {
pub fn is_safe(&self) -> bool {
use Term::*;
match self {
Var(_) => false,
Check(_) | Axiom(_) | FunDecl(_) | LamDecl(_) | App(..) | Match(..) => true,
}
}
pub fn get_type(&self) -> Type {
use Term::*;
match self {
Check(t) => t.clone(),
Axiom(t) => t.clone(),
Var(t) => t.clone(),
FunDecl(ty) => ty.clone(),
LamDecl(ty) => ty.clone(),
App(_, _, t) => t.clone(),
Match(_, t) => t.clone(),
}
}
pub fn has_type(
&self,
ty: &Type,
ctx: &mut Context,
search: &mut Search
) -> Result<(), String> {
use Term::*;
match self {
App(f, args, t) if t.has_bound(ty).is_ok() => {
let mut fun_decl: Option<usize> = None;
let mut arg_inds: Vec<Option<usize>> = vec![None; args.len()];
for (i, term_name) in ctx.term_names.iter().enumerate().rev() {
if term_name == f {
fun_decl = Some(i);
}
}
for (j, arg) in args.iter().enumerate() {
for (i, term_name) in ctx.term_names.iter().enumerate().rev() {
if term_name == arg {
arg_inds[j] = Some(i);
break;
}
}
}
for (i, arg_ind) in arg_inds.iter().enumerate() {
if arg_ind.is_none() {
return Err(format!("Argument `{}` is not found", args[i]));
}
}
if let Some(fun_decl) = fun_decl {
let ty_f = ctx.terms[fun_decl].get_type();
let ty_f = if let Type::All(x) = ty_f {(*x).clone()} else {ty_f};
if args.len() == 0 {
if ty_f.has_bound(t).is_ok() {return Ok(())};
if let Some(ty) = ty.de_all() {
if ty_f.has_bound(&ty).is_ok() {return Ok(())};
}
Err(format!("Expected:\n\n {}\n\nFound:\n\n {}\n", ty, ty_f))
} else {
let arg_ind = arg_inds.pop().unwrap();
let mut ty_arg = ctx.terms[arg_ind.unwrap()].get_type();
for arg_ind in arg_inds.into_iter().rev() {
ty_arg = and(ctx.terms[arg_ind.unwrap()].get_type(), ty_arg);
}
if let Some(ab) = ty_f.fun_norm() {
return ty_arg.app_to_has_bound(&ab.0, &ab.1, t).map_err(|err| {
format!("Expected:\n\n {}\n\n\
Could not apply:\n\n {}\n\n To:\n\n {}\n\n{}",
t, ty_f, ty_arg, err)
});
} else {
return Err("Expected `->` or `=>`".into());
}
}
} else {
return Err(format!("Could not find `{}`", f));
}
}
Match(args, t) if t.has_bound(ty).is_ok() => {
let mut arg_inds: Vec<Option<usize>> = vec![None; args.len()];
for (j, arg) in args.iter().enumerate() {
for (i, term_name) in ctx.term_names.iter().enumerate().rev() {
if term_name == arg {
arg_inds[j] = Some(i);
break;
}
}
}
for (i, arg_ind) in arg_inds.iter().enumerate() {
if arg_ind.is_none() {
return Err(format!("Argument `{}` is not found", args[i]));
}
}
let arg_ind = arg_inds.pop().unwrap();
let mut ty_arg = ctx.terms[arg_ind.unwrap()].get_type();
for arg_ind in arg_inds.into_iter().rev() {
ty_arg = and(ctx.terms[arg_ind.unwrap()].get_type(), ty_arg);
}
let ty_f: Type = if args.len() == 1 {pow(crate::ty("a"), Type::False)}
else {MATCH_TYPE.clone()};
if let Type::Pow(ab) = ty_f.lift() {
return ty_arg.app_to_has_bound(&ab.1, &ab.0, t);
}
return Err(format!("Match failed. Expected:\n\n {}\n", t));
}
Axiom(t) => {
if t.has_bound(ty).is_ok() {return Ok(())}
else {return Err(format!(
"Type check error #300\nExpected `{}`, found `{}`",
ty, t
))}
}
FunDecl(t) if t.has_bound(ty).is_ok() => Ok(()),
LamDecl(t) if t.has_bound(ty).is_ok() => Ok(()),
Var(t) if t.has_bound(ty).is_ok() => Ok(()),
Check(t) if ctx.prove(t.clone(), search) &&
ctx.prove(ty.clone(), search) => Ok(()),
_ => return Err("Type check error #100".into()),
}
}
}
/// Represent types.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Type {
/// Unit type.
True,
/// Empty type.
False,
/// A type variable that binds to expressions of same name.
Ty(Arc<String>),
/// A type variable that can bind to any expression.
AllTy(Arc<String>),
/// Exponential type (reverse function pointer).
Pow(Box<(Type, Type)>),
/// Function pointer.
Fun(Box<(Type, Type)>),
/// Tuple.
And(Box<(Type, Type)>),
/// Or.
Or(Box<(Type, Type)>),
/// Imply.
Imply(Box<(Type, Type)>),
/// For-all.
All(Box<Type>),
/// Symbol.
Sym(Arc<String>),
/// Locally declared symbol.
LocSym(Arc<String>),
/// Application.
App(Box<(Type, Type)>),
/// Symbolic distinction.
Sd(Box<(Type, Type)>),
/// Type judgement.
Jud(Box<(Type, Type)>),
/// Function composition.
Comp(Box<(Type, Type)>),
/// Necessary (modal logic).
Nec(Box<Type>),
/// Possibly (modal logoc).
Pos(Box<Type>),
/// Path semantical qubit.
Qu(Box<Type>),
/// Path semantical quality.
Q(Box<(Type, Type)>),
/// Avatar Logic pair.
Pair(Box<(Type, Type)>),
/// Symbolic block (used to freeze variables).
SymBlock(Box<(Arc<String>, Type)>),
}
#[derive(Copy, Clone)]
pub enum Op {
Pow,
Fun,
And,
Or,
Imply,
Not,
Eq,
Excm,
PowEq,
All,
App,
Sd,
Jud,
Comp,
Nec,
Pos,
Qu,
Q,
Pair,
SymBlock,
}
fn needs_parens(ty: &Type, parent_op: Option<Op>) -> bool {
use Type::*;
if ty.as_not().is_some() ||
ty.as_nec().is_some() ||
ty.as_pos().is_some() ||
ty.as_qu().is_some() ||
ty.as_sym_block().is_some() {
if let Some(Op::Pow) = parent_op {return true};
return false;
}
if ty.as_excm().is_some() {return false};
match ty {
True | False | Ty(_) | AllTy(_) | All(_) |
App(_) | Sym(_) | Nec(_) | Qu(_) | Pair(_) => false,
_ => {
match (ty.op(), parent_op) {
(Some(Op::Pow), Some(Op::And | Op::Or | Op::Imply | Op::Fun)) => false,
_ => true,
}
}
}
}
impl Type {
pub fn op(&self) -> Option<Op> {
use Type::*;
if self.as_not().is_some() {return Some(Op::Not)};
if self.as_eq().is_some() {return Some(Op::Eq)};
if self.as_excm().is_some() {return Some(Op::Excm)};
if self.as_pow_eq().is_some() {return Some(Op::PowEq)};
match self {
True | False | Ty(_) | AllTy(_) => None,
Pow(_) => Some(Op::Pow),
Fun(_) => Some(Op::Fun),
And(_) => Some(Op::And),
Or(_) => Some(Op::Or),
Imply(_) => Some(Op::Imply),
All(_) => Some(Op::All),
Sym(_) => None,
LocSym(_) => None,
App(_) => Some(Op::App),
Sd(_) => Some(Op::Sd),
Jud(_) => Some(Op::Jud),
Comp(_) => Some(Op::Comp),
Nec(_) => Some(Op::Nec),
Pos(_) => Some(Op::Pos),
Qu(_) => Some(Op::Qu),
Q(_) => Some(Op::Q),
Pair(_) => Some(Op::Pair),
SymBlock(_) => Some(Op::SymBlock),
}
}
pub fn symbolic_distinct(&self) -> bool {
if let Type::Sd(ab) = self {
if let (Type::Sym(a), Type::Sym(b)) = &**ab {
if a != b {return true} else {false}
} else {false}
} else {false}
}
pub fn as_not(&self) -> Option<&Type> {
if let Type::Imply(ab) = self {
if let Type::False = ab.1 {Some(&ab.0)} else {None}
} else {None}
}
pub fn as_nec(&self) -> Option<&Type> {
if let Type::Nec(a) = self {Some(a)} else {None}
}
pub fn as_pos(&self) -> Option<&Type> {
if let Type::Pos(a) = self {Some(a)} else {None}
}
pub fn as_qu(&self) -> Option<&Type> {
if let Type::Qu(a) = self {Some(a)} else {None}
}
pub fn as_sym_block(&self) -> Option<(&Arc<String>, &Type)> {
if let Type::SymBlock(ab) = self {Some((&ab.0, &ab.1))} else {None}
}
pub fn as_eq(&self) -> Option<(&Type, &Type)> {
if let Type::And(ab) = self {
if let (Type::Imply(ab), Type::Imply(cd)) = &**ab {
if ab.0 == cd.1 && ab.1 == cd.0 {Some((&ab.0, &ab.1))} else {None}
} else {None}
} else {None}
}
pub fn as_excm(&self) -> Option<&Type> {
if let Type::Or(ab) = self {
if let Some(b) = ab.1.as_not() {
if &ab.0 == b {return Some(&ab.0)} else {None}
} else {None}
} else {None}
}
pub fn as_pow_eq(&self) -> Option<(&Type, &Type)> {
if let Type::And(ab) = self {
if let (Type::Pow(ab), Type::Pow(cd)) = &**ab {
if ab.1 == cd.0 && ab.0 == cd.1 {Some((&ab.1, &ab.0))} else {None}
} else {None}
} else {None}
}
pub fn as_app_sym(&self) -> Option<(&Arc<String>, &Type)> {
if let Type::App(ab) = self {
if let Type::Sym(s) = &ab.0 {
return Some((s, &ab.1));
} else {None}
} else {None}
}
pub fn as_multi_app(&self) -> Option<(&Type, Vec<&Type>)> {
let mut args: Vec<&Type> = vec![];
let mut ty = self;
loop {
if let Type::App(ab) = ty {
args.push(&ab.1);
ty = &ab.0;
} else {
if args.len() < 2 {return None}
else {
args.reverse();
return Some((ty, args))
}
}
}
}
pub fn to_str(&self, top: bool, parent_op: Option<Op>) -> String {
if !top && needs_parens(self, parent_op) {format!("({})", self)}
else {format!("{}", self)}
}
}
impl fmt::Display for Type {
fn fmt(&self, w: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
use Type::*;
let op = self.op();
if let Some(a) = self.as_not() {
return write!(w, "!{}", a.to_str(false, op));
}
if let Some((a, b)) = self.as_eq() {
return write!(w, "{} == {}", a.to_str(false, op), b.to_str(false, op));
}
if let Some(a) = self.as_excm() {
return write!(w, "excm({})", a);
}
if let Some((a, b)) = self.as_pow_eq() {
return write!(w, "{} =^= {}", a, b);
}
if let Some((f, args)) = self.as_multi_app() {
write!(w, "{}(", f.to_str(false, None))?;
let mut first = true;
for arg in args {
if !first {
write!(w, ", ")?;
}
first = false;
write!(w, "{}", arg)?;
}
return write!(w, ")");
}
match self {
True => write!(w, "true")?,
False => write!(w, "false")?,
Ty(a) => write!(w, "{}", a)?,
AllTy(a) => write!(w, "{}", a)?,
Pow(ab) => write!(w, "{}^{}", ab.0.to_str(false, op), ab.1.to_str(false, op))?,
Fun(ab) => write!(w, "{} -> {}", ab.0.to_str(false, op), ab.1.to_str(false, op))?,
And(ab) => write!(w, "{} & {}", ab.0.to_str(false, op), ab.1.to_str(false, op))?,
Or(ab) => write!(w, "{} | {}", ab.0.to_str(false, op), ab.1.to_str(false, op))?,
Imply(ab) => write!(w, "{} => {}", ab.0.to_str(false, op), ab.1.to_str(false, op))?,
All(a) => write!(w, "all({})", a.to_str(true, op))?,
Sym(a) => write!(w, "{}'", a)?,
LocSym(a) => write!(w, "sym {}", a)?,
App(ab) => write!(w, "{}({})", ab.0.to_str(false, op), ab.1)?,
Sd(ab) => write!(w, "sd({}, {})", ab.0, ab.1)?,
Jud(ab) => write!(w, "{} : {}", ab.0.to_str(false, op), ab.1.to_str(true, op))?,
Comp(ab) => write!(w, "{} . {}", ab.0, ab.1)?,
Nec(a) => write!(w, "□{}", a.to_str(false, op))?,
Pos(a) => write!(w, "◇{}", a.to_str(false, op))?,
Qu(a) => write!(w, "~{}", a.to_str(false, op))?,
Q(ab) => write!(w, "{} ~~ {}", ab.0.to_str(false, op), ab.1.to_str(false, op))?,
Pair(ab) => write!(w, "({}, {})", ab.0.to_str(true, op), ab.1.to_str(true, op))?,
SymBlock(ab) => write!(w, "sym({}, {})", ab.0, ab.1.to_str(true, op))?,
}
Ok(())
}
}
impl TryFrom<&str> for Type {
type Error = String;
fn try_from(s: &str) -> Result<Type, String> {
parsing::parse_ty_str(s, &MetaCache::new())
}
}
/// Type alias for binding variables.
///
/// The last binding flag tells whether it was a variable from a sym block.
/// This is used to avoid an edge case where the body of the sym block
/// is more general than some symbol bound to the bounded sym block (other, not pattern).
pub type Bind = (Type, Type, bool);
impl Type {
pub fn is_safe_to_prove(&self) -> bool {
use Type::*;
match self {
True | False | Ty(_) => true,
And(ab) => ab.0.is_safe_to_prove() && ab.1.is_safe_to_prove(),
Or(ab) => ab.0.is_safe_to_prove() && ab.1.is_safe_to_prove(),
Imply(ab) => ab.1.is_safe_to_prove(),
Pow(ab) => ab.0.is_safe_to_prove(),
Fun(ab) => ab.1.is_safe_to_prove(),
AllTy(_) | All(_) => false,
Sym(_) => true,
LocSym(_) => true,
App(ab) => {
if let SymBlock(_) = &ab.0 {false} else {true}
}
Sd(_) => true,
Jud(_) => true,
Comp(_) => true,
Nec(_) => true,
Pos(_) => true,
Qu(_) => true,
Q(_) => true,
Pair(_) => true,
SymBlock(ab) => ab.1.is_safe_to_prove(),
}
}
pub fn is_covered(&self, other: &Type) -> bool {
use Type::*;
if self.has_bound(other).is_ok() {return true};
match other {
And(ab) => self.is_covered(&ab.0) || self.is_covered(&ab.1),
_ => false,
}
}
pub fn lift(self) -> Type {
use Type::*;
match self {
True => True,
False => False,
Ty(a) => AllTy(a),
AllTy(a) => AllTy(a),
And(ab) => and(ab.0.lift(), ab.1.lift()),
Imply(ab) => imply(ab.0.lift(), ab.1.lift()),
Pow(ab) => pow(ab.0.lift(), ab.1.lift()),
Fun(ab) => fun(ab.0.lift(), ab.1.lift()),
Or(ab) => or(ab.0.lift(), ab.1.lift()),
All(_) => self,
Sym(_) => self,
LocSym(_) => self,
App(ab) => app(ab.0.lift(), ab.1.lift()),
Sd(ab) => sd(ab.0.lift(), ab.1.lift()),
Jud(ab) => jud(ab.0.lift(), ab.1.lift()),
Comp(ab) => comp(ab.0.lift(), ab.1.lift()),
Nec(a) => nec(a.lift()),
Pos(a) => pos(a.lift()),
Qu(a) => qu(a.lift()),
Q(ab) => q(ab.0.lift(), ab.1.lift()),
Pair(ab) => pair(ab.0.lift(), ab.1.lift()),
SymBlock(ab) => sym_block(ab.0.clone(), ab.1.lift()),
}
}
/// Binds variables.
#[must_use]
pub fn bind(
&self,
contra: bool,
val: &Type,
bind: &mut Vec<Bind>
) -> Result<(), String> {
use Type::*;
fn bind_ty<F: FnOnce(&mut Vec<Bind>)>(
bind: &mut Vec<(Type, Type, bool)>,
a: &Type,
b: &Type,
f: F,
) -> Result<(), String> {
let mut found = false;
for (ty, val, sym_block) in bind.iter() {
if ty == a {
if val != b && val.clone().lift() != b.clone().lift() {
return Err(format!("Could not unify:\n\n {}\n\nWith:\n\n {}\n", a, b));
}
found = true;
break;
}
if *sym_block {
if val == b {
return Err(format!("Symbol used by sym block:\n\n {}\n\nWith:\n\n {}\n", a, b));
}
}
}
if !found {f(bind)};
Ok(())
}
if self.fun_stronger(val, contra) {
if let (Some(ab), Some(cd)) = (self.fun_norm(), val.fun_norm()) {
let _ = ab.0.bind(!contra, &cd.0, bind)?;
return ab.1.bind(contra, &cd.1, bind);
}
}
match (self, val) {
(True, True) => Ok(()),
(False, False) => Ok(()),
(Ty(a), Ty(b)) => if a == b {Ok(())}
else {Err(format!("Could not unify type:\n\n {}\n\nWith:\n\n {}\n", a, b))},
(LocSym(a), LocSym(b)) => if a == b {Ok(())}
else {
for (ty, _, _) in bind.iter() {
if let Type::Sym(name) = ty {
if name == a {
return Err(format!("Local symbol already bound:\n\n {}\n", a))
}
}
}
bind.push((Sym(a.clone()), Sym(b.clone()), false));
Ok(())
},
(Sym(a), Sym(b)) => {
for (ty, v, _) in bind.iter() {
if let Type::Sym(name) = ty {
if name == a && val == v {return Ok(())}
}
}
if a == b {Ok(())}
else {Err(format!("Could not unify symbol:\n\n {}\n\nWith:\n\n {}\n", a, b))}
}
(Sym(a), b) => {
for (ty, val, _) in bind.iter() {
if let Type::Sym(name) = ty {
if name == a && b == val {return Ok(())}
}
}
Err(format!("Could not find symbol:\n\n {}\n\nWith binding:\n\n {}\n", a, b))
}
(Nec(a), Nec(b)) |
(Pos(a), Pos(b)) |
(Qu(a), Qu(b)) => a.bind(contra, b, bind),
(And(ab), And(cd)) |
(Or(ab), Or(cd)) |
(App(ab), App(cd)) |
(Sd(ab), Sd(cd)) |
(Jud(ab), Jud(cd)) |
(Comp(ab), Comp(cd)) |
(Q(ab), Q(cd)) |
(Pair(ab), Pair(cd)) => {
let _ = ab.0.bind(contra, &cd.0, bind)?;
ab.1.bind(contra, &cd.1, bind)
}
(AllTy(_), _) => bind_ty(bind, self, val, |bind|
bind.push((self.clone(), val.clone(), false))),
(_, AllTy(_)) => Ok(()),
(App(ab), x) => {
if let Type::SymBlock(s_ab) = &ab.0 {
let n = bind.len();
bind.push((Type::Sym(s_ab.0.clone()), ab.1.clone(), false));
let res = s_ab.1.bind(contra, &x, bind);
if res.is_ok() {
let ty = s_ab.1.replace(bind);
bind.truncate(n);
bind.push((self.clone(), ty, false));
return Ok(());
} else {
bind.truncate(n);
}
}
Err(format!("Expected sym block:\n\n {}\n", ab.0))
}
(All(a), All(b)) => {
let (a, b) = if contra {(b, a)} else {(a, b)};
let mut bind2: Vec<Bind> = bind.iter()
.filter(|(a, b, _)| {
if contra {
if let Sym(_) = b {true} else {false}
} else {
if let Sym(_) = a {true} else {false}
}
})
.map(|(a, b, sym_block)| if contra {(b.clone(), a.clone(), *sym_block)}
else {(a.clone(), b.clone(), *sym_block)})
.collect();
let _ = a.bind(contra, b, &mut bind2)?;
let res = a.replace(&bind2);
bind.push((self.clone(), All(Box::new(res)), false));
Ok(())
}
(All(a), b) if !contra => a.bind(contra, b, bind),
(SymBlock(ab), SymBlock(cd)) => {
let n = bind.len();
bind.push((Sym(ab.0.clone()), Sym(cd.0.clone()), true));
let res = ab.1.bind(contra, &cd.1, bind);
if res.is_ok() {
let ty = self.replace(bind);
bind.truncate(n);
bind.push((self.clone(), ty, false));
} else {bind.truncate(n)};
res
}
// (_, App(_)) => self.sym_block_bind(contra, val, bind),
_ => Err(format!("Could not bind:\n\n {}\n\nTo:\n\n {}\n", self, val)),
}
}
pub fn replace(&self, bind: &[Bind]) -> Type {
use Type::*;
for (arg, val, _) in bind {
if arg == self {return val.clone()}
}
match self {
True => self.clone(),
False => self.clone(),
Ty(_) => self.clone(),
Sym(_) => self.clone(),
AllTy(_) => self.clone(),
LocSym(a) => {
for (arg, val, _) in bind {
if let Sym(name) = arg {
if name == a {
if let Sym(other_name) = val {
return LocSym(other_name.clone());
}
}
}
}
self.clone()
}
Pow(ab) => pow(ab.0.replace(bind), ab.1.replace(bind)),
Fun(ab) => fun(ab.0.replace(bind), ab.1.replace(bind)),
Imply(ab) => imply(ab.0.replace(bind), ab.1.replace(bind)),
And(ab) => and(ab.0.replace(bind), ab.1.replace(bind)),
Or(ab) => or(ab.0.replace(bind), ab.1.replace(bind)),
App(ab) => app(ab.0.replace(bind), ab.1.replace(bind)),
All(a) => All(Box::new(a.replace(bind))),
Sd(ab) => sd(ab.0.replace(bind), ab.1.replace(bind)),
Jud(ab) => jud(ab.0.replace(bind), ab.1.replace(bind)),
Comp(ab) => comp(ab.0.replace(bind), ab.1.replace(bind)),
Nec(a) => nec(a.replace(bind)),
Pos(a) => pos(a.replace(bind)),
Qu(a) => qu(a.replace(bind)),
Q(ab) => q(ab.0.replace(bind), ab.1.replace(bind)),
Pair(ab) => pair(ab.0.replace(bind), ab.1.replace(bind)),