-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathbuiltins.ml
1923 lines (1765 loc) · 70.6 KB
/
builtins.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
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
open Bwd
open Util
open Postprocess
open Print
open Format
open Core
open Syntax
open Raw
open Reporter
open Notation
open Monad.Ops (Monad.Maybe)
open Printconfig
open Range
module StringSet = Set.Make (String)
(* ********************
Parentheses
******************** *)
let parens = make "parens" Outfix
(* Parentheses are parsed, processed, and printed along with tuples, since their notation overlaps. *)
(* ********************
Let-binding
******************** *)
(* Let-in doesn't need to be right-associative in order to chain, because it is left-closed, but we make it right-associative anyway for consistency. *)
let letin = make "let" (Prefixr No.minus_omega)
let letrec = make "letrec" (Prefixr No.minus_omega)
let process_let :
type n. (string option, n) Bwv.t -> observation list -> Asai.Range.t option -> n check located =
fun ctx obs loc ->
match obs with
| [ Term x; Term ty; Term tm; Term body ] ->
let x = get_var x in
let ty = process ctx ty in
let tm = process ctx tm in
let body = process (Bwv.snoc ctx x) body in
let v : n synth located = { value = Asc (tm, ty); loc = Range.merge_opt ty.loc tm.loc } in
{ value = Synth (Let (x, v, body)); loc }
| [ Term x; Term tm; Term body ] ->
let x = get_var x in
let term = process_synth ctx tm "value of let" in
let body = process (Bwv.snoc ctx x) body in
{ value = Synth (Let (x, term, body)); loc }
| _ -> fatal (Anomaly "invalid notation arguments for let")
let pp_let toks space ppf obs ws =
let rec pp_let toks space ppf obs ws =
let style = style () in
let ws, wslets =
List.fold_left_map
(fun ws tok ->
let wstok, ws = take tok ws in
(ws, (tok, wstok)))
ws toks in
match obs with
| [ x; ty; tm; body ] ->
let wscolon, ws = take Colon ws in
let wscoloneq, ws = take Coloneq ws in
let wsin, ws = take In ws in
taken_last ws;
if style = `Compact then pp_open_hovbox ppf 2;
if true then (
pp_open_hvbox ppf 2;
if true then (
List.iter
(fun (tok, wstok) ->
pp_tok ppf tok;
pp_ws `Nobreak ppf wstok)
wslets;
pp_term `Break ppf x;
pp_tok ppf Colon;
pp_ws `Nobreak ppf wscolon;
pp_term `Break ppf ty;
pp_tok ppf Coloneq;
pp_ws `Nobreak ppf wscoloneq;
pp_term (if style = `Compact then `Nobreak else `Break) ppf tm);
if style = `Compact then pp_close_box ppf ();
pp_tok ppf In);
pp_close_box ppf ();
pp_ws `Break ppf wsin;
pp_let_body space ppf body
| [ x; tm; body ] ->
let wscoloneq, ws = take Coloneq ws in
let wsin, ws = take In ws in
taken_last ws;
if style = `Compact then pp_open_hovbox ppf 2 else pp_open_hvbox ppf 2;
if true then (
List.iter
(fun (tok, wstok) ->
pp_tok ppf tok;
pp_ws `Nobreak ppf wstok)
wslets;
pp_term `Break ppf x;
pp_tok ppf Coloneq;
pp_ws `Nobreak ppf wscoloneq;
pp_term (if style = `Compact then `Nobreak else `Break) ppf tm;
pp_tok ppf In);
pp_close_box ppf ();
pp_ws `Break ppf wsin;
pp_let_body space ppf body
| x :: ty :: tm :: rest when toks = [ Let; Rec ] || toks = [ And ] ->
let wscolon, ws = take Colon ws in
let wscoloneq, ws = take Coloneq ws in
if style = `Compact then pp_open_hovbox ppf 2;
if true then (
pp_open_hvbox ppf 2;
if true then (
List.iter
(fun (tok, wstok) ->
pp_tok ppf tok;
pp_ws `Nobreak ppf wstok)
wslets;
pp_term `Break ppf x;
pp_tok ppf Colon;
pp_ws `Nobreak ppf wscolon;
pp_term `Break ppf ty;
pp_tok ppf Coloneq;
pp_ws `Nobreak ppf wscoloneq;
pp_term (if style = `Compact then `Nobreak else `Break) ppf tm);
if style = `Compact then pp_close_box ppf ());
pp_close_box ppf ();
pp_let [ And ] space ppf rest ws
| _ -> fatal (Anomaly "invalid notation arguments for let")
and pp_let_body space ppf tr =
match tr with
| Term { value = Notn n; _ } when equal (notn n) letin ->
pp_let [ Let ] space ppf (args n) (whitespace n)
| Term { value = Notn n; _ } when equal (notn n) letrec ->
pp_let [ Let; Rec ] space ppf (args n) (whitespace n)
| _ -> pp_term space ppf tr in
pp_open_hvbox ppf 0;
pp_let toks space ppf obs ws;
pp_close_box ppf ()
let () =
set_tree letin
(Closed_entry
(eop Let
(terms
[
(Coloneq, term In (Done_closed letin));
(Colon, term Coloneq (term In (Done_closed letin)));
])));
set_processor letin { process = (fun ctx obs loc _ -> process_let ctx obs loc) };
set_print letin (pp_let [ Let ])
(* ********************
Let rec
******************** *)
type (_, _) letrec_terms =
| Letrec_terms :
('a, 'b, 'ab) tel
* ('c, 'b, 'cb) Fwn.fplus
* ('ab check located, 'cb) Vec.t
* 'ab check located
-> ('c, 'a) letrec_terms
let rec process_letrec :
type c a.
(string option, a) Bwv.t ->
observation list ->
(observation, c) Bwv.t ->
c N.t ->
(c, a) letrec_terms =
fun ctx obs terms c ->
match obs with
| Term x :: Term ty :: tm :: rest ->
let x = get_var x in
let ty = process ctx ty in
let (Letrec_terms (tel, Suc cb, terms, body)) =
process_letrec (Snoc (ctx, x)) rest (Snoc (terms, tm)) (N.suc c) in
Letrec_terms (Ext (x, ty, tel), cb, terms, body)
| [ Term body ] ->
let (Fplus cb) = Fwn.fplus c in
let body = process ctx body in
let terms = Bwv.mmap (fun [ Term t ] -> process ctx t) [ terms ] in
Letrec_terms (Emp, cb, Bwv.prepend cb terms [], body)
| _ -> fatal (Anomaly "invalid notation arguments for let-rec")
let rec letrec_terms () =
term Colon
(term Coloneq (terms [ (And, Lazy (lazy (letrec_terms ()))); (In, Done_closed letrec) ]))
let () =
set_tree letrec (Closed_entry (eop Let (op Rec (letrec_terms ()))));
set_processor letrec
{
process =
(fun ctx obs loc _ ->
let (Letrec_terms (tys, Zero, tms, body)) = process_letrec ctx obs Emp N.zero in
locate (Synth (Letrec (tys, tms, body))) loc);
};
set_print letrec (pp_let [ Let; Rec ])
(* ********************
Ascription
******************** *)
let asc = make "ascription" (Infix No.minus_omega)
let () = set_tree asc (Open_entry (eop Colon (done_open asc)))
let () =
set_processor asc
{
process =
(fun ctx obs loc _ ->
match obs with
| [ Term tm; Term ty ] ->
let tm = process ctx tm in
let ty = process ctx ty in
{ value = Synth (Asc (tm, ty)); loc }
| _ -> fatal (Anomaly "invalid notation arguments for ascription"));
};
set_print asc @@ fun space ppf obs ws ->
match obs with
| [ tm; ty ] ->
let w, ws = take Colon ws in
taken_last ws;
pp_open_box ppf 0;
if true then (
pp_term `Break ppf tm;
pp_tok ppf Colon;
pp_ws `Nobreak ppf w;
pp_term space ppf ty);
pp_close_box ppf ()
| _ -> fatal (Anomaly "invalid notation arguments for ascription")
(* ********************
Telescopes
******************** *)
exception Invalid_telescope
(* Inspect 'xs', expecting it to be a spine of valid bindable local variables or underscores, and produce a list of those variables, consing it onto the accumulator argument 'vars'. *)
let rec process_var_list :
type lt ls rt rs.
(lt, ls, rt, rs) parse located ->
(string option * Whitespace.t list) list ->
(string option * Whitespace.t list) list =
fun { value; loc } vars ->
match value with
| Ident ([ x ], w) -> (Some x, w) :: vars
| Placeholder w -> (None, w) :: vars
| App { fn; arg = { value = Ident ([ x ], w); _ }; _ } -> process_var_list fn ((Some x, w) :: vars)
| App { fn; arg = { value = Placeholder w; _ }; _ } -> process_var_list fn ((None, w) :: vars)
(* There's a choice here: an invalid variable name could still be a valid term, so we could allow for instance (x.y : A) → B to be parsed as a non-dependent function type. But that seems a recipe for confusion. *)
| Ident (name, _) -> fatal ?loc (Invalid_variable name)
| App { arg = { value = Ident (xs, _); loc }; _ } -> fatal ?loc (Invalid_variable xs)
| _ -> raise Invalid_telescope
(* Inspect 'arg', expecting it to be of the form 'x y z : A', and return the list of variables, the type, and the whitespace of the colon. *)
let process_typed_vars :
type lt ls rt rs.
(lt, ls, rt, rs) parse ->
(string option * Whitespace.t list) list * Whitespace.t list * observation =
fun arg ->
match arg with
| Notn n when equal (notn n) asc -> (
match args n with
| [ Term xs; ty ] ->
let wscolon, ws = take Colon (whitespace n) in
taken_last ws;
(process_var_list xs [], wscolon, ty)
| _ -> fatal (Anomaly "invalid notation arguments for telescope"))
| _ -> raise Invalid_telescope
(* ****************************************
Function types (dependent and non)
**************************************** *)
let arrow = make "arrow" (Infixr No.zero)
type arrow_opt = [ `Arrow of Whitespace.t list | `Noarrow | `First ]
type pi_dom =
| Dep of {
wsarrow : arrow_opt;
vars : (string option * Whitespace.t list) list;
ty : observation;
wslparen : Whitespace.t list;
wscolon : Whitespace.t list;
wsrparen : Whitespace.t list;
}
| Nondep of { wsarrow : arrow_opt; ty : observation }
(* Inspect 'doms', expecting it to be of the form (x:A)(y:B) etc, and produce a list of variables with types, prepending that list onto the front of the given accumulation list, with the first one having an arrow attached (before it front) if 'wsarrow' is given. If it isn't of that form, interpret it as the single domain type of a non-dependent function-type and cons it onto the list. *)
let rec get_pi_args :
type lt ls rt rs. arrow_opt -> (lt, ls, rt, rs) parse located -> pi_dom list -> pi_dom list =
fun wsarrow doms accum ->
try
match doms.value with
| Notn n when equal (notn n) parens -> (
match args n with
| [ Term body ] ->
let wslparen, ws = take LParen (whitespace n) in
let wsrparen, ws = take RParen ws in
taken_last ws;
let vars, wscolon, ty = process_typed_vars body.value in
Dep { wsarrow; vars; ty; wslparen; wscolon; wsrparen } :: accum
| _ -> fatal (Anomaly "invalid notation arguments for arrow"))
| App { fn; arg = { value = Notn n; _ }; _ } when equal (notn n) parens -> (
match args n with
| [ Term body ] ->
let wslparen, ws = take LParen (whitespace n) in
let wsrparen, ws = take RParen ws in
taken_last ws;
let vars, wscolon, ty = process_typed_vars body.value in
get_pi_args wsarrow fn
(Dep { wsarrow = `Noarrow; vars; ty; wslparen; wscolon; wsrparen } :: accum)
| _ -> fatal (Anomaly "invalid notation arguments for arrow"))
| _ -> raise Invalid_telescope
with Invalid_telescope -> Nondep { wsarrow; ty = Term doms } :: accum
(* Get all the domains and eventual codomain from a right-associated iterated function-type. *)
let rec get_pi :
type lt ls rt rs.
arrow_opt ->
observation list ->
Whitespace.alist ->
pi_dom list * Whitespace.t list * observation =
fun prev_arr obs ws ->
match obs with
| [ Term doms; Term cod ] ->
let wsarrow, ws = take Arrow ws in
taken_last ws;
let vars, ws, cod =
match cod.value with
| Notn n when equal (notn n) arrow -> get_pi (`Arrow wsarrow) (args n) (whitespace n)
| _ -> ([], wsarrow, Term cod) in
(get_pi_args prev_arr doms vars, ws, cod)
| _ -> fatal (Anomaly "invalid notation arguments for arrow")
(* Given the variables with domains and the codomain of a pi-type, process it into a raw term. *)
let rec process_pi :
type n lt ls rt rs.
(string option, n) Bwv.t -> pi_dom list -> (lt, ls, rt, rs) parse located -> n check located =
fun ctx doms cod ->
match doms with
| [] -> process ctx cod
| Nondep { ty = Term dom; _ } :: doms ->
let cdom = process ctx dom in
let ctx = Bwv.snoc ctx None in
let cod = process_pi ctx doms cod in
let loc = Range.merge_opt cdom.loc cod.loc in
{ value = Synth (Pi (None, cdom, cod)); loc }
| Dep ({ vars = (x, _) :: xs; ty = Term dom; _ } as data) :: doms ->
let cdom = process ctx dom in
let ctx = Bwv.snoc ctx x in
let cod = process_pi ctx (Dep { data with vars = xs } :: doms) cod in
let loc = Range.merge_opt cdom.loc cod.loc in
{ value = Synth (Pi (x, cdom, cod)); loc }
| Dep { vars = []; _ } :: doms -> process_pi ctx doms cod
let () =
set_tree arrow (Open_entry (eop Arrow (done_open arrow)));
set_processor arrow
{
process =
(fun ctx obs _loc ws ->
(* We don't need the loc parameter here, since we can reconstruct the location of each pi-type from its arguments. *)
let doms, _, Term cod = get_pi `First obs ws in
process_pi ctx doms cod);
}
(* Pretty-print the domains of a right-associated iterated function-type *)
let rec pp_doms : formatter -> pi_dom list -> unit =
fun ppf doms ->
match doms with
| [] -> ()
| Dep { wsarrow; vars; ty; wslparen; wscolon; wsrparen } :: doms ->
(match wsarrow with
| `Arrow _ | `Noarrow -> pp_print_space ppf ()
| `First -> ());
pp_open_hbox ppf ();
if true then (
(match wsarrow with
| `Arrow wsarrow ->
pp_tok ppf Arrow;
pp_ws `Nobreak ppf wsarrow
| `Noarrow | `First -> ());
pp_open_hovbox ppf 1;
if true then (
pp_tok ppf LParen;
pp_ws `None ppf wslparen;
List.iter
(fun (x, w) ->
pp_var ppf x;
pp_ws `Break ppf w)
vars;
pp_tok ppf Colon;
pp_ws `Nobreak ppf wscolon;
pp_term `None ppf ty;
pp_tok ppf RParen);
pp_close_box ppf ());
pp_close_box ppf ();
pp_ws `None ppf wsrparen;
pp_doms ppf doms
| Nondep { wsarrow; ty } :: doms ->
(match wsarrow with
| `Arrow wsarrow ->
pp_print_space ppf ();
pp_tok ppf Arrow;
pp_ws `Nobreak ppf wsarrow
| `Noarrow -> pp_print_space ppf ()
| `First -> ());
pp_term `None ppf ty;
pp_doms ppf doms
let () =
set_print arrow @@ fun space ppf obs ws ->
let doms, wsarrow, cod = get_pi `First obs ws in
pp_open_box ppf 1;
if true then (
(* *)
pp_open_hovbox ppf 2;
pp_doms ppf doms;
pp_close_box ppf ();
(* *)
pp_print_custom_break ppf ~fits:("", 1, "") ~breaks:("", 0, " ");
pp_tok ppf Arrow;
pp_ws `Nobreak ppf wsarrow;
pp_term space ppf cod);
pp_close_box ppf ()
(* ********************
Abstraction
******************** *)
(* Abstractions are encoded as a right-associative infix operator that inspects its left-hand argument deeply before compiling it, expecting it to look like an application spine of variables, and then instead binds those variables in its right-hand argument. *)
let abs = make "abstraction" (Infixr No.minus_omega)
let () = set_tree abs (Open_entry (eop Mapsto (done_open abs)))
let cubeabs = make "cube_abstraction" (Infixr No.minus_omega)
let () = set_tree cubeabs (Open_entry (eop DblMapsto (done_open cubeabs)))
type _ extended_ctx =
| Extctx :
('n, 'm, 'nm) N.plus * (Asai.Range.t option, 'm) Bwv.t * (string option, 'nm) Bwv.t
-> 'n extended_ctx
let rec get_vars :
type n lt1 ls1 rt1 rs1.
(string option, n) Bwv.t -> (lt1, ls1, rt1, rs1) parse located -> n extended_ctx =
fun ctx vars ->
match vars.value with
| Ident ([ x ], _) -> Extctx (Suc Zero, Snoc (Emp, vars.loc), Bwv.snoc ctx (Some x))
| Ident (xs, _) -> fatal ?loc:vars.loc (Invalid_variable xs)
| Placeholder _ -> Extctx (Suc Zero, Snoc (Emp, vars.loc), Bwv.snoc ctx None)
| App { fn; arg = { value = Ident ([ x ], _); _ }; _ } ->
let (Extctx (ab, locs, ctx)) = get_vars ctx fn in
Extctx (Suc ab, Snoc (locs, vars.loc), Bwv.snoc ctx (Some x))
| App { arg = { value = Ident (xs, _); loc }; _ } -> fatal ?loc (Invalid_variable xs)
| App { fn; arg = { value = Placeholder _; _ }; _ } ->
let (Extctx (ab, locs, ctx)) = get_vars ctx fn in
Extctx (Suc ab, Snoc (locs, vars.loc), Bwv.snoc ctx None)
| _ -> fatal ?loc:vars.loc Parse_error
let rec raw_lam :
type a b ab.
(string option, ab) Bwv.t ->
[ `Cube | `Normal ] ->
(a, b, ab) N.plus ->
(Asai.Range.t option, b) Bwv.t ->
ab check located ->
a check located =
fun names cube ab locs tm ->
match (ab, locs) with
| Zero, Emp -> tm
| Suc ab, Snoc (locs, loc) ->
let (Snoc (names, x)) = names in
raw_lam names cube ab locs
{ value = Lam ({ value = x; loc }, cube, tm); loc = Range.merge_opt loc tm.loc }
let process_abs cube =
{
process =
(fun ctx obs _loc _ ->
(* The loc argument isn't used here since we can deduce the locations of each lambda by merging its variables with its body. *)
match obs with
| [ Term vars; Term body ] ->
let (Extctx (ab, locs, ctx)) = get_vars ctx vars in
raw_lam ctx cube ab locs (process ctx body)
| _ -> fatal (Anomaly "invalid notation arguments for abstraction"));
}
let pp_abs cube space ppf obs ws =
match obs with
| [ vars; body ] ->
let wsmapsto, ws = take Mapsto ws in
taken_last ws;
pp_open_box ppf 0;
if true then (
pp_open_hovbox ppf 2;
if true then (
pp_term `Nobreak ppf vars;
pp_tok ppf
(match cube with
| `Normal -> Mapsto
| `Cube -> DblMapsto));
pp_close_box ppf ();
pp_ws `Break ppf wsmapsto;
pp_term space ppf body);
pp_close_box ppf ()
| _ -> fatal (Anomaly "invalid notation arguments for abstraction")
let () =
set_processor abs (process_abs `Normal);
set_processor cubeabs (process_abs `Cube);
set_print abs (pp_abs `Normal);
set_print cubeabs (pp_abs `Cube);
set_print_as_case abs (pp_abs `Normal);
set_print_as_case cubeabs (pp_abs `Cube)
(* ********************
The universe
******************** *)
let universe = make "Type" Outfix
let () =
set_tree universe (Closed_entry (eop (Ident [ "Type" ]) (Done_closed universe)));
set_processor universe
{
process =
(fun _ obs loc _ ->
match obs with
| [] -> { value = Synth UU; loc }
| _ -> fatal (Anomaly "invalid notation arguments for Type"));
};
set_print universe @@ fun space ppf obs ws ->
match obs with
| [] ->
let wstype, ws = take (Ident [ "Type" ]) ws in
taken_last ws;
pp_print_string ppf "Type";
pp_ws space ppf wstype
| _ -> fatal (Anomaly (Printf.sprintf "invalid notation arguments for Type: %d" (List.length ws)))
(* ********************
Anonymous tuples
******************** *)
let coloneq = make "coloneq" (Infixr No.minus_omega)
let () =
set_tree coloneq (Open_entry (eop Coloneq (done_open coloneq)));
set_processor coloneq { process = (fun _ _ _ _ -> fatal Parse_error) }
(* The notation for tuples is "( x ≔ M, y ≔ N, z ≔ P )". The parentheses don't conflict with ordinary parentheses, since ≔ and , are not term-forming operators all by themselves. The 0-ary tuple "()" is included, and also doesn't conflict since ordinary parentheses must contain a term. We also allow some of the components of the tuple to be unlabeled, as in "(M, N, P)"; these are assigned to the fields that don't have a corresponding labeled component in the order they appear in the record type. The only thing that's not allowed is an unlabeled 1-tuple "(M)" since that would conflict with ordinary parentheses. (TODO: We could essentially allow that by making the tupling and projection of a 1-ary record type implicit coercions.) *)
let rec tuple_fields () =
Inner
{
empty_branch with
ops = TokMap.singleton RParen (Done_closed parens);
term =
Some
(TokMap.of_list [ (Op ",", Lazy (lazy (tuple_fields ()))); (RParen, Done_closed parens) ]);
}
let () = set_tree parens (Closed_entry (eop LParen (tuple_fields ())))
let rec process_tuple :
type n.
bool ->
(Field.t option, n check located) Abwd.t ->
Field.Set.t ->
(string option, n) Bwv.t ->
observation list ->
Asai.Range.t option ->
Whitespace.alist ->
n check located =
fun first flds found ctx obs loc ws ->
match obs with
| [] -> { value = Raw.Struct (Eta, flds); loc }
| Term { value = Notn n; loc } :: obs when equal (notn n) coloneq -> (
let ws = Option.fold ~none:ws ~some:snd (take_opt (Op ",") ws) in
match args n with
| [ Term { value = Ident ([ x ], _); loc = xloc }; Term tm ] ->
let tm = process ctx tm in
let fld = Field.intern x in
if Field.Set.mem fld found then fatal ?loc:xloc (Duplicate_field_in_tuple fld)
else
process_tuple false (Abwd.add (Some fld) tm flds) (Field.Set.add fld found) ctx obs loc
ws
| [ Term { value = Placeholder _; _ }; Term tm ] ->
let tm = process ctx tm in
process_tuple false (Abwd.add None tm flds) found ctx obs loc ws
| Term x :: _ -> fatal ?loc:x.loc Invalid_field_in_tuple
| _ -> fatal (Anomaly "invalid notation arguments for tuple"))
| [ Term body ] when first && Option.is_none (take_opt (Op ",") ws) -> process ctx body
| Term tm :: obs ->
let tm = process ctx tm in
let ws = Option.fold ~none:ws ~some:snd (take_opt (Op ",") ws) in
process_tuple false (Abwd.add None tm flds) found ctx obs loc ws
let () =
set_processor parens
{
process =
(fun ctx obs loc ws ->
let _, ws = take LParen ws in
process_tuple true Abwd.empty Field.Set.empty ctx obs loc ws);
}
let pp_coloneq space ppf obs ws =
let wscoloneq, ws = take Coloneq ws in
taken_last ws;
match obs with
| [ x; body ] ->
pp_open_hovbox ppf 2;
if true then (
pp_term `Nobreak ppf x;
pp_tok ppf Coloneq;
pp_ws `Break ppf wscoloneq;
pp_term space ppf body);
pp_close_box ppf ()
| _ -> fatal (Anomaly "invalid notation arguments for tuple")
let () = set_print coloneq pp_coloneq
let rec pp_fields : formatter -> observation list -> Whitespace.alist -> Whitespace.alist =
fun ppf obs ws ->
match obs with
| [] -> ws
| tm :: obs -> (
pp_term `None ppf tm;
match obs with
| [] -> ws
| _ ->
let wscomma, ws = take (Op ",") ws in
pp_tok ppf (Op ",");
pp_ws `Break ppf wscomma;
pp_fields ppf obs ws)
let pp_tuple space ppf obs ws =
match obs with
| [] ->
let wslparen, ws = take LParen ws in
let wsrparen, ws = take RParen ws in
taken_last ws;
pp_tok ppf LParen;
pp_ws `None ppf wslparen;
pp_tok ppf RParen;
pp_ws `None ppf wsrparen
| [ body ] ->
let wslparen, ws = take LParen ws in
let wsrparen, ws = take RParen ws in
taken_last ws;
pp_open_hovbox ppf 1;
if true then (
pp_tok ppf LParen;
pp_ws `None ppf wslparen;
pp_term `None ppf body;
pp_tok ppf RParen);
pp_close_box ppf ();
pp_ws space ppf wsrparen
| _ :: _ ->
let style, state = (style (), state ()) in
(match state with
| `Term ->
if style = `Noncompact then pp_open_box ppf 0;
pp_open_hvbox ppf 2
| `Case -> pp_open_vbox ppf 2);
pp_tok ppf LParen;
let wslparen, ws = take LParen ws in
pp_ws (if style = `Compact then `Nobreak else `Break) ppf wslparen;
let ws = pp_fields ppf obs ws in
(if style = `Compact then pp_print_string ppf " "
else
match state with
| `Term ->
pp_close_box ppf ();
pp_print_custom_break ~fits:("", 1, "") ~breaks:(",", 0, "") ppf
| `Case -> pp_print_custom_break ~fits:("", 1, "") ~breaks:(",", -2, "") ppf);
let ws =
match take_opt (Op ",") ws with
| Some (wscomma, ws) ->
pp_ws `None ppf wscomma;
ws
| None -> ws in
pp_tok ppf RParen;
let wsrparen, ws = take RParen ws in
taken_last ws;
pp_ws space ppf wsrparen;
pp_close_box ppf ()
let () =
set_print parens pp_tuple;
set_print_as_case parens pp_tuple
(* ********************
Comatches
******************** *)
let comatch = make "comatch" Outfix
let rec comatch_fields () =
field
(op Mapsto
(terms [ (Op "|", Lazy (lazy (comatch_fields ()))); (RBracket, Done_closed comatch) ]))
let () =
set_tree comatch
(Closed_entry
(eop LBracket
(Inner
{
empty_branch with
ops = TokMap.singleton (Op "|") (comatch_fields ());
field =
Some
(op Mapsto
(terms
[
(Op "|", Lazy (lazy (comatch_fields ()))); (RBracket, Done_closed comatch);
]));
})))
let rec process_comatch :
type n.
(Field.t option, n check located) Abwd.t * Field.Set.t ->
(string option, n) Bwv.t ->
observation list ->
Asai.Range.t option ->
n check located =
fun (flds, found) ctx obs loc ->
match obs with
| [] -> { value = Raw.Struct (Noeta, flds); loc }
| Term { value = Field (x, _); loc } :: Term tm :: obs ->
let tm = process ctx tm in
let fld = Field.intern x in
if Field.Set.mem fld found then fatal ?loc (Duplicate_method_in_comatch fld)
(* Comatches can't have unlabeled fields *)
else process_comatch (Abwd.add (Some fld) tm flds, Field.Set.add fld found) ctx obs loc
| _ :: _ -> fatal (Anomaly "invalid notation arguments for comatch")
let () =
set_processor comatch
{ process = (fun ctx obs loc _ -> process_comatch (Abwd.empty, Field.Set.empty) ctx obs loc) }
(* Comatches will be printed with a different instantiation of the functions that print matches. *)
let empty_co_match = make "empty_co_match" Outfix
let () =
set_tree empty_co_match (Closed_entry (eop LBracket (op RBracket (Done_closed empty_co_match))));
set_processor empty_co_match { process = (fun _ _ loc _ -> { value = Empty_co_match; loc }) }
(* ********************
Matches
******************** *)
(* A dot is used for refutation branches. *)
let dot = make "dot" Outfix
let () =
set_tree dot (Closed_entry (eop Dot (Done_closed dot)));
set_processor dot { process = (fun _ _ _ _ -> fatal Parse_error) }
(* Parsing for implicit matches, explicit (including nondependent) matches, and pattern-matching lambdas shares some code. *)
let implicit_mtch = make "implicit_match" Outfix
let explicit_mtch = make "explicit_match" Outfix
let mtchlam = make "matchlam" Outfix
(* Here are the basic match notation trees. *)
let rec mtch_branches notn bar_ok end_ok comma_ok =
Inner
{
empty_branch with
ops =
TokMap.of_list
((if end_ok then [ (Token.RBracket, Done_closed notn) ] else [])
@ if bar_ok then [ (Op "|", mtch_branches notn false false comma_ok) ] else []);
term =
Some
(TokMap.of_list
((if comma_ok then [ (Token.Op ",", patterns notn) ] else [])
@ [ (Mapsto, body notn comma_ok) ]));
}
and body notn comma_ok =
terms
[
(Op "|", Lazy (lazy (mtch_branches notn false false comma_ok))); (RBracket, Done_closed notn);
]
and patterns notn = terms [ (Token.Op ",", Lazy (lazy (patterns notn))); (Mapsto, body notn true) ]
let rec discriminees () =
terms
[
(LBracket, mtch_branches implicit_mtch true true true); (Op ",", Lazy (lazy (discriminees ())));
]
(* Implicit matches can be multiple and deep matches, with multiple discriminees and multiple patterns. *)
let () = set_tree implicit_mtch (Closed_entry (eop Match (discriminees ())))
(* Empty matches [ ] are not allowed for mtchlam, because they are parsed separately as empty_co_match. *)
let () = set_tree mtchlam (Closed_entry (eop LBracket (mtch_branches mtchlam true false true)))
(* Explicitly typed matches can be deep, but not (yet) multiple. *)
let () =
set_tree explicit_mtch
(Closed_entry
(eop Match
(Inner
{
empty_branch with
term =
Some
(TokMap.singleton Return
(term LBracket (mtch_branches explicit_mtch true true false)));
})))
(* A pattern is either a variable name or a constructor with some number of pattern arguments. *)
module Pattern = struct
type t =
| Var : string option located -> t
| Constr : Constr.t located * (t, 'n) Vec.t located -> t
end
type pattern = Pattern.t
let get_pattern : type lt1 ls1 rt1 rs1. (lt1, ls1, rt1, rs1) parse located -> pattern =
fun pat ->
let rec go :
type n lt1 ls1 rt1 rs1.
(lt1, ls1, rt1, rs1) parse located -> (pattern, n) Vec.t located -> pattern =
fun pat pats ->
match pat.value with
| Ident ([ x ], _) -> (
match pats.value with
| [] -> Var (locate (Some x) pat.loc)
| _ -> fatal ?loc:pat.loc Parse_error)
| Ident (xs, _) -> fatal ?loc:pat.loc (Invalid_variable xs)
| Placeholder _ -> (
match pats.value with
| [] -> Var (locate None pat.loc)
| _ -> fatal ?loc:pat.loc Parse_error)
| Constr (c, _) -> Constr (locate (Constr.intern c) pat.loc, pats)
| App { fn; arg; _ } ->
go fn
(locate
(go arg (locate Vec.[] arg.loc) :: pats.value : (pattern, n Fwn.suc) Vec.t)
pats.loc)
| Notn n when equal (notn n) parens -> (
match args n with
| [ Term arg ] -> go arg pats
| _ -> fatal ?loc:pat.loc Parse_error)
| _ -> fatal ?loc:pat.loc Parse_error in
go pat (locate Vec.[] pat.loc)
(* For parsing matches, we use a special kind of scope that labels all the variables with integers (De Bruijn levels) in addition to possible strings. *)
module Matchscope : sig
type 'a t
val lookup_num : int -> 'a t -> 'a N.index option
val ext : 'a t -> string option -> 'a N.suc t
val last_num : 'a t -> int
val exts : ('a, 'm, 'am) Fwn.bplus -> 'a t -> 'am t * (int, 'm) Vec.t
val make : (string option, 'a) Bwv.t -> 'a t
val names : 'a t -> (string option, 'a) Bwv.t
val give_name : int -> string option -> 'a t -> 'a t
end = struct
type _ t =
| Matchscope :
(string option, 'a) Bwv.t * ('a, 'b, 'ab) N.plus * (string option * int, 'b) Bwv.t * int
-> 'ab t
let rec lookup_num : type a. int -> a t -> a N.index option =
fun i -> function
| Matchscope (_, Zero, Emp, _) -> None
| Matchscope (base, Suc ab, Snoc (scope, (_, j)), n) -> (
if i = j then Some Top
else
match lookup_num i (Matchscope (base, ab, scope, n - 1)) with
| Some k -> Some (Pop k)
| None -> None)
let check_duplicates : type b. (string option * int, b) Bwv.t -> string option -> unit =
fun scope name ->
match name with
| Some name -> (
match Bwv.find_opt (fun (y, _) -> y = Some name) scope with
| Some _ -> fatal (Duplicate_pattern_variable name)
| None -> ())
| None -> ()
let ext : type a. a t -> string option -> a N.suc t =
fun (Matchscope (base, ab, scope, i)) name ->
check_duplicates scope name;
Matchscope (base, Suc ab, Snoc (scope, (name, i)), i + 1)
let last_num : type a. a t -> int = fun (Matchscope (_, _, _, i)) -> i - 1
let rec exts : type a m am. (a, m, am) Fwn.bplus -> a t -> am t * (int, m) Vec.t =
fun am scope ->
match (am, scope) with
| Zero, _ -> (scope, [])
| Suc am, Matchscope (base, ab, scope, i) ->
let newscope, levels = exts am (Matchscope (base, Suc ab, Snoc (scope, (None, i)), i + 1)) in
(newscope, i :: levels)
let make : type a. (string option, a) Bwv.t -> a t = fun base -> Matchscope (base, Zero, Emp, 0)
let names : type a. a t -> (string option, a) Bwv.t =
fun (Matchscope (base, ab, scope, _)) -> Bwv.bappend ab base (Bwv.map fst scope)
let give_name : type a. int -> string option -> a t -> a t =
fun i x (Matchscope (base, ab, scope, n)) ->
check_duplicates scope x;
Matchscope
( base,
ab,
Bwv.map
(fun (y, j) ->
if i = j then
match y with
| None -> (x, j)
| Some _ -> fatal (Anomaly "renaming already-named pattern variable")
else (y, j))
scope,
n )
end
(* An ('a, 'n) branch is a scope of 'a variables, a vector of 'n patterns, and a body to be parsed in the scope extended by the variables in those patterns. At the beginning, all the branches start out with the same scope of variables, but as we proceed they can get different ones. All the branches in a single invocation of process_match have the same *number* of variables in scope, but different branches could have different *names* for those variables. *)
type ('a, 'n) branch = 'a Matchscope.t * (pattern, 'n) Vec.t * observation
(* An ('a, 'm, 'n) cbranch is a branch, with scope of 'a variables, that starts with a constructor (unspecified) having 'm arguments and proceeds with 'n other patterns. *)
type ('a, 'm, 'n) cbranch =
'a Matchscope.t * (pattern, 'm) Vec.t located * (pattern, 'n) Vec.t * observation
(* An ('a, 'n) cbranches is a Bwd of branches that start with the same constructor, which always has the same number of arguments, along with a scope of 'a variables common to those branches. *)
type (_, _) cbranches =
| CBranches : Constr.t located * ('a, 'm, 'n) cbranch Bwd.t -> ('a, 'n) cbranches
let process_ix : type a. a Matchscope.t -> int -> a synth located =
fun ctx i ->
match Matchscope.lookup_num i ctx with
| Some k -> unlocated (Raw.Var (k, None))
| None -> fatal (Anomaly "invalid parse-level in processing match")
let process_obs_or_ix : type a. a Matchscope.t -> (observation, int) Either.t -> a synth located =
fun ctx -> function
| Left (Term x) -> process_synth (Matchscope.names ctx) x "discriminee of match"
| Right i -> (
match Matchscope.lookup_num i ctx with
| Some k -> unlocated (Raw.Var (k, None))
| None -> fatal (Anomaly "invalid parse-level in processing match"))
(* Given a scope of 'a variables, a vector of 'n not-yet-processed discriminees or previous match variables, and a list of branches with 'n patterns each, compile them into a nested match. The scope given as an argument to this function is used only for the discriminees; it is the original scope extended by unnamed variables (since the discriminees can't actually depend on the pattern variables). The scopes used for the branches, which also include pattern variables, are stored in the branch data structures. *)
let rec process_branches :
type a n.
a Matchscope.t ->
((observation, int) Either.t, n) Vec.t ->
int Bwd.t ->
(a, n) branch list ->
Asai.Range.t option ->
[ `Implicit | `Explicit of observation | `Nondep of int located ] ->
a check located =
fun xctx xs seen branches loc sort ->
match branches with
(* An empty match, having no branches, compiles to a refutation that will check by looking for any discriminee with an empty type. This can only happen as the top-level call, so 'seen' should be empty and we really can just take all the discriminees. *)
| [] -> (
let tms = Vec.to_list_map (process_obs_or_ix xctx) xs in
match (sort, xs) with
| `Implicit, _ -> locate (Refute (tms, `Implicit)) loc
| `Explicit (Term motive), [ Left (Term tm) ] -> (
let ctx = Matchscope.names xctx in
let sort = `Explicit (process ctx motive) in
match process ctx tm with
| { value = Synth tm; loc } ->
let refutables = { refutables = (fun _ -> []) } in
locate (Synth (Match { tm = locate tm loc; sort; branches = Emp; refutables })) loc
| _ -> fatal (Nonsynthesizing "motive of explicit match"))
| `Nondep i, [ Left (Term tm) ] -> (
let ctx = Matchscope.names xctx in
let sort = `Nondep i in
match process ctx tm with
| { value = Synth tm; loc } ->
let refutables = { refutables = (fun _ -> []) } in
locate (Synth (Match { tm = locate tm loc; sort; branches = Emp; refutables })) loc
| _ -> fatal (Nonsynthesizing "motive of explicit match"))
| _ -> fatal (Anomaly "multiple match with return-type"))
(* If there are no patterns left, and hence no discriminees either, we require that there must be exactly one branch. *)
| (_, [], _) :: _ :: _ -> fatal No_remaining_patterns
(* If that one remaining branch is a refutation, we refute all the "seen" terms or variables. *)
| [ (_, [], Term { value = Notn n; loc }) ] when equal (notn n) dot ->
let [] = xs in
let tms = Bwd_extra.to_list_map (process_ix xctx) seen in