Source file reduction.ml
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
open Basic
open Rule
open Term
open Dtree
open Ac
let d_reduce = Debug.register_flag "Reduce"
type red_target = Snf | Whnf
type red_strategy = ByName | ByValue | ByStrongValue
type dtree_finder = Signature.t -> Basic.loc -> Basic.name -> t
type red_cfg = {
select : (Rule.rule_name -> bool) option;
nb_steps : int option;
target : red_target;
strat : red_strategy;
beta : bool;
logger : position -> Rule.rule_name -> term Lazy.t -> term Lazy.t -> unit;
finder : dtree_finder;
}
let pp_red_cfg fmt cfg =
let args =
(match cfg.target with Snf -> ["SNF"] | _ -> [])
@ (match cfg.strat with
| ByValue -> ["CBV"]
| ByStrongValue -> ["CBSV"]
| _ -> [])
@ match cfg.nb_steps with Some i -> [string_of_int i] | _ -> []
in
Format.fprintf fmt "[%a]" (pp_list "," Format.pp_print_string) args
let default_cfg =
{
select = None;
nb_steps = None;
target = Snf;
strat = ByName;
beta = true;
logger = (fun _ _ _ _ -> ());
finder = Signature.get_dtree;
}
exception Not_convertible
let rec zip_lists l1 l2 lst =
match (l1, l2) with
| [], [] -> lst
| s1 :: l1, s2 :: l2 -> zip_lists l1 l2 ((s1, s2) :: lst)
| _, _ -> raise Not_convertible
type env = term Lazy.t LList.t
type state = {
ctx : env;
term : term;
stack : stack;
}
and stack = state ref list
let rec term_of_state {ctx; term; stack} : term =
let t = if LList.is_empty ctx then term else Subst.psubst_l ctx term in
mk_App2 t (List.map term_of_state_ref stack)
and term_of_state_ref r = term_of_state !r
let state_of_term t = {ctx = LList.nil; term = t; stack = []}
let state_ref_of_term t = ref {ctx = LList.nil; term = t; stack = []}
type convertibility_test = Signature.t -> term -> term -> bool
module type ConvChecker = sig
val are_convertible : convertibility_test
val constraint_convertibility :
Rule.constr -> Rule.rule_name -> convertibility_test
val conversion_step :
Signature.t -> term * term -> (term * term) list -> (term * term) list
end
module type S = sig
include ConvChecker
val reduction : red_cfg -> Signature.t -> term -> term
val whnf : Signature.t -> term -> term
val snf : Signature.t -> term -> term
end
let eta = ref false
let beta = ref true
let selection = ref None
let dtree_finder : dtree_finder ref = ref Signature.get_dtree
module Make (C : ConvChecker) (M : Matching.Matcher) : S = struct
let filter_neutral sg l cst terms =
match Signature.get_algebra sg l cst with
| ACU neu -> (
match List.filter (fun x -> not (C.are_convertible sg neu x)) terms with
| [] -> [neu]
| s -> s)
| _ -> terms
(** Builds a comb-shaped AC term from a list of arguments. *)
let to_comb sg l cst ctx stack =
let rec f = function
| [] ->
{ctx = LList.nil; term = Signature.get_neutral sg l cst; stack = []}
| [t] -> !t
| t1 :: t2 :: tl ->
f (ref {ctx; term = mk_Const l cst; stack = [t1; t2]} :: tl)
in
f stack
let rec flatten_AC_stack sg (cst : name) : stack -> stack =
let rec flatten acc = function
| [] -> acc
| st :: tl -> (
match !st with
| {term = Const (_, cst'); stack = [st1; st2]; _}
when name_eq cst cst' ->
flatten acc (st1 :: st2 :: tl)
| _ -> (
st := state_whnf sg !st;
match !st with
| {term = Const (_, cst'); stack = [st1; st2]; _}
when name_eq cst cst' ->
flatten acc (st1 :: st2 :: tl)
| _ -> flatten (st :: acc) tl))
in
flatten []
and comb_state_if_AC alg sg st =
if Term.is_AC alg then
match st with
| {ctx; term = Const (l, cst); stack = s1 :: s2 :: rstack; _} ->
let nstack = flatten_AC_stack sg cst [s1; s2] in
let nstack =
match alg with
| ACU neu ->
List.filter
(fun st ->
not (C.are_convertible sg (term_of_state_ref st) neu))
nstack
| _ -> nstack
in
let combed = to_comb sg l cst ctx nstack in
let fstack =
match rstack with [] -> combed.stack | l -> combed.stack @ l
in
{combed with stack = fstack}
| st -> st
else st
and comb_term_if_AC sg : term -> term = function
| App (Const (l, cst), a1, a2 :: remain_args) as t ->
let alg = Signature.get_algebra sg l cst in
if is_AC alg then
let id_comp = Signature.get_id_comparator sg in
let args = flatten_AC_terms cst [a1; a2] in
let args = filter_neutral sg l cst args in
let args = List.sort (compare_term id_comp) args in
let _ = assert (List.length args > 0) in
mk_App2 (unflatten_AC (cst, alg) args) remain_args
else t
| t -> t
and find_case sg (st : state) (case : case) : stack option =
match (st, case) with
| {term = Const (_, cst); stack; _}, CConst (nargs, cst', false) ->
if name_eq cst cst' && List.length stack == nargs then Some stack
else None
| {ctx; term = DB (_, _, n); stack; _}, CDB (nargs, n') ->
assert (ctx = LList.nil);
if n == n' && List.length stack == nargs then Some stack else None
| {term = Lam (_, _, _, _); _}, CLam -> (
match term_of_state st with
| Lam (_, _, _, te) -> Some [state_ref_of_term te]
| _ -> assert false)
| ( {term = Const (_, cst); stack = t1 :: t2 :: s; _},
CConst (nargs, cst', true) )
when name_eq cst cst' && nargs == List.length s + 2 ->
Some (ref {st with stack = flatten_AC_stack sg cst [t1; t2]} :: s)
| {ctx; term; stack}, CConst (nargs, cst, true)
when List.length stack == nargs - 2 ->
let new_st = ref {ctx; term; stack = []} in
let new_stack = flatten_AC_stack sg cst [new_st] in
Some (ref {ctx; term = mk_Const dloc cst; stack = new_stack} :: stack)
| _ -> None
and fetch_case sg (state : state ref) (case : case) (dt_suc : dtree)
(dt_def : dtree option) : (dtree * state ref * stack) list =
let def_s = match dt_def with None -> [] | Some g -> [(g, state, [])] in
let stack = !state.stack in
match !state.term with
| Const _ ->
let rec f acc (stack_acc : state ref list) st =
match (st, case) with
| [], _ -> acc
| hd :: tl, _ ->
let new_stack_acc = hd :: stack_acc in
let new_acc =
match find_case sg !hd case with
| None -> acc
| Some s ->
let new_stack = List.rev_append stack_acc tl in
let new_state = ref {!state with stack = new_stack} in
(dt_suc, new_state, s) :: acc
in
f new_acc new_stack_acc tl
in
List.rev_append (f [] [] stack) def_s
| _ -> assert false
and find_cases sg (st : state) (cases : (case * dtree) list)
(default : dtree option) : (dtree * stack) list =
List.fold_left
(fun acc (case, tr) ->
match find_case sg st case with
| None -> acc
| Some stack -> (tr, stack) :: acc)
(match default with None -> [] | Some g -> [(g, [])])
cases
and gamma_rw (sg : Signature.t) (filter : (Rule.rule_name -> bool) option) :
stack -> dtree -> (rule_name * env * term) option =
let rec rw_list : (stack * dtree) list -> (rule_name * env * term) option =
function
| [] -> None
| [(stack, tree)] -> rw stack tree
| (stack, tree) :: tl -> (
match rw stack tree with None -> rw_list tl | x -> x)
and rw (stack : stack) : dtree -> (rule_name * env * term) option = function
| Fetch (i, case, dt_suc, dt_def) ->
let rec split_ith acc i l =
match (i, l) with
| 0, h :: t -> (acc, h, t)
| i, h :: t -> split_ith (h :: acc) (i - 1) t
| _ -> assert false
in
let stack_h, arg_i, stack_t = split_ith [] i stack in
assert (
match !arg_i.term with
| Const (l, cst) -> Signature.is_AC sg l cst
| _ -> false);
let process (g, new_s, s) =
( List.rev_append stack_h
(new_s :: (match s with [] -> stack_t | s -> stack_t @ s)),
g )
in
let cases =
fetch_case sg arg_i case dt_suc dt_def
in
let new_cases = List.map process cases in
rw_list new_cases
| ACEmpty (i, dt_suc, dt_def) -> (
match !(List.nth stack i) with
| {term = Const (l, cst); stack = st; _} ->
assert (Signature.is_AC sg l cst);
if st = [] then rw stack dt_suc else bind_opt (rw stack) dt_def
| _ -> assert false)
| Switch (i, cases, def) ->
let arg_i = List.nth stack i in
arg_i := state_whnf sg !arg_i;
let new_cases =
List.map
(fun (g, l) -> (concat stack l, g))
(find_cases sg !arg_i cases def)
in
rw_list new_cases
| Test (rule_name, matching_pb, cstr, right, def) ->
let keep_rule =
match filter with None -> true | Some f -> f rule_name
in
if keep_rule then (
let convert i =
let te = List.nth stack i in
lazy (term_of_state_ref te)
in
let convert_ac i =
List.map
(fun s -> lazy (term_of_state_ref s))
!(List.nth stack i).stack
in
match
M.solve_problem rule_name sg convert convert_ac matching_pb
with
| None -> bind_opt (rw stack) def
| Some ctx ->
List.iter
(fun (i, t2) ->
let t1 = Lazy.force (LList.nth ctx i) in
let t2 = term_of_state {ctx; term = t2; stack = []} in
if
not
(C.constraint_convertibility (i, t2) rule_name sg t1 t2)
then
raise
(Signature.Signature_error
(Signature.GuardNotSatisfied (get_loc t1, t1, t2))))
cstr;
Some (rule_name, ctx, right))
else bind_opt (rw stack) def
in
rw
and state_whnf (sg : Signature.t) (st : state) : state =
let rec_call ctx term stack = state_whnf sg {ctx; term; stack} in
match st with
| {term = Type _; _}
| {term = Kind; _}
| {term = Pi _; _}
| {term = Lam _; stack = []; _} ->
st
| {ctx; term = DB (l, x, n); stack} ->
if LList.is_empty ctx then st
else if n < LList.len ctx then
state_whnf sg
{ctx = LList.nil; term = Lazy.force (LList.nth ctx n); stack}
else {ctx = LList.nil; term = mk_DB l x (n - LList.len ctx); stack}
| {ctx; term = Lam (_, _, _, t); stack = p :: s; _} ->
if not !beta then st
else rec_call (LList.cons (lazy (term_of_state_ref p)) ctx) t s
| {ctx; term = App (f, a, lst); stack = s; _} ->
let tl' =
List.rev_map (fun t -> ref {ctx; term = t; stack = []}) (a :: lst)
in
rec_call ctx f (List.rev_append tl' s)
| {ctx; term = Const (l, n); stack; _} -> (
let trees = !dtree_finder sg l n in
match find_dtree (List.length stack) trees with
| alg, None -> comb_state_if_AC alg sg st
| alg, Some (ar, tree) -> (
let s1, s2 = split ar stack in
let s1 =
if ar > 1 && Term.is_AC alg then
match s1 with
| t1 :: t2 :: tl ->
let flat = flatten_AC_stack sg n [t1; t2] in
ref {ctx; term = mk_Const l n; stack = flat} :: tl
| _ -> assert false
else s1
in
match gamma_rw sg !selection s1 tree with
| None -> comb_state_if_AC alg sg st
| Some (_, ctx, term) -> rec_call ctx term s2))
and whnf sg term = term_of_state (state_whnf sg (state_of_term term))
and snf sg (t : term) : term =
match whnf sg t with
| (Kind | Const _ | DB _ | Type _) as t' -> t'
| App (f, a, lst) ->
let res = mk_App (snf sg f) (snf sg a) (List.map (snf sg) lst) in
comb_term_if_AC sg res
| Pi (_, x, a, b) -> mk_Pi dloc x (snf sg a) (snf sg b)
| Lam (_, x, a, b) -> mk_Lam dloc x (map_opt (snf sg) a) (snf sg b)
and conversion_step sg :
term * term -> (term * term) list -> (term * term) list =
fun (l, r) lst ->
match (l, r) with
| Kind, Kind | Type _, Type _ -> lst
| Const (_, n), Const (_, n') when name_eq n n' -> lst
| DB (_, _, n), DB (_, _, n') when n == n' -> lst
| App (Const (lc, cst), _, _), App (Const (_, cst'), _, _)
when Signature.is_AC sg lc cst && name_eq cst cst' -> (
match (snf sg l, snf sg r) with
| App (Const (_, cst2), a, args), App (Const (_, cst2'), a', args')
when name_eq cst2 cst && name_eq cst2' cst && name_eq cst2 cst'
&& name_eq cst2' cst' ->
(a, a') :: zip_lists args args' lst
| p -> p :: lst)
| App (f, a, args), App (f', a', args') ->
(f, f') :: (a, a') :: zip_lists args args' lst
| Lam (_, _, _, b), Lam (_, _, _, b') -> (b, b') :: lst
| Lam (_, i, _, b), a when !eta ->
let b' = mk_App (Subst.shift 1 a) (mk_DB dloc i 0) [] in
(b, b') :: lst
| a, Lam (_, i, _, b) when !eta ->
let b' = mk_App (Subst.shift 1 a) (mk_DB dloc i 0) [] in
(b, b') :: lst
| Pi (_, _, a, b), Pi (_, _, a', b') -> (a, a') :: (b, b') :: lst
| t1, t2 ->
Debug.(debug d_reduce "Not convertible: %a / %a" pp_term t1 pp_term t2);
raise Not_convertible
let rec are_convertible_lst sg : (term * term) list -> bool = function
| [] -> true
| (t1, t2) :: lst ->
are_convertible_lst sg
(if t1 == t2 then lst
else if term_eq t1 t2 then lst
else conversion_step sg (whnf sg t1, whnf sg t2) lst)
let are_convertible sg t1 t2 =
try are_convertible_lst sg [(t1, t2)]
with Not_convertible | Invalid_argument _ -> false
type state_reducer = position -> state -> state
type term_reducer = position -> term -> term
let logged_state_whnf log stop (strat : red_strategy) (sg : Signature.t) :
state_reducer =
let rec aux : state_reducer =
fun (pos : position) (st : state) ->
if stop () then st
else
match (st, strat) with
| {term = Type _; _}, _ | {term = Kind; _}, _ -> st
| {term = Pi _; _}, ByName | {term = Pi _; _}, ByValue -> st
| {ctx; term = Pi (l, x, a, b); _}, ByStrongValue ->
let a' =
term_of_state (aux (0 :: pos) {ctx; term = a; stack = []})
in
{st with term = mk_Pi l x a' b}
| {ctx; term = Lam (l, x, Some ty, t); stack = []; _}, ByStrongValue ->
let ty' =
term_of_state (aux (0 :: pos) {ctx; term = ty; stack = []})
in
{st with term = mk_Lam l x (Some ty') t}
| {term = Lam _; stack = []; _}, _ -> st
| {ctx; term = Lam (l, x, Some ty, t); stack = p :: s; _}, ByStrongValue
->
let ty' =
term_of_state (aux (0 :: pos) {ctx; term = ty; stack = []})
in
if stop () || not !beta then
{st with term = mk_Lam l x (Some ty') t}
else
let st' =
{
ctx = LList.cons (lazy (term_of_state_ref p)) ctx;
term = t;
stack = s;
}
in
let _ = log pos Rule.Beta st st' in
aux pos st'
| {ctx; term = Lam (_, _, _, t); stack = p :: s; _}, _ ->
if not !beta then st
else
let st' =
{
ctx = LList.cons (lazy (term_of_state_ref p)) ctx;
term = t;
stack = s;
}
in
let _ = log pos Rule.Beta st st' in
aux pos st'
| {ctx; term = DB (l, x, n); stack; _}, _ ->
if n < LList.len ctx then
aux pos
{ctx = LList.nil; term = Lazy.force (LList.nth ctx n); stack}
else {ctx = LList.nil; term = mk_DB l x (n - LList.len ctx); stack}
| {ctx; term = App (f, a, lst); stack; _}, ByName ->
let tl' =
List.rev_map (fun t -> ref {ctx; term = t; stack = []}) (a :: lst)
in
aux pos {ctx; term = f; stack = List.rev_append tl' stack}
| {ctx; term = App (f, a, lst); stack; _}, _ ->
let arg_reduce i t =
ref (aux (i :: pos) {ctx; term = t; stack = []})
in
let tl' = rev_mapi arg_reduce (a :: lst) in
aux pos {ctx; term = f; stack = List.rev_append tl' stack}
| {ctx; term = Const (l, n); stack; _}, _ -> (
let trees = !dtree_finder sg l n in
match find_dtree (List.length stack) trees with
| alg, None -> comb_state_if_AC alg sg st
| alg, Some (ar, tree) -> (
let s1, s2 = split ar stack in
let s1 =
if ar > 1 && Term.is_AC alg then
match s1 with
| t1 :: t2 :: tl ->
let flat = flatten_AC_stack sg n [t1; t2] in
ref {ctx; term = mk_Const l n; stack = flat} :: tl
| _ -> assert false
else s1
in
match gamma_rw sg !selection s1 tree with
| None -> comb_state_if_AC alg sg st
| Some (rn, ctx, term) ->
let st' = {ctx; term; stack = s2} in
log pos rn st st'; aux pos st'))
in
aux
let term_whnf (st_reducer : state_reducer) : term_reducer =
fun pos t -> term_of_state (st_reducer pos (state_of_term t))
let term_snf (st_reducer : state_reducer) : term_reducer =
let rec aux pos t =
match term_whnf st_reducer pos t with
| (Kind | Const _ | DB _ | Type _) as t' -> t'
| App (f, a, lst) ->
mk_App
(aux (0 :: pos) f)
(aux (1 :: pos) a)
(List.mapi (fun p arg -> aux (p :: pos) arg) lst)
| Pi (_, x, a, b) -> mk_Pi dloc x (aux (0 :: pos) a) (aux (1 :: pos) b)
| Lam (_, x, a, b) ->
mk_Lam dloc x (map_opt (aux (0 :: pos)) a) (aux (1 :: pos) b)
in
aux
let reduction cfg sg te =
let log, stop =
match cfg.nb_steps with
| None -> ((fun _ _ _ _ -> ()), fun () -> false)
| Some n ->
let aux = ref n in
((fun _ _ _ _ -> decr aux), fun () -> !aux <= 0)
in
let st_logger p rn stb sta =
log p rn stb sta;
cfg.logger p rn (lazy (term_of_state stb)) (lazy (term_of_state sta))
in
let st_red = logged_state_whnf st_logger stop cfg.strat sg in
let term_red =
match cfg.target with Snf -> term_snf | Whnf -> term_whnf
in
selection := cfg.select;
beta := cfg.beta;
dtree_finder := cfg.finder;
let te' = term_red st_red [] te in
selection := default_cfg.select;
beta := default_cfg.beta;
dtree_finder := default_cfg.finder;
te'
let are_convertible = are_convertible
let constraint_convertibility _ _ = are_convertible
end
module rec Default : S = Make (Default) (Matching.Make (Default))